From: Svjatoslav Agejenko Date: Sun, 20 Mar 2016 20:14:30 +0000 (+0200) Subject: code cleanup and formatting X-Git-Tag: meviz-1.0~9 X-Git-Url: http://www2.svjatoslav.eu/gitweb/?a=commitdiff_plain;h=1b742640af99284aae1cd10c259254137316ba7c;p=meviz.git code cleanup and formatting --- diff --git a/doc/index.html b/doc/index.html index 0307371..166eebc 100644 --- a/doc/index.html +++ b/doc/index.html @@ -1,25 +1,26 @@ - -MeWiz + + MeWiz -

MeWiz - Media Wizard

- Download -    - Online homepage -    - Other applications hosted on svjatoslav.eu +

MeWiz - Media Wizard

+Download +   +Online homepage +   +Other applications hosted on svjatoslav.eu
 Program author:
     Svjatoslav Agejenko
     Homepage: http://svjatoslav.eu
     Email: svjatoslav@svjatoslav.eu
 
-This software is distributed under GNU GENERAL PUBLIC LICENSE Version 2.
+This software is distributed under GNU GENERAL PUBLIC LICENSE Version
+        2.
 
 

Introdution

diff --git a/pom.xml b/pom.xml index 9886233..7b104ea 100644 --- a/pom.xml +++ b/pom.xml @@ -1,146 +1,146 @@ - - 4.0.0 - eu.svjatoslav - meviz - 1.0-SNAPSHOT - jar - meviz - media wizard - - - svjatoslav.eu - http://svjatoslav.eu - - - - - eu.svjatoslav - svjatoslavcommons - 1.5-SNAPSHOT - - - - log4j - log4j - 1.2.16 - - - - - - - - maven-assembly-plugin - - - - eu.svjatoslav.meviz.Main - - - - jar-with-dependencies - - - - - - - package-jar-with-dependencies - package - - single - - - - jar-with-dependencies - - - - eu.svjatoslav.meviz.Main - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - UTF-8 - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - - attach-javadocs - - jar - - - - - - - - - org.apache.maven.wagon - wagon-ssh-external - 2.6 - - - - - - - svjatoslav.eu - svjatoslav.eu - scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven - - - svjatoslav.eu - svjatoslav.eu - scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven - - - - - - svjatoslav.eu - Svjatoslav repository - http://www2.svjatoslav.eu/maven/ - - - true - - - true - - - + + 4.0.0 + eu.svjatoslav + meviz + 1.0-SNAPSHOT + jar + meviz + media wizard + + + svjatoslav.eu + http://svjatoslav.eu + + + + + eu.svjatoslav + svjatoslavcommons + 1.5-SNAPSHOT + + + + log4j + log4j + 1.2.16 + + + + + + + + maven-assembly-plugin + + + + eu.svjatoslav.meviz.Main + + + + jar-with-dependencies + + + + + + + package-jar-with-dependencies + package + + single + + + + jar-with-dependencies + + + + eu.svjatoslav.meviz.Main + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + UTF-8 + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + + attach-javadocs + + jar + + + + + + + + + org.apache.maven.wagon + wagon-ssh-external + 2.6 + + + + + + + svjatoslav.eu + svjatoslav.eu + scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven + + + svjatoslav.eu + svjatoslav.eu + scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven + + + + + + svjatoslav.eu + Svjatoslav repository + http://www2.svjatoslav.eu/maven/ + + + true + + + true + + + diff --git a/src/main/java/eu/svjatoslav/meviz/Main.java b/src/main/java/eu/svjatoslav/meviz/Main.java index a629d1b..9fc8f98 100755 --- a/src/main/java/eu/svjatoslav/meviz/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/Main.java @@ -9,88 +9,87 @@ package eu.svjatoslav.meviz; -import java.util.ArrayList; - import eu.svjatoslav.meviz.encoder.Encoder; +import java.util.ArrayList; + public class Main { - public static ArrayList modules; + public static ArrayList modules; - public static String[] getRemainingOptions(final String[] options) { - final String[] remainingOptions = new String[options.length - 1]; + public static String[] getRemainingOptions(final String[] options) { + final String[] remainingOptions = new String[options.length - 1]; - for (int i = 1; i < options.length; i++) - remainingOptions[i - 1] = options[i]; + System.arraycopy(options, 1, remainingOptions, 0, options.length - 1); - return remainingOptions; - }; + return remainingOptions; + } - public static void initModules() { - modules = new ArrayList(); + public static void initModules() { + modules = new ArrayList(); - modules.add(new Encoder()); - modules.add(new eu.svjatoslav.meviz.htmlindexer.Main()); - modules.add(new eu.svjatoslav.meviz.renamer.Main()); - modules.add(new eu.svjatoslav.meviz.grabmemcard.Main()); - modules.add(new eu.svjatoslav.meviz.texttruncate.Main()); - modules.add(new eu.svjatoslav.meviz.textsplitter.Main()); - modules.add(new eu.svjatoslav.meviz.bomremove.Main()); - modules.add(new eu.svjatoslav.meviz.replace.Main()); - } + modules.add(new Encoder()); + modules.add(new eu.svjatoslav.meviz.htmlindexer.Main()); + modules.add(new eu.svjatoslav.meviz.renamer.Main()); + modules.add(new eu.svjatoslav.meviz.grabmemcard.Main()); + modules.add(new eu.svjatoslav.meviz.texttruncate.Main()); + modules.add(new eu.svjatoslav.meviz.textsplitter.Main()); + modules.add(new eu.svjatoslav.meviz.bomremove.Main()); + modules.add(new eu.svjatoslav.meviz.replace.Main()); + } - public static void main(final String[] args) throws Exception { + public static void main(final String[] args) throws Exception { - initModules(); + initModules(); - if (args.length < 1) - showHelp(); - else if (args[0].equals("help")) { - if (args.length != 2) - showHelp(); - else { + if (args.length < 1) + showHelp(); + else if (args[0].equals("help")) { + if (args.length != 2) + showHelp(); + else { - for (final Module module : modules) - if (args[1].equals(module.getModuleCommand())) { - module.showCommandlineHelp(); - return; - } + for (final Module module : modules) + if (args[1].equals(module.getModuleCommand())) { + module.showCommandlineHelp(); + return; + } - System.out.println("Error: unrecognized module by name:" - + args[1] + "\n"); - showHelp(); + System.out.println("Error: unrecognized module by name:" + + args[1] + "\n"); + showHelp(); - } - } else { + } + } else { - for (final Module module : modules) - if (args[0].equals(module.getModuleCommand())) { - module.run(getRemainingOptions(args)); - return; - } + for (final Module module : modules) + if (args[0].equals(module.getModuleCommand())) { + module.run(getRemainingOptions(args)); + return; + } - System.out.println("Error: unrecognized commandline option:" - + args[0] + "\n"); - showHelp(); - } + System.out.println("Error: unrecognized commandline option:" + + args[0] + "\n"); + showHelp(); + } - } + } - public static void showHelp() { - final StringBuffer buffer = new StringBuffer(); + public static void showHelp() { + final StringBuilder buffer = new StringBuilder(); - buffer.append("Commandline options: \n" - + "help\n show this help screen \n\n"); + buffer.append("Commandline options: \n" + + "help\n show this help screen \n\n"); - buffer.append("help \n show module specific help screen\n\n"); + buffer.append("help \n show module specific help screen\n\n"); - buffer.append("Available modules:\n\n"); + buffer.append("Available modules:\n\n"); - for (final Module module : modules) { - buffer.append(module.getModuleCommand() + "\n"); - buffer.append(" " + module.getDescription() + "\n\n"); - } + for (final Module module : modules) { + buffer.append(module.getModuleCommand() + "\n"); + buffer.append(" " + module.getDescription() + "\n\n"); + } - System.out.println(buffer.toString()); - } + System.out.println(buffer.toString()); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/Module.java b/src/main/java/eu/svjatoslav/meviz/Module.java index 026ec6a..73642b0 100755 --- a/src/main/java/eu/svjatoslav/meviz/Module.java +++ b/src/main/java/eu/svjatoslav/meviz/Module.java @@ -11,12 +11,12 @@ package eu.svjatoslav.meviz; public interface Module { - public String getDescription(); + String getDescription(); - public String getModuleCommand(); + String getModuleCommand(); - public void run(String args[]) throws Exception; + void run(String args[]) throws Exception; - public void showCommandlineHelp(); + void showCommandlineHelp(); } diff --git a/src/main/java/eu/svjatoslav/meviz/bomremove/BomStrippingOptions.java b/src/main/java/eu/svjatoslav/meviz/bomremove/BomStrippingOptions.java index a97147d..491f64f 100755 --- a/src/main/java/eu/svjatoslav/meviz/bomremove/BomStrippingOptions.java +++ b/src/main/java/eu/svjatoslav/meviz/bomremove/BomStrippingOptions.java @@ -14,10 +14,10 @@ import java.util.ArrayList; public class BomStrippingOptions { - public ArrayList inputPatterns = new ArrayList(); + public ArrayList inputPatterns = new ArrayList(); - public boolean recursive = false; + public boolean recursive = false; - public File targetDirectory; + public File targetDirectory; } diff --git a/src/main/java/eu/svjatoslav/meviz/bomremove/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/bomremove/CommandlineHandler.java index 46750a3..367a7f2 100755 --- a/src/main/java/eu/svjatoslav/meviz/bomremove/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/bomremove/CommandlineHandler.java @@ -9,48 +9,48 @@ package eu.svjatoslav.meviz.bomremove; -import java.io.File; - import eu.svjatoslav.commons.commandline.parameterparser.Parser; import eu.svjatoslav.commons.commandline.parameterparser.parameter.DirectoryParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.NullParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameters; +import java.io.File; + public class CommandlineHandler { - Parser parser = new Parser(); + Parser parser = new Parser(); - NullParameter recursiveParameter = parser.add( - new NullParameter("Enable recursive mode.")).addAliases("-r", - "--recursive"); + NullParameter recursiveParameter = parser.add( + new NullParameter("Enable recursive mode.")).addAliases("-r", + "--recursive"); - StringParameters inputPatternParameter = parser.add( - new StringParameters("File input pattern.")).addAliases("-i", - "--input-pattern"); + StringParameters inputPatternParameter = parser.add( + new StringParameters("File input pattern.")).addAliases("-i", + "--input-pattern"); - DirectoryParameter workingDirectoryParameter = parser - .add(new DirectoryParameter("Working directory.")) - .addAliases("-w", "--working-directory").mustExist(); + DirectoryParameter workingDirectoryParameter = parser + .add(new DirectoryParameter("Working directory.")) + .addAliases("-w", "--working-directory").mustExist(); - public BomStrippingOptions parseCommandlineArguments(final String[] args) { + public BomStrippingOptions parseCommandlineArguments(final String[] args) { - final BomStrippingOptions options = new BomStrippingOptions(); + final BomStrippingOptions options = new BomStrippingOptions(); - if (!parser.parse(args)) - return null; + if (!parser.parse(args)) + return null; - if (recursiveParameter.isParameterSpecified()) - options.recursive = true; + if (recursiveParameter.isParameterSpecified()) + options.recursive = true; - if (workingDirectoryParameter.isParameterSpecified()) - options.targetDirectory = workingDirectoryParameter.getValue(); - else - options.targetDirectory = new File(System.getProperty("user.dir")); + if (workingDirectoryParameter.isParameterSpecified()) + options.targetDirectory = workingDirectoryParameter.getValue(); + else + options.targetDirectory = new File(System.getProperty("user.dir")); - // TODO: add support for multiple input patterns - if (inputPatternParameter.isParameterSpecified()) - options.inputPatterns.addAll(inputPatternParameter.getValue()); + // TODO: add support for multiple input patterns + if (inputPatternParameter.isParameterSpecified()) + options.inputPatterns.addAll(inputPatternParameter.getValue()); - return options; - } + return options; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/bomremove/Main.java b/src/main/java/eu/svjatoslav/meviz/bomremove/Main.java index 201c723..d792bb6 100755 --- a/src/main/java/eu/svjatoslav/meviz/bomremove/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/bomremove/Main.java @@ -9,125 +9,124 @@ package eu.svjatoslav.meviz.bomremove; +import eu.svjatoslav.commons.file.IOHelper; +import eu.svjatoslav.commons.string.WildCardMatcher; +import eu.svjatoslav.meviz.Module; + import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; -import eu.svjatoslav.commons.file.IOHelper; -import eu.svjatoslav.commons.string.WildCardMatcher; -import eu.svjatoslav.meviz.Module; - public class Main implements Module { - byte[] bomHeader = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf }; + byte[] bomHeader = new byte[]{(byte) 0xef, (byte) 0xbb, (byte) 0xbf}; - CommandlineHandler commandlineHandler = new CommandlineHandler(); + CommandlineHandler commandlineHandler = new CommandlineHandler(); - BomStrippingOptions options; + BomStrippingOptions options; - public boolean contains(final byte[] header, final byte[] patternToSeek) { + public boolean contains(final byte[] header, final byte[] patternToSeek) { - for (int i = 0; i < patternToSeek.length; i++) - if (header[i] != patternToSeek[i]) - return false; + for (int i = 0; i < patternToSeek.length; i++) + if (header[i] != patternToSeek[i]) + return false; - return true; - } + return true; + } - public boolean fileContainsHeader(final File file) - throws FileNotFoundException, IOException { + public boolean fileContainsHeader(final File file) + throws IOException { - final FileInputStream fileInputStream = new FileInputStream(file); + final FileInputStream fileInputStream = new FileInputStream(file); - final byte[] currentFileHeader = new byte[bomHeader.length]; - fileInputStream.read(currentFileHeader); - fileInputStream.close(); + final byte[] currentFileHeader = new byte[bomHeader.length]; + fileInputStream.read(currentFileHeader); + fileInputStream.close(); - return contains(currentFileHeader, bomHeader); - } + return contains(currentFileHeader, bomHeader); + } - public boolean fileMatchesInputPattern(final File file) { - final String fileName = file.getName().toLowerCase(); + public boolean fileMatchesInputPattern(final File file) { + final String fileName = file.getName().toLowerCase(); - for (final String inputPattern : options.inputPatterns) - if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) - return true; + for (final String inputPattern : options.inputPatterns) + if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) + return true; - return false; - } + return false; + } - @Override - public String getDescription() { - return "Remove byte order mark (bom) from UTF text files if they are present."; - } + @Override + public String getDescription() { + return "Remove byte order mark (bom) from UTF text files if they are present."; + } - @Override - public String getModuleCommand() { - return "stripbom"; - } + @Override + public String getModuleCommand() { + return "stripbom"; + } - public void processDirectory(final File directory) { + public void processDirectory(final File directory) { - for (final File subFile : directory.listFiles()) - if (subFile.isDirectory()) { - if (options.recursive) - processDirectory(subFile); - } else if (fileMatchesInputPattern(subFile)) - try { - processFile(subFile); - } catch (final IOException exception) { - System.out.println("Error processing file: " - + subFile.getAbsolutePath()); - System.out.println(" exception: " - + exception.getMessage()); - } + for (final File subFile : directory.listFiles()) + if (subFile.isDirectory()) { + if (options.recursive) + processDirectory(subFile); + } else if (fileMatchesInputPattern(subFile)) + try { + processFile(subFile); + } catch (final IOException exception) { + System.out.println("Error processing file: " + + subFile.getAbsolutePath()); + System.out.println(" exception: " + + exception.getMessage()); + } - } + } - public void processFile(final File file) throws IOException { + public void processFile(final File file) throws IOException { - if (file.length() < bomHeader.length) - return; + if (file.length() < bomHeader.length) + return; - if (!fileContainsHeader(file)) - return; + if (!fileContainsHeader(file)) + return; - System.out.println("Removing BOM from: " + file.getAbsolutePath()); - stripFileFromHeader(file); - } + System.out.println("Removing BOM from: " + file.getAbsolutePath()); + stripFileFromHeader(file); + } - @Override - public void run(final String[] args) throws IOException { + @Override + public void run(final String[] args) throws IOException { - options = commandlineHandler.parseCommandlineArguments(args); + options = commandlineHandler.parseCommandlineArguments(args); - if (options == null) { - showCommandlineHelp(); - return; - } + if (options == null) { + showCommandlineHelp(); + return; + } - processDirectory(options.targetDirectory); + processDirectory(options.targetDirectory); - } + } - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - } + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + } - public void stripFileFromHeader(final File file) - throws FileNotFoundException, IOException { - // read entire file - final byte[] fileContents = IOHelper.getFileContents(file); + public void stripFileFromHeader(final File file) + throws IOException { + // read entire file + final byte[] fileContents = IOHelper.getFileContents(file); - // remove BOM header form file - final byte[] newFileContents = Arrays.copyOfRange(fileContents, - bomHeader.length, fileContents.length); + // remove BOM header form file + final byte[] newFileContents = Arrays.copyOfRange(fileContents, + bomHeader.length, fileContents.length); - // overwrite file with new contents - IOHelper.saveToFile(file, newFileContents); - } + // overwrite file with new contents + IOHelper.saveToFile(file, newFileContents); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/BitrateParameter.java b/src/main/java/eu/svjatoslav/meviz/encoder/BitrateParameter.java index ec88b61..30a6712 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/BitrateParameter.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/BitrateParameter.java @@ -14,32 +14,32 @@ import eu.svjatoslav.commons.commandline.parameterparser.Parameter; public class BitrateParameter extends Parameter { - static public enum bitrate { - NONE, LOW, MEDIUM, HIGH, COPY - } - - public BitrateParameter(final String description) { - super(description, ArgumentCount.SINGLE); - } - - @Override - public String describeFormat() { - return "Target bitrate [NONE / LOW / MEDIUM / HIGH / COPY ]"; - }; - - @Override - public bitrate getValue() { - return bitrate.valueOf(arguments.get(0).toUpperCase()); - } - - @Override - public boolean validate(final String value) { - try { - bitrate.valueOf(value.toUpperCase()); - } catch (final IllegalArgumentException exception) { - return false; - } - - return true; - } + public BitrateParameter(final String description) { + super(description, ArgumentCount.SINGLE); + } + + @Override + public String describeFormat() { + return "Target bitrate [NONE / LOW / MEDIUM / HIGH / COPY ]"; + } + + @Override + public bitrate getValue() { + return bitrate.valueOf(arguments.get(0).toUpperCase()); + } + + @Override + public boolean validate(final String value) { + try { + bitrate.valueOf(value.toUpperCase()); + } catch (final IllegalArgumentException exception) { + return false; + } + + return true; + } + + public enum bitrate { + NONE, LOW, MEDIUM, HIGH, COPY + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/encoder/CommandlineHandler.java index e83b4b8..dc1601d 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/CommandlineHandler.java @@ -17,74 +17,74 @@ import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParamet public class CommandlineHandler { - Parser parser = new Parser(); + Parser parser = new Parser(); - StringParameters outputFormatParameter = parser.add(new StringParameters("Encoding output format.")) - .addAliases("-o", "--output-format").setMandatory(); + StringParameters outputFormatParameter = parser.add(new StringParameters("Encoding output format.")) + .addAliases("-o", "--output-format").setMandatory(); - IntegerParameter targetFramerate = parser - .add(new IntegerParameter("Target framerate.").addAliases("-f", "--target-framerate")); + IntegerParameter targetFramerate = parser + .add(new IntegerParameter("Target framerate.").addAliases("-f", "--target-framerate")); - NullParameter deinterlaceParameter = parser.add(new NullParameter("Deinterlace video.")).addAliases("-d", - "--deinterlace"); + NullParameter deinterlaceParameter = parser.add(new NullParameter("Deinterlace video.")).addAliases("-d", + "--deinterlace"); - NullParameter testParameter = parser.add(new NullParameter("Simulate file encoding.")).addAliases("-t", "--test"); + NullParameter testParameter = parser.add(new NullParameter("Simulate file encoding.")).addAliases("-t", "--test"); - NullParameter recursiveParameter = parser.add(new NullParameter("Enable recursive mode.")).addAliases("-r", - "--recursive"); + NullParameter recursiveParameter = parser.add(new NullParameter("Enable recursive mode.")).addAliases("-r", + "--recursive"); - NullParameter forPortableParameter = parser.add(new NullParameter("Encode for portable player.")).addAliases("-p", - "--portable"); + NullParameter forPortableParameter = parser.add(new NullParameter("Encode for portable player.")).addAliases("-p", + "--portable"); - StringParameters inputPatternParameter = parser.add(new StringParameters("File input pattern.")) - .addAliases("-i", "--input-pattern").setMandatory(); + StringParameters inputPatternParameter = parser.add(new StringParameters("File input pattern.")) + .addAliases("-i", "--input-pattern").setMandatory(); - DirectoryParameter workingDirectoryParameter = parser.add(new DirectoryParameter("Working directory.")) - .addAliases("-w", "--working-directory").mustExist(); + DirectoryParameter workingDirectoryParameter = parser.add(new DirectoryParameter("Working directory.")) + .addAliases("-w", "--working-directory").mustExist(); - BitrateParameter videoBitrateParameter = parser.add(new BitrateParameter("Video bitrate")).addAliases("-v", - "--video-bitrate"); + BitrateParameter videoBitrateParameter = parser.add(new BitrateParameter("Video bitrate")).addAliases("-v", + "--video-bitrate"); - BitrateParameter audioBitrateParameter = parser.add(new BitrateParameter("Audio bitrate")).addAliases("-a", - "--audio-bitrate"); + BitrateParameter audioBitrateParameter = parser.add(new BitrateParameter("Audio bitrate")).addAliases("-a", + "--audio-bitrate"); - /** - * @return {@link EncodingOptions} if commandline arguments were - * successfully parsed, or null if parsing error - * occurred. - */ - public EncodingOptions parseCommandlineArguments(final String[] args) { + /** + * @return {@link EncodingOptions} if commandline arguments were + * successfully parsed, or null if parsing error + * occurred. + */ + public EncodingOptions parseCommandlineArguments(final String[] args) { - final EncodingOptions options = new EncodingOptions(); + final EncodingOptions options = new EncodingOptions(); - parser.parse(args); + parser.parse(args); - options.setRecursive(recursiveParameter.isParameterSpecified()); + options.setRecursive(recursiveParameter.isParameterSpecified()); - options.setDeinterlace(deinterlaceParameter.isParameterSpecified()); + options.setDeinterlace(deinterlaceParameter.isParameterSpecified()); - options.setTestOnly(testParameter.isParameterSpecified()); + options.setTestOnly(testParameter.isParameterSpecified()); - if (outputFormatParameter.isParameterSpecified()) - options.getOutputFormats().addAll(outputFormatParameter.getValue()); + if (outputFormatParameter.isParameterSpecified()) + options.getOutputFormats().addAll(outputFormatParameter.getValue()); - if (targetFramerate.isParameterSpecified()) - options.setTargetFps(targetFramerate.getValue()); + if (targetFramerate.isParameterSpecified()) + options.setTargetFps(targetFramerate.getValue()); - if (workingDirectoryParameter.isParameterSpecified()) - options.setWorkingDirectory(workingDirectoryParameter.getValue()); + if (workingDirectoryParameter.isParameterSpecified()) + options.setWorkingDirectory(workingDirectoryParameter.getValue()); - if (inputPatternParameter.isParameterSpecified()) - options.getInputPatterns().addAll(inputPatternParameter.getValue()); + if (inputPatternParameter.isParameterSpecified()) + options.getInputPatterns().addAll(inputPatternParameter.getValue()); - options.setForPortablePlayer(forPortableParameter.isParameterSpecified()); + options.setForPortablePlayer(forPortableParameter.isParameterSpecified()); - if (videoBitrateParameter.isParameterSpecified()) - options.setVideoBitrate(videoBitrateParameter.getValue()); + if (videoBitrateParameter.isParameterSpecified()) + options.setVideoBitrate(videoBitrateParameter.getValue()); - if (audioBitrateParameter.isParameterSpecified()) - options.setAudioBitrate(audioBitrateParameter.getValue()); + if (audioBitrateParameter.isParameterSpecified()) + options.setAudioBitrate(audioBitrateParameter.getValue()); - return options; - } + return options; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/Encoder.java b/src/main/java/eu/svjatoslav/meviz/encoder/Encoder.java index 1ec9d03..fda023e 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/Encoder.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/Encoder.java @@ -9,169 +9,165 @@ package eu.svjatoslav.meviz.encoder; -import java.io.File; -import java.util.List; - import eu.svjatoslav.commons.file.FilePathParser; import eu.svjatoslav.commons.string.WildCardMatcher; import eu.svjatoslav.meviz.Module; import eu.svjatoslav.meviz.encoder.converters.AbstractConverter; +import java.io.File; +import java.util.List; + public class Encoder implements Module { - public FormatsRegistry encoderRegistry = new FormatsRegistry(); - - public EncodingOptions encodingOptions; - - public EncodingPlan encodingPlan; - - CommandlineHandler commandlineHandler = new CommandlineHandler(); - - /** - * Generate encoding plan - * - * @param sourceFile - * Source directory of file - */ - public void compileEncodingPlan(final File sourceFile) { - if (!sourceFile.exists()) { - System.out.println("Error: file \"" + sourceFile.getAbsolutePath() - + "\" does not exist."); - return; - } - - if (sourceFile.isDirectory()) { - // handle directory - for (final File subFile : sourceFile.listFiles()) - if (subFile.isDirectory()) { - if (encodingOptions.isRecursive()) - compileEncodingPlan(subFile); - } else - compileEncodingPlan(subFile); - } else if (sourceFile.isFile()) - if (fileMatchesInputPattern(sourceFile)) { - - // System.out.println("Processing file: " + - // file.getAbsolutePath()); - - final String sourceFileExtension = FilePathParser - .getFileExtension(sourceFile); - - // encode source file into every desired target format - for (final String targetFormat : encodingOptions.getOutputFormats()) { - - // construct target file - final File targetFile = getTargetFile(sourceFile, - targetFormat); - - // System.out.println("target path: " + - // targetFilePath.toString()); - - if (!targetFile.exists()) { - - final List formats = encoderRegistry - .getEncoders(sourceFileExtension, targetFormat); - - if (formats.size() == 0) - System.out - .println("Error: no encoders found to convert file \"" - + sourceFile.getAbsolutePath() - + "\" into " - + targetFormat - + " format."); - else if (formats.size() > 1) - System.out - .println("Error: Encoders piping not yet supported to convert file \"" - + sourceFile.getAbsolutePath() - + "\" into " - + targetFormat - + " format."); - else { - final AbstractConverter chosenFormat = formats - .get(0); - final EncodingTask encodingTask = new EncodingTask( - sourceFile, targetFile, chosenFormat, - targetFormat); - - if (chosenFormat.isTerminalMandatory()) - encodingTask.setUseTerminal(true); - encodingPlan.scheduleTask(encodingTask); - } - } - } - } - - } - - /** - * @param file - * single file candidate to potentially be encoded - * - * @return true if file shall be encoded. - */ - public boolean fileMatchesInputPattern(final File file) { - final String fileName = file.getName().toLowerCase(); - - for (final String inputPattern : encodingOptions.getInputPatterns()) - if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) - return true; - - return false; - } - - @Override - public String getDescription() { - return "Convert between various media formats."; - } - - @Override - public String getModuleCommand() { - return "encode"; - } - - private File getTargetFile(final File sourceFile, final String targetFormat) { - final StringBuffer targetFilePath = new StringBuffer(); - targetFilePath.append(sourceFile.getParent()); - targetFilePath.append("/"); - targetFilePath.append(FilePathParser - .getFileNameWithoutExtension(sourceFile)); - targetFilePath.append("."); - targetFilePath.append(targetFormat); - - return new File(targetFilePath.toString()); - } - - @Override - public void run(final String[] args) { - - // parse incoming commandline arguments - encodingOptions = commandlineHandler.parseCommandlineArguments(args); - - if (encodingOptions == null) { - showCommandlineHelp(); - return; - } - - encodingPlan = new EncodingPlan(); - - compileEncodingPlan(encodingOptions.getWorkingDirectory()); - - if (!encodingOptions.isTestOnly()) - try { - encodingPlan.execute(encodingOptions); - } catch (final Exception exception) { - exception.printStackTrace(); - } - - } - - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - System.out.println("Example commands:"); - System.out - .println(" Convert all MTS files in the current directory into MP4's."); - System.out.println(" meviz encode -o mp4 -i *.MTS"); - } + public FormatsRegistry encoderRegistry = new FormatsRegistry(); + + public EncodingOptions encodingOptions; + + public EncodingPlan encodingPlan; + + CommandlineHandler commandlineHandler = new CommandlineHandler(); + + /** + * Generate encoding plan + * + * @param sourceFile Source directory of file + */ + public void compileEncodingPlan(final File sourceFile) { + if (!sourceFile.exists()) { + System.out.println("Error: file \"" + sourceFile.getAbsolutePath() + + "\" does not exist."); + return; + } + + if (sourceFile.isDirectory()) { + // handle directory + for (final File subFile : sourceFile.listFiles()) + if (subFile.isDirectory()) { + if (encodingOptions.isRecursive()) + compileEncodingPlan(subFile); + } else + compileEncodingPlan(subFile); + } else if (sourceFile.isFile()) + if (fileMatchesInputPattern(sourceFile)) { + + // System.out.println("Processing file: " + + // file.getAbsolutePath()); + + final String sourceFileExtension = FilePathParser + .getFileExtension(sourceFile); + + // encode source file into every desired target format + for (final String targetFormat : encodingOptions.getOutputFormats()) { + + // construct target file + final File targetFile = getTargetFile(sourceFile, + targetFormat); + + // System.out.println("target path: " + + // targetFilePath.toString()); + + if (!targetFile.exists()) { + + final List formats = encoderRegistry + .getEncoders(sourceFileExtension, targetFormat); + + if (formats.size() == 0) + System.out + .println("Error: no encoders found to convert file \"" + + sourceFile.getAbsolutePath() + + "\" into " + + targetFormat + + " format."); + else if (formats.size() > 1) + System.out + .println("Error: Encoders piping not yet supported to convert file \"" + + sourceFile.getAbsolutePath() + + "\" into " + + targetFormat + + " format."); + else { + final AbstractConverter chosenFormat = formats + .get(0); + final EncodingTask encodingTask = new EncodingTask( + sourceFile, targetFile, chosenFormat, + targetFormat); + + if (chosenFormat.isTerminalMandatory()) + encodingTask.setUseTerminal(true); + encodingPlan.scheduleTask(encodingTask); + } + } + } + } + + } + + /** + * @param file single file candidate to potentially be encoded + * @return true if file shall be encoded. + */ + public boolean fileMatchesInputPattern(final File file) { + final String fileName = file.getName().toLowerCase(); + + for (final String inputPattern : encodingOptions.getInputPatterns()) + if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) + return true; + + return false; + } + + @Override + public String getDescription() { + return "Convert between various media formats."; + } + + @Override + public String getModuleCommand() { + return "encode"; + } + + private File getTargetFile(final File sourceFile, final String targetFormat) { + String targetFilePath = sourceFile.getParent() + + "/" + + FilePathParser + .getFileNameWithoutExtension(sourceFile) + + "." + + targetFormat; + + return new File(targetFilePath); + } + + @Override + public void run(final String[] args) { + + // parse incoming commandline arguments + encodingOptions = commandlineHandler.parseCommandlineArguments(args); + + if (encodingOptions == null) { + showCommandlineHelp(); + return; + } + + encodingPlan = new EncodingPlan(); + + compileEncodingPlan(encodingOptions.getWorkingDirectory()); + + if (!encodingOptions.isTestOnly()) + try { + encodingPlan.execute(encodingOptions); + } catch (final Exception exception) { + exception.printStackTrace(); + } + + } + + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + System.out.println("Example commands:"); + System.out + .println(" Convert all MTS files in the current directory into MP4's."); + System.out.println(" meviz encode -o mp4 -i *.MTS"); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/EncodingOptions.java b/src/main/java/eu/svjatoslav/meviz/encoder/EncodingOptions.java index 419aae4..b4efb1f 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/EncodingOptions.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/EncodingOptions.java @@ -15,104 +15,104 @@ import java.util.List; public class EncodingOptions { - private BitrateParameter.bitrate videoBitrate = BitrateParameter.bitrate.MEDIUM; + private BitrateParameter.bitrate videoBitrate = BitrateParameter.bitrate.MEDIUM; - private BitrateParameter.bitrate audioBitrate = BitrateParameter.bitrate.MEDIUM; + private BitrateParameter.bitrate audioBitrate = BitrateParameter.bitrate.MEDIUM; - private Integer targetFps; + private Integer targetFps; - private boolean deinterlace = false; + private boolean deinterlace = false; - private boolean recursive; + private boolean recursive; - private boolean testOnly; + private boolean testOnly; - private boolean forPortablePlayer = false; + private boolean forPortablePlayer = false; - private File workingDirectory = new File(System.getProperty("user.dir")); + private File workingDirectory = new File(System.getProperty("user.dir")); - private List outputFormats = new ArrayList(); + private List outputFormats = new ArrayList(); - private List inputPatterns = new ArrayList(); + private List inputPatterns = new ArrayList(); - public BitrateParameter.bitrate getAudioBitrate() { - return audioBitrate; - } + public BitrateParameter.bitrate getAudioBitrate() { + return audioBitrate; + } - public List getInputPatterns() { - return inputPatterns; - } + public void setAudioBitrate(final BitrateParameter.bitrate audioBitrate) { + this.audioBitrate = audioBitrate; + } - public List getOutputFormats() { - return outputFormats; - } + public List getInputPatterns() { + return inputPatterns; + } - public Integer getTargetFps() { - return targetFps; - } + public void setInputPatterns(final List inputPatterns) { + this.inputPatterns = inputPatterns; + } - public BitrateParameter.bitrate getVideoBitrate() { - return videoBitrate; - } + public List getOutputFormats() { + return outputFormats; + } - public File getWorkingDirectory() { - return workingDirectory; - } + public void setOutputFormats(final List outputFormats) { + this.outputFormats = outputFormats; + } - public boolean isDeinterlace() { - return deinterlace; - } + public Integer getTargetFps() { + return targetFps; + } - public boolean isForPortablePlayer() { - return forPortablePlayer; - } + public void setTargetFps(final Integer targetFps) { + this.targetFps = targetFps; + } - public boolean isRecursive() { - return recursive; - } + public BitrateParameter.bitrate getVideoBitrate() { + return videoBitrate; + } - public boolean isTestOnly() { - return testOnly; - } + public void setVideoBitrate(final BitrateParameter.bitrate videoBitrate) { + this.videoBitrate = videoBitrate; + } - public void setAudioBitrate(final BitrateParameter.bitrate audioBitrate) { - this.audioBitrate = audioBitrate; - } + public File getWorkingDirectory() { + return workingDirectory; + } - public void setDeinterlace(final boolean deinterlace) { - this.deinterlace = deinterlace; - } + public void setWorkingDirectory(final File workingDirectory) { + this.workingDirectory = workingDirectory; + } - public void setForPortablePlayer(final boolean forPortablePlayer) { - this.forPortablePlayer = forPortablePlayer; - } + public boolean isDeinterlace() { + return deinterlace; + } - public void setInputPatterns(final List inputPatterns) { - this.inputPatterns = inputPatterns; - } + public void setDeinterlace(final boolean deinterlace) { + this.deinterlace = deinterlace; + } - public void setOutputFormats(final List outputFormats) { - this.outputFormats = outputFormats; - } + public boolean isForPortablePlayer() { + return forPortablePlayer; + } - public void setRecursive(final boolean recursive) { - this.recursive = recursive; - } + public void setForPortablePlayer(final boolean forPortablePlayer) { + this.forPortablePlayer = forPortablePlayer; + } - public void setTargetFps(final Integer targetFps) { - this.targetFps = targetFps; - } + public boolean isRecursive() { + return recursive; + } - public void setTestOnly(final boolean testOnly) { - this.testOnly = testOnly; - } + public void setRecursive(final boolean recursive) { + this.recursive = recursive; + } - public void setVideoBitrate(final BitrateParameter.bitrate videoBitrate) { - this.videoBitrate = videoBitrate; - } + public boolean isTestOnly() { + return testOnly; + } - public void setWorkingDirectory(final File workingDirectory) { - this.workingDirectory = workingDirectory; - } + public void setTestOnly(final boolean testOnly) { + this.testOnly = testOnly; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/EncodingPlan.java b/src/main/java/eu/svjatoslav/meviz/encoder/EncodingPlan.java index e4c75c3..0838d1a 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/EncodingPlan.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/EncodingPlan.java @@ -14,18 +14,18 @@ import java.util.ArrayList; public class EncodingPlan { - public ArrayList encodingTasks = new ArrayList(); + public ArrayList encodingTasks = new ArrayList(); - public void execute(final EncodingOptions encodingOptions) - throws IOException { + public void execute(final EncodingOptions encodingOptions) + throws IOException { - for (final EncodingTask task : encodingTasks) - task.execute(encodingOptions); + for (final EncodingTask task : encodingTasks) + task.execute(encodingOptions); - } + } - public void scheduleTask(final EncodingTask encodingTask) { - encodingTasks.add(encodingTask); - }; + public void scheduleTask(final EncodingTask encodingTask) { + encodingTasks.add(encodingTask); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/EncodingTask.java b/src/main/java/eu/svjatoslav/meviz/encoder/EncodingTask.java index b5dbe08..896ce15 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/EncodingTask.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/EncodingTask.java @@ -9,88 +9,85 @@ package eu.svjatoslav.meviz.encoder; -import java.io.File; - import eu.svjatoslav.meviz.encoder.converters.AbstractConverter; -public class EncodingTask { - - /** - * Source file to encode - */ - private final File source; - - /** - * Target file. - */ - private final File target; - - private final AbstractConverter converter; - - private boolean useTerminal; - - private final String targetFormat; - - public EncodingTask(final File source, final File target, final AbstractConverter converter, - final String targetFormat) { - - this.source = source; - this.target = target; - this.converter = converter; - this.targetFormat = targetFormat; - } - - /** - * @return the useTerminal - */ - public boolean doUseTerminal() { - return useTerminal; - } - - public String encodeApostrophes(final String input) { - final StringBuffer result = new StringBuffer(); - - for (final char c : input.toCharArray()) { - if (c == '\'') { - result.append("'\\''"); - continue; - } - result.append(c); - } - - return result.toString(); - } - - public void execute(final EncodingOptions encodingOptions) { - try { - String command = getCommand(encodingOptions); - - if (doUseTerminal()) - command = "xterm -e '" + encodeApostrophes(command) + "'"; - - System.out.println("Executing command: " + command); - - final Runtime runtime = Runtime.getRuntime(); - final Process process = runtime.exec(new String[] { "/bin/bash", "-c", command }); - - process.waitFor(); - - } catch (final Exception e) { - System.out.println(e.toString()); - e.printStackTrace(); - } - - } +import java.io.File; - public String getCommand(final EncodingOptions encodingOptions) { - return converter.getCommand(source, target, encodingOptions, targetFormat); - } +public class EncodingTask { - /** - * @param useTerminal - * the useTerminal to set - */ - public void setUseTerminal(final boolean useTerminal) { - this.useTerminal = useTerminal; - } + /** + * Source file to encode + */ + private final File source; + + /** + * Target file. + */ + private final File target; + + private final AbstractConverter converter; + private final String targetFormat; + private boolean useTerminal; + + public EncodingTask(final File source, final File target, final AbstractConverter converter, + final String targetFormat) { + + this.source = source; + this.target = target; + this.converter = converter; + this.targetFormat = targetFormat; + } + + /** + * @return the useTerminal + */ + public boolean doUseTerminal() { + return useTerminal; + } + + public String encodeApostrophes(final String input) { + final StringBuilder result = new StringBuilder(); + + for (final char c : input.toCharArray()) { + if (c == '\'') { + result.append("'\\''"); + continue; + } + result.append(c); + } + + return result.toString(); + } + + public void execute(final EncodingOptions encodingOptions) { + try { + String command = getCommand(encodingOptions); + + if (doUseTerminal()) + command = "xterm -e '" + encodeApostrophes(command) + "'"; + + System.out.println("Executing command: " + command); + + final Runtime runtime = Runtime.getRuntime(); + final Process process = runtime.exec(new String[]{"/bin/bash", "-c", command}); + + process.waitFor(); + + } catch (final Exception e) { + System.out.println(e.toString()); + e.printStackTrace(); + } + + } + + public String getCommand(final EncodingOptions encodingOptions) { + return converter.getCommand(source, target, encodingOptions, targetFormat); + } + + /** + * @param useTerminal the useTerminal to set + */ + public void setUseTerminal(final boolean useTerminal) { + this.useTerminal = useTerminal; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/FormatsRegistry.java b/src/main/java/eu/svjatoslav/meviz/encoder/FormatsRegistry.java index 6b8d129..7395c31 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/FormatsRegistry.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/FormatsRegistry.java @@ -9,61 +9,53 @@ package eu.svjatoslav.meviz.encoder; +import eu.svjatoslav.meviz.encoder.converters.*; + import java.util.ArrayList; import java.util.List; -import eu.svjatoslav.meviz.encoder.converters.AbstractConverter; -import eu.svjatoslav.meviz.encoder.converters.AvconvAudio; -import eu.svjatoslav.meviz.encoder.converters.AvconvVideo; -import eu.svjatoslav.meviz.encoder.converters.Convert; -import eu.svjatoslav.meviz.encoder.converters.Ffmpeg2theora; -import eu.svjatoslav.meviz.encoder.converters.Flac; -import eu.svjatoslav.meviz.encoder.converters.Midi2Wav; -import eu.svjatoslav.meviz.encoder.converters.Ocr; -import eu.svjatoslav.meviz.encoder.converters.Ogg2Wav; - public class FormatsRegistry { - public ArrayList encoders = new ArrayList(); + public ArrayList encoders = new ArrayList(); - public FormatsRegistry() { - // video conversion - registerEncoder(new Ffmpeg2theora()); - registerEncoder(new AvconvVideo()); + public FormatsRegistry() { + // video conversion + registerEncoder(new Ffmpeg2theora()); + registerEncoder(new AvconvVideo()); - // image conversion - registerEncoder(new Convert()); + // image conversion + registerEncoder(new Convert()); - // image to text (OCR) - registerEncoder(new Ocr()); + // image to text (OCR) + registerEncoder(new Ocr()); - // audio conversion - registerEncoder(new Ogg2Wav()); - registerEncoder(new Flac()); - registerEncoder(new AvconvAudio()); - registerEncoder(new Midi2Wav()); - } + // audio conversion + registerEncoder(new Ogg2Wav()); + registerEncoder(new Flac()); + registerEncoder(new AvconvAudio()); + registerEncoder(new Midi2Wav()); + } - public List getEncoders(final String sourceFormat, - final String targetFormat) { + public List getEncoders(final String sourceFormat, + final String targetFormat) { - final String sourceFormatLowerCase = sourceFormat.toLowerCase(); - final String targetFormatLowerCase = targetFormat.toLowerCase(); + final String sourceFormatLowerCase = sourceFormat.toLowerCase(); + final String targetFormatLowerCase = targetFormat.toLowerCase(); - final ArrayList encoders = new ArrayList(); + final ArrayList encoders = new ArrayList(); - for (final AbstractConverter encoder : this.encoders) - if (encoder.supportsSource(sourceFormatLowerCase)) - if (encoder.supportsTarget(targetFormatLowerCase)) { - encoders.add(encoder); - return encoders; - } + for (final AbstractConverter encoder : this.encoders) + if (encoder.supportsSource(sourceFormatLowerCase)) + if (encoder.supportsTarget(targetFormatLowerCase)) { + encoders.add(encoder); + return encoders; + } - return encoders; - } + return encoders; + } - public void registerEncoder(final AbstractConverter encoder) { - encoders.add(encoder); - } + public void registerEncoder(final AbstractConverter encoder) { + encoders.add(encoder); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/AbstractConverter.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/AbstractConverter.java index 6d61f91..322566b 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/AbstractConverter.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/AbstractConverter.java @@ -9,41 +9,41 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public abstract class AbstractConverter { - public abstract String getCommand(File inputFile, File targetFile, - EncodingOptions options, String targetFormat); + public abstract String getCommand(File inputFile, File targetFile, + EncodingOptions options, String targetFormat); - public abstract List getSourceFileExtensions(); + public abstract List getSourceFileExtensions(); - public abstract List getTargetFileExtensions(); + public abstract List getTargetFileExtensions(); - /** - * For some reasons some encoders require terminal to run. Until this is - * resolved, encoder can request for terminal using this method. - */ - public abstract boolean isTerminalMandatory(); + /** + * For some reasons some encoders require terminal to run. Until this is + * resolved, encoder can request for terminal using this method. + */ + public abstract boolean isTerminalMandatory(); - public boolean supportsSource(final String format) { - return getSourceFileExtensions().contains(format); - } + public boolean supportsSource(final String format) { + return getSourceFileExtensions().contains(format); + } - public boolean supportsTarget(final String format) { - return getTargetFileExtensions().contains(format); - } + public boolean supportsTarget(final String format) { + return getTargetFileExtensions().contains(format); + } - public List toList(final String... strings) { - final ArrayList result = new ArrayList(); + public List toList(final String... strings) { + final ArrayList result = new ArrayList(); - for (final String string : strings) - result.add(string); + Collections.addAll(result, strings); - return result; - } + return result; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvAudio.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvAudio.java index 5dd258a..6746ad6 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvAudio.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvAudio.java @@ -9,36 +9,36 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class AvconvAudio extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { - final String codecParams = "-b:a 192k"; + final String codecParams = "-b:a 192k"; - return "avconv -i \"" + inputFile.getAbsolutePath() + "\" " - + codecParams + " \"" + targetFile.getAbsolutePath() + "\""; - } + return "avconv -i \"" + inputFile.getAbsolutePath() + "\" " + + codecParams + " \"" + targetFile.getAbsolutePath() + "\""; + } - @Override - public List getSourceFileExtensions() { - return toList("ogg", "wav"); - } + @Override + public List getSourceFileExtensions() { + return toList("ogg", "wav"); + } - @Override - public List getTargetFileExtensions() { - return toList("mp3"); - } + @Override + public List getTargetFileExtensions() { + return toList("mp3"); + } - @Override - public boolean isTerminalMandatory() { - return false; - } + @Override + public boolean isTerminalMandatory() { + return false; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvVideo.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvVideo.java index 58cd215..9228317 100644 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvVideo.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/AvconvVideo.java @@ -9,149 +9,149 @@ package eu.svjatoslav.meviz.encoder.converters; -import java.io.File; -import java.util.List; - import eu.svjatoslav.meviz.encoder.BitrateParameter; import eu.svjatoslav.meviz.encoder.BitrateParameter.bitrate; import eu.svjatoslav.meviz.encoder.EncodingOptions; +import java.io.File; +import java.util.List; + public class AvconvVideo extends AbstractConverter { - private String constructCodecParamsString(final EncodingOptions options, - final int videoBitrate, final int audioBitrate, - final String videoCodec, final String audioCodec) { + private String constructCodecParamsString(final EncodingOptions options, + final int videoBitrate, final int audioBitrate, + final String videoCodec, final String audioCodec) { - final StringBuffer codecParams = new StringBuffer(); + final StringBuilder codecParams = new StringBuilder(); - if (audioCodec == null) - codecParams.append("-an "); - else - codecParams.append("-acodec " + audioCodec + " "); + if (audioCodec == null) + codecParams.append("-an "); + else + codecParams.append("-acodec " + audioCodec + " "); - codecParams.append("-vcodec " + videoCodec + " "); + codecParams.append("-vcodec " + videoCodec + " "); - if (videoBitrate != -1) - codecParams.append("-b " + videoBitrate + "k "); + if (videoBitrate != -1) + codecParams.append("-b " + videoBitrate + "k "); - if (audioBitrate != -1) - codecParams.append("-b:a " + audioBitrate + "k "); + if (audioBitrate != -1) + codecParams.append("-b:a " + audioBitrate + "k "); - if (options.isDeinterlace()) - codecParams.append("-filter:v yadif "); + if (options.isDeinterlace()) + codecParams.append("-filter:v yadif "); - if (options.getTargetFps() != null) - codecParams.append("-r " + options.getTargetFps() + " "); + if (options.getTargetFps() != null) + codecParams.append("-r " + options.getTargetFps() + " "); - return codecParams.toString(); - } + return codecParams.toString(); + } - private int getAudioBitrateValue(final BitrateParameter.bitrate bitRate) { - switch (bitRate) { - case LOW: - return 128; + private int getAudioBitrateValue(final BitrateParameter.bitrate bitRate) { + switch (bitRate) { + case LOW: + return 128; - case MEDIUM: - return 160; + case MEDIUM: + return 160; - case HIGH: - return 320; + case HIGH: + return 320; - case COPY: - return -1; + case COPY: + return -1; - case NONE: - return -1; + case NONE: + return -1; - default: - throw new RuntimeException("Audio bitrate: " + bitRate - + " is not supported."); - } - } + default: + throw new RuntimeException("Audio bitrate: " + bitRate + + " is not supported."); + } + } - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, final String targetFormat) { + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, final String targetFormat) { - int videoBitrate = getVideoBitrateValue(options.getVideoBitrate()); - int audioBitrate = getAudioBitrateValue(options.getAudioBitrate()); + int videoBitrate = getVideoBitrateValue(options.getVideoBitrate()); + int audioBitrate = getAudioBitrateValue(options.getAudioBitrate()); - // convert - final StringBuffer codecParams = new StringBuffer(); + // convert + final StringBuilder codecParams = new StringBuilder(); - String videoCodec = "libx264"; - String audioCodec = "libmp3lame"; + String videoCodec = "libx264"; + String audioCodec = "libmp3lame"; - if (targetFormat.equals("webm")) { - videoCodec = "vp8"; - audioCodec = "opus"; - codecParams.append("-s 800x600 "); - } + if (targetFormat.equals("webm")) { + videoCodec = "vp8"; + audioCodec = "opus"; + codecParams.append("-s 800x600 "); + } - if (options.getVideoBitrate() == bitrate.COPY) - videoCodec = "copy"; + if (options.getVideoBitrate() == bitrate.COPY) + videoCodec = "copy"; - if (options.getAudioBitrate() == bitrate.COPY) - audioCodec = "copy"; + if (options.getAudioBitrate() == bitrate.COPY) + audioCodec = "copy"; - if (options.getAudioBitrate() == bitrate.NONE) - audioCodec = null; + if (options.getAudioBitrate() == bitrate.NONE) + audioCodec = null; - if (options.isForPortablePlayer()) { - videoBitrate = 1000; - audioBitrate = 128; - videoCodec = "libxvid"; + if (options.isForPortablePlayer()) { + videoBitrate = 1000; + audioBitrate = 128; + videoCodec = "libxvid"; - // reduce resolution - codecParams.append("-s 640x480 "); + // reduce resolution + codecParams.append("-s 640x480 "); - // enforce maximum keyframe interval - codecParams.append("-g 150 "); - } + // enforce maximum keyframe interval + codecParams.append("-g 150 "); + } - codecParams.append(constructCodecParamsString(options, videoBitrate, - audioBitrate, videoCodec, audioCodec)); + codecParams.append(constructCodecParamsString(options, videoBitrate, + audioBitrate, videoCodec, audioCodec)); - return "avconv -i \"" + inputFile.getAbsolutePath() + "\" " - + codecParams.toString() + "\"" + targetFile.getAbsolutePath() - + "\""; - } + return "avconv -i \"" + inputFile.getAbsolutePath() + "\" " + + codecParams.toString() + "\"" + targetFile.getAbsolutePath() + + "\""; + } - @Override - public List getSourceFileExtensions() { - return toList("mkv", "mts", "mp4", "avi", "mpg", "mpeg", "vob", "m4v", - "webm", "mov"); - } + @Override + public List getSourceFileExtensions() { + return toList("mkv", "mts", "mp4", "avi", "mpg", "mpeg", "vob", "m4v", + "webm", "mov"); + } - @Override - public List getTargetFileExtensions() { - return toList("mkv", "mts", "mp4", "avi", "mpg", "mpeg", "vob", "m4v", - "webm", "mov"); - } + @Override + public List getTargetFileExtensions() { + return toList("mkv", "mts", "mp4", "avi", "mpg", "mpeg", "vob", "m4v", + "webm", "mov"); + } - private int getVideoBitrateValue(final BitrateParameter.bitrate bitRate) { - switch (bitRate) { - case LOW: - return 1000; + private int getVideoBitrateValue(final BitrateParameter.bitrate bitRate) { + switch (bitRate) { + case LOW: + return 1000; - case MEDIUM: - return 4000; + case MEDIUM: + return 4000; - case HIGH: - return 16000; + case HIGH: + return 16000; - case COPY: - return -1; + case COPY: + return -1; - default: - throw new RuntimeException("Video bitrate: " + bitRate - + " is not supported."); - } - } + default: + throw new RuntimeException("Video bitrate: " + bitRate + + " is not supported."); + } + } - @Override - public boolean isTerminalMandatory() { - return true; - } + @Override + public boolean isTerminalMandatory() { + return true; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Convert.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Convert.java index e7abf57..cf416a9 100644 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Convert.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Convert.java @@ -9,33 +9,33 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class Convert extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { - return "convert \"" + inputFile.getAbsolutePath() + "\" \"" - + targetFile.getAbsolutePath() + "\""; - } - - @Override - public List getSourceFileExtensions() { - return toList("tif", "tiff", "png", "jpg", "jpeg"); - } - - @Override - public List getTargetFileExtensions() { - return toList("png", "tiff", "tif"); - } - - @Override - public boolean isTerminalMandatory() { - return false; - } + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { + return "convert \"" + inputFile.getAbsolutePath() + "\" \"" + + targetFile.getAbsolutePath() + "\""; + } + + @Override + public List getSourceFileExtensions() { + return toList("tif", "tiff", "png", "jpg", "jpeg"); + } + + @Override + public List getTargetFileExtensions() { + return toList("png", "tiff", "tif"); + } + + @Override + public boolean isTerminalMandatory() { + return false; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ffmpeg2theora.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ffmpeg2theora.java index b2afedb..e214bd9 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ffmpeg2theora.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ffmpeg2theora.java @@ -9,34 +9,34 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class Ffmpeg2theora extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { - return "ffmpeg2theora \"" + inputFile.getAbsolutePath() + "\" -o \"" - + targetFile.getAbsolutePath() - + "\" --optimize --videobitrate 3000 --width 800"; - } - - @Override - public List getSourceFileExtensions() { - return toList("avi", "mp4", "m4v", "asf"); - } - - @Override - public List getTargetFileExtensions() { - return toList("ogv"); - } - - @Override - public boolean isTerminalMandatory() { - return true; - } + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { + return "ffmpeg2theora \"" + inputFile.getAbsolutePath() + "\" -o \"" + + targetFile.getAbsolutePath() + + "\" --optimize --videobitrate 3000 --width 800"; + } + + @Override + public List getSourceFileExtensions() { + return toList("avi", "mp4", "m4v", "asf"); + } + + @Override + public List getTargetFileExtensions() { + return toList("ogv"); + } + + @Override + public boolean isTerminalMandatory() { + return true; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Flac.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Flac.java index bf239cc..ac2b468 100644 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Flac.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Flac.java @@ -9,34 +9,34 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class Flac extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { - return "flac -8 \"" + inputFile.getAbsolutePath() + "\" -o \"" - + targetFile.getAbsolutePath() + "\""; - } + return "flac -8 \"" + inputFile.getAbsolutePath() + "\" -o \"" + + targetFile.getAbsolutePath() + "\""; + } - @Override - public List getSourceFileExtensions() { - return toList("wav"); - } + @Override + public List getSourceFileExtensions() { + return toList("wav"); + } - @Override - public List getTargetFileExtensions() { - return toList("flac"); - } + @Override + public List getTargetFileExtensions() { + return toList("flac"); + } - @Override - public boolean isTerminalMandatory() { - return false; - } + @Override + public boolean isTerminalMandatory() { + return false; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Midi2Wav.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Midi2Wav.java index d823761..9478e23 100644 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Midi2Wav.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Midi2Wav.java @@ -9,34 +9,34 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class Midi2Wav extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { - return "timidity \"" + inputFile.getAbsolutePath() + "\" -Ow -o \"" - + targetFile.getAbsolutePath() + "\""; - } + return "timidity \"" + inputFile.getAbsolutePath() + "\" -Ow -o \"" + + targetFile.getAbsolutePath() + "\""; + } - @Override - public List getSourceFileExtensions() { - return toList("mid"); - } + @Override + public List getSourceFileExtensions() { + return toList("mid"); + } - @Override - public List getTargetFileExtensions() { - return toList("wav"); - } + @Override + public List getTargetFileExtensions() { + return toList("wav"); + } - @Override - public boolean isTerminalMandatory() { - return true; - } + @Override + public boolean isTerminalMandatory() { + return true; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ocr.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ocr.java index 0c20018..e4753fe 100644 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ocr.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ocr.java @@ -9,40 +9,40 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class Ocr extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { - - // for some stupid reason tesseract ALWAYS insists on automatically - // adding txt suffix - String targetAbsolutePath = targetFile.getAbsolutePath(); - String targetFileName = targetAbsolutePath.substring(0, - targetAbsolutePath.length() - 4); - - return "tesseract \"" + inputFile.getAbsolutePath() + "\" \"" - + targetFileName + "\""; - } - - @Override - public List getSourceFileExtensions() { - return toList("tif", "tiff", "png", "jpg", "jpeg"); - } - - @Override - public List getTargetFileExtensions() { - return toList("txt"); - } - - @Override - public boolean isTerminalMandatory() { - return false; - } + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { + + // for some stupid reason tesseract ALWAYS insists on automatically + // adding txt suffix + String targetAbsolutePath = targetFile.getAbsolutePath(); + String targetFileName = targetAbsolutePath.substring(0, + targetAbsolutePath.length() - 4); + + return "tesseract \"" + inputFile.getAbsolutePath() + "\" \"" + + targetFileName + "\""; + } + + @Override + public List getSourceFileExtensions() { + return toList("tif", "tiff", "png", "jpg", "jpeg"); + } + + @Override + public List getTargetFileExtensions() { + return toList("txt"); + } + + @Override + public boolean isTerminalMandatory() { + return false; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ogg2Wav.java b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ogg2Wav.java index f89927b..57a6d2d 100755 --- a/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ogg2Wav.java +++ b/src/main/java/eu/svjatoslav/meviz/encoder/converters/Ogg2Wav.java @@ -9,35 +9,35 @@ package eu.svjatoslav.meviz.encoder.converters; +import eu.svjatoslav.meviz.encoder.EncodingOptions; + import java.io.File; import java.util.List; -import eu.svjatoslav.meviz.encoder.EncodingOptions; - public class Ogg2Wav extends AbstractConverter { - @Override - public String getCommand(final File inputFile, final File targetFile, - final EncodingOptions options, String targetFormat) { + @Override + public String getCommand(final File inputFile, final File targetFile, + final EncodingOptions options, String targetFormat) { - return "oggdec \"" + inputFile.getAbsolutePath() + "\" -o \"" - + targetFile.getAbsolutePath() + "\""; + return "oggdec \"" + inputFile.getAbsolutePath() + "\" -o \"" + + targetFile.getAbsolutePath() + "\""; - } + } - @Override - public List getSourceFileExtensions() { - return toList("ogg"); - } + @Override + public List getSourceFileExtensions() { + return toList("ogg"); + } - @Override - public List getTargetFileExtensions() { - return toList("wav"); - } + @Override + public List getTargetFileExtensions() { + return toList("wav"); + } - @Override - public boolean isTerminalMandatory() { - return true; - } + @Override + public boolean isTerminalMandatory() { + return true; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/grabmemcard/Main.java b/src/main/java/eu/svjatoslav/meviz/grabmemcard/Main.java index e538338..44faebc 100755 --- a/src/main/java/eu/svjatoslav/meviz/grabmemcard/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/grabmemcard/Main.java @@ -9,11 +9,6 @@ package eu.svjatoslav.meviz.grabmemcard; -import java.io.File; -import java.io.IOException; -import java.util.Date; -import java.util.GregorianCalendar; - import eu.svjatoslav.commons.file.CommonPathResolver; import eu.svjatoslav.commons.file.FilePathParser; import eu.svjatoslav.meviz.Module; @@ -24,106 +19,108 @@ import eu.svjatoslav.meviz.encoder.EncodingTask; import eu.svjatoslav.meviz.encoder.converters.AbstractConverter; import eu.svjatoslav.meviz.encoder.converters.AvconvVideo; -public class Main implements Module { +import java.io.File; +import java.io.IOException; +import java.util.Date; +import java.util.GregorianCalendar; - @Override - public String getDescription() { - return "Convenience helper to retrieve contents of inserted memory card."; - } +public class Main implements Module { - public File[] getDiskVideos(final File file) { - final String videosPath = file.getAbsolutePath() + "/AVCHD/BDMV/STREAM/"; - final File videosDirectory = new File(videosPath); + @Override + public String getDescription() { + return "Convenience helper to retrieve contents of inserted memory card."; + } - if (!videosDirectory.exists()) - return new File[0]; + public File[] getDiskVideos(final File file) { + final String videosPath = file.getAbsolutePath() + "/AVCHD/BDMV/STREAM/"; + final File videosDirectory = new File(videosPath); - return videosDirectory.listFiles(); - } + if (!videosDirectory.exists()) + return new File[0]; - public String getDoubleDigit(final int value) { - String valueString = Integer.toString(value); - if (valueString.length() == 1) - valueString = "0" + valueString; - return valueString; - }; + return videosDirectory.listFiles(); + } - private EncodingOptions getEncodingOptions() { - final EncodingOptions options = new EncodingOptions(); - options.setVideoBitrate(BitrateParameter.bitrate.COPY); - options.setAudioBitrate(BitrateParameter.bitrate.COPY); - return options; - } + public String getDoubleDigit(final int value) { + String valueString = Integer.toString(value); + if (valueString.length() == 1) + valueString = "0" + valueString; + return valueString; + } - @Override - public String getModuleCommand() { - return "grabmemcard"; - } + private EncodingOptions getEncodingOptions() { + final EncodingOptions options = new EncodingOptions(); + options.setVideoBitrate(BitrateParameter.bitrate.COPY); + options.setAudioBitrate(BitrateParameter.bitrate.COPY); + return options; + } - @SuppressWarnings("deprecation") - public File getTargetDirectory() { - final Date now = new Date(); - final GregorianCalendar calendar = new GregorianCalendar(); + @Override + public String getModuleCommand() { + return "grabmemcard"; + } - final StringBuffer directoryName = new StringBuffer(); - directoryName.append( - calendar.get(GregorianCalendar.YEAR) + "." + getDoubleDigit(calendar.get(GregorianCalendar.MONTH) + 1) - + "." + getDoubleDigit(calendar.get(GregorianCalendar.DAY_OF_MONTH)) + " "); + @SuppressWarnings("deprecation") + public File getTargetDirectory() { + final Date now = new Date(); + final GregorianCalendar calendar = new GregorianCalendar(); - directoryName.append(getDoubleDigit(now.getHours()) + ":" + getDoubleDigit(now.getMinutes()) + ":" - + getDoubleDigit(now.getSeconds())); + String directoryName = (calendar.get(GregorianCalendar.YEAR) + "." + getDoubleDigit(calendar.get(GregorianCalendar.MONTH) + 1) + + "." + getDoubleDigit(calendar.get(GregorianCalendar.DAY_OF_MONTH)) + " ") + + getDoubleDigit(now.getHours()) + ":" + getDoubleDigit(now.getMinutes()) + ":" + + getDoubleDigit(now.getSeconds()); - final String targetDirectoryPath = CommonPathResolver.getDesktopDirectory().getAbsolutePath() + "/" - + directoryName.toString() + "/"; + final String targetDirectoryPath = CommonPathResolver.getDesktopDirectory().getAbsolutePath() + "/" + + directoryName + "/"; - System.out.println("Target directory path: " + targetDirectoryPath); + System.out.println("Target directory path: " + targetDirectoryPath); - return new File(targetDirectoryPath); - } + return new File(targetDirectoryPath); + } - private File getTargetFile(final File targetDirectory, final File sourceFile) { - // compute target file path - final StringBuffer targetFilePath = new StringBuffer(); - targetFilePath.append(targetDirectory.getAbsolutePath()); - targetFilePath.append("/"); - targetFilePath.append(FilePathParser.getFileNameWithoutExtension(sourceFile)); - targetFilePath.append(".mp4"); - final File targetFile = new File(targetFilePath.toString()); - return targetFile; - } + private File getTargetFile(final File targetDirectory, final File sourceFile) { + // compute target file path + final StringBuilder targetFilePath = new StringBuilder(); + targetFilePath.append(targetDirectory.getAbsolutePath()); + targetFilePath.append("/"); + targetFilePath.append(FilePathParser.getFileNameWithoutExtension(sourceFile)); + targetFilePath.append(".mp4"); + final File targetFile = new File(targetFilePath.toString()); + return targetFile; + } - @Override - public void run(final String[] args) throws IOException { + @Override + public void run(final String[] args) throws IOException { - final File targetDirectory = getTargetDirectory(); - targetDirectory.mkdirs(); + final File targetDirectory = getTargetDirectory(); + targetDirectory.mkdirs(); - final AbstractConverter converter = new AvconvVideo(); - final EncodingPlan encodingPlan = new EncodingPlan(); + final AbstractConverter converter = new AvconvVideo(); + final EncodingPlan encodingPlan = new EncodingPlan(); - final String userName = System.getProperty("user.name"); + final String userName = System.getProperty("user.name"); - final File file = new File("/media/" + userName + "/"); + final File file = new File("/media/" + userName + "/"); - for (final File insertedDisk : file.listFiles()) { - final File[] diskVideos = getDiskVideos(insertedDisk); + for (final File insertedDisk : file.listFiles()) { + final File[] diskVideos = getDiskVideos(insertedDisk); - for (final File sourceFile : diskVideos) { + for (final File sourceFile : diskVideos) { - final File targetFile = getTargetFile(targetDirectory, sourceFile); + final File targetFile = getTargetFile(targetDirectory, sourceFile); - final EncodingTask encodingTask = new EncodingTask(sourceFile, targetFile, converter, "mp4"); - encodingTask.setUseTerminal(true); - encodingPlan.scheduleTask(encodingTask); - } - } + final EncodingTask encodingTask = new EncodingTask(sourceFile, targetFile, converter, "mp4"); + encodingTask.setUseTerminal(true); + encodingPlan.scheduleTask(encodingTask); + } + } - encodingPlan.execute(getEncodingOptions()); - } + encodingPlan.execute(getEncodingOptions()); + } - @Override - public void showCommandlineHelp() { - System.out.println("memory card grabber has no commandline options"); - } + @Override + public void showCommandlineHelp() { + System.out.println("memory card grabber has no commandline options"); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/AbstractIndexer.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/AbstractIndexer.java index 294189b..2394ece 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/AbstractIndexer.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/AbstractIndexer.java @@ -1,8 +1,5 @@ package eu.svjatoslav.meviz.htmlindexer; -import java.io.File; -import java.io.UnsupportedEncodingException; - import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; import eu.svjatoslav.meviz.htmlindexer.metadata.DirectoryMetadata; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; @@ -10,58 +7,61 @@ import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.DirectoryFile; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.GeneralFile; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; +import java.io.File; +import java.io.UnsupportedEncodingException; + public abstract class AbstractIndexer { - public static boolean isImage(final String fileExtension) { - for (final String ext : Constants.SUPPORTED_IMAGE_EXTENSIONS) - if (ext.equals(fileExtension)) - return true; - return false; - } + public static boolean isImage(final String fileExtension) { + for (final String ext : Constants.SUPPORTED_IMAGE_EXTENSIONS) + if (ext.equals(fileExtension)) + return true; + return false; + } - public static boolean isOgv(final String fileExtension) { - return fileExtension.equalsIgnoreCase("ogv"); - } + public static boolean isOgv(final String fileExtension) { + return fileExtension.equalsIgnoreCase("ogv"); + } - public static boolean shallFileBeIndexed(final File file) { + public static boolean shallFileBeIndexed(final File file) { - if (file.getName().startsWith(".")) - return false; - if (file.getName().startsWith("index")) - if (file.getName().endsWith(".html")) - return false; + if (file.getName().startsWith(".")) + return false; + if (file.getName().startsWith("index")) + if (file.getName().endsWith(".html")) + return false; - return true; - } + return true; + } - public void compileHtml(final Layout layout, - final DirectoryMetadata directory) - throws UnsupportedEncodingException { + public void compileHtml(final Layout layout, + final DirectoryMetadata directory) + throws UnsupportedEncodingException { - for (final AbstractFile file : directory.getFiles()) - if (file instanceof GeneralFile) { - final String fileExtension = file.getFileExtension(); + for (final AbstractFile file : directory.getFiles()) + if (file instanceof GeneralFile) { + final String fileExtension = file.getFileExtension(); - if ("ogv".equals(fileExtension)) - layout.enlistOgv(file, directory); - else if ("webm".equals(fileExtension)) - layout.enlistWebm(file, directory); - else - layout.enlistFile(file, directory); + if ("ogv".equals(fileExtension)) + layout.enlistOgv(file, directory); + else if ("webm".equals(fileExtension)) + layout.enlistWebm(file, directory); + else + layout.enlistFile(file, directory); - } else if (file instanceof Picture) - layout.enlistImage((Picture) file, directory); - else if (file instanceof DirectoryFile) - layout.enlistDirectory(file, directory); + } else if (file instanceof Picture) + layout.enlistImage((Picture) file, directory); + else if (file instanceof DirectoryFile) + layout.enlistDirectory(file, directory); - } + } - public abstract String getDirectoryUrl(final AbstractFile directory, - IndexingContext context); + public abstract String getDirectoryUrl(final AbstractFile directory, + IndexingContext context); - public abstract String getParentDirectoryUrl(IndexingContext context); + public abstract String getParentDirectoryUrl(IndexingContext context); - public abstract String getThumbnailUrl(Picture picture, - final Dimension desiredDimension, IndexingContext context); + public abstract String getThumbnailUrl(Picture picture, + final Dimension desiredDimension, IndexingContext context); } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/CommandlineHandler.java index 5f27ee0..d45bc84 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/CommandlineHandler.java @@ -9,55 +9,55 @@ package eu.svjatoslav.meviz.htmlindexer; -import java.io.File; - import eu.svjatoslav.commons.commandline.parameterparser.Parser; import eu.svjatoslav.commons.commandline.parameterparser.parameter.DirectoryParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.NullParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameter; import eu.svjatoslav.meviz.encoder.EncodingOptions; +import java.io.File; + public class CommandlineHandler { - Parser parser = new Parser(); - - StringParameter galleryNameParameter = parser.add( - new StringParameter("Gallery title. (default is: " - + Constants.DEFAULT_GALLERY_TITLE + ").")).addAliases("-t", - "--gallery-title"); - - DirectoryParameter workingDirectoryParameter = parser - .add(new DirectoryParameter("Working directory.")) - .addAliases("-w", "--working-directory").mustExist(); - - NullParameter removeIndex = parser.add( - new NullParameter("Remove generated index")).addAliases("-r", - "--remove"); - - public String getGalleryTitle() { - if (galleryNameParameter.isParameterSpecified()) - return galleryNameParameter.getValue(); - return Constants.DEFAULT_GALLERY_TITLE; - } - - public File getWorkingDirectory() { - if (workingDirectoryParameter.isParameterSpecified()) - return workingDirectoryParameter.getValue(); - else - return new File(System.getProperty("user.dir")); - } - - /** - * @return {@link EncodingOptions} if commandline arguments were - * successfully parsed, or null if parsing error - * occurred. - */ - public boolean parseCommandlineArguments(final String[] args) { - final boolean parsingSucceeded = parser.parse(args); - - if (!parsingSucceeded) - parser.showHelp(); - - return parsingSucceeded; - } + Parser parser = new Parser(); + + StringParameter galleryNameParameter = parser.add( + new StringParameter("Gallery title. (default is: " + + Constants.DEFAULT_GALLERY_TITLE + ").")).addAliases("-t", + "--gallery-title"); + + DirectoryParameter workingDirectoryParameter = parser + .add(new DirectoryParameter("Working directory.")) + .addAliases("-w", "--working-directory").mustExist(); + + NullParameter removeIndex = parser.add( + new NullParameter("Remove generated index")).addAliases("-r", + "--remove"); + + public String getGalleryTitle() { + if (galleryNameParameter.isParameterSpecified()) + return galleryNameParameter.getValue(); + return Constants.DEFAULT_GALLERY_TITLE; + } + + public File getWorkingDirectory() { + if (workingDirectoryParameter.isParameterSpecified()) + return workingDirectoryParameter.getValue(); + else + return new File(System.getProperty("user.dir")); + } + + /** + * @return {@link EncodingOptions} if commandline arguments were + * successfully parsed, or null if parsing error + * occurred. + */ + public boolean parseCommandlineArguments(final String[] args) { + final boolean parsingSucceeded = parser.parse(args); + + if (!parsingSucceeded) + parser.showHelp(); + + return parsingSucceeded; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Constants.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Constants.java index 3167f3b..1cfbe1e 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Constants.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Constants.java @@ -11,30 +11,30 @@ package eu.svjatoslav.meviz.htmlindexer; public class Constants { - public static final String DEFAULT_GALLERY_TITLE = "Gallery"; + public static final String DEFAULT_GALLERY_TITLE = "Gallery"; - public static final String METADATA_FILE_NAME = "metadata_6.dat"; + public static final String METADATA_FILE_NAME = "metadata_6.dat"; - public static final String THUMBNAILS_DIRECTORY_NAME = ".thumbnails"; + public static final String THUMBNAILS_DIRECTORY_NAME = ".thumbnails"; - /** - * If this string is found within index.html then it is assumed that the - * file is generated by current utility and therefore is safe to overwrite - * with the newer version. - * - * TODO: possibility of multiple patterns shall be present, to allow easy - * migration - * - * TODO: a safer way shall be used for detection, like specific pattern also - * in specific place within a file - */ - public static final String HTML_MAGIC_STRING = "DirListGen"; + /** + * If this string is found within index.html then it is assumed that the + * file is generated by current utility and therefore is safe to overwrite + * with the newer version. + *

+ * TODO: possibility of multiple patterns shall be present, to allow easy + * migration + *

+ * TODO: a safer way shall be used for detection, like specific pattern also + * in specific place within a file + */ + public static final String HTML_MAGIC_STRING = "DirListGen"; - public static final String HTML_MEMO = "Directory Listing Generator by Svjatoslav Agejenko. E-mail: svjatoslav@svjatoslav.eu, homepage: http://svjatoslav.eu"; + public static final String HTML_MEMO = "Directory Listing Generator by Svjatoslav Agejenko. E-mail: svjatoslav@svjatoslav.eu, homepage: http://svjatoslav.eu"; - public static final String[] SUPPORTED_IMAGE_EXTENSIONS = { "jpg", "jpeg", - "png", "gif" }; + public static final String[] SUPPORTED_IMAGE_EXTENSIONS = {"jpg", "jpeg", + "png", "gif"}; - public static final String THUMBNAIL_VERSION = "2"; + public static final String THUMBNAIL_VERSION = "2"; } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/FileSortComparator.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/FileSortComparator.java index b7ecef7..7497eeb 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/FileSortComparator.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/FileSortComparator.java @@ -1,14 +1,14 @@ package eu.svjatoslav.meviz.htmlindexer; -import java.util.Comparator; - import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; +import java.util.Comparator; + public class FileSortComparator implements Comparator { - @Override - public int compare(final AbstractFile o1, final AbstractFile o2) { - return o1.fileName.compareTo(o2.fileName); - } + @Override + public int compare(final AbstractFile o1, final AbstractFile o2) { + return o1.fileName.compareTo(o2.fileName); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexRemover.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexRemover.java index ba455ef..0b3b816 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexRemover.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexRemover.java @@ -1,49 +1,49 @@ package eu.svjatoslav.meviz.htmlindexer; +import eu.svjatoslav.commons.file.IOHelper; + import java.io.File; import java.io.IOException; -import eu.svjatoslav.commons.file.IOHelper; - public class FilesystemIndexRemover { - private final CommandlineHandler commandlineHandler; + private final CommandlineHandler commandlineHandler; - public FilesystemIndexRemover(final CommandlineHandler commandlineHandler) - throws IOException { - this.commandlineHandler = commandlineHandler; + public FilesystemIndexRemover(final CommandlineHandler commandlineHandler) + throws IOException { + this.commandlineHandler = commandlineHandler; - removeIndex(commandlineHandler.getWorkingDirectory()); - } + removeIndex(commandlineHandler.getWorkingDirectory()); + } - public void removeIndex(final File workingDirectory) throws IOException { + public void removeIndex(final File workingDirectory) throws IOException { - // remove thumbnails directory from current directory - final File thumbnailsDirectory = Utils - .getThumbnailsDirectory(workingDirectory); - if (thumbnailsDirectory.exists()) { - System.out.println("Deleting thumbnails directory: " - + thumbnailsDirectory); - IOHelper.deleteRecursively(thumbnailsDirectory); - } + // remove thumbnails directory from current directory + final File thumbnailsDirectory = Utils + .getThumbnailsDirectory(workingDirectory); + if (thumbnailsDirectory.exists()) { + System.out.println("Deleting thumbnails directory: " + + thumbnailsDirectory); + IOHelper.deleteRecursively(thumbnailsDirectory); + } - // recursively remove thumbnail directories from sub directories - for (final File subFile : workingDirectory.listFiles()) - if (subFile.isDirectory()) - removeIndex(subFile); + // recursively remove thumbnail directories from sub directories + for (final File subFile : workingDirectory.listFiles()) + if (subFile.isDirectory()) + removeIndex(subFile); - for (final Layout layout : Utils.getLayouts()) { - final File indexFile = Utils.getLayoutIndexFile(layout, - workingDirectory); + for (final Layout layout : Utils.getLayouts()) { + final File indexFile = Utils.getLayoutIndexFile(layout, + workingDirectory); - if (indexFile.exists()) - if (Utils.isMevizGeneratedIndexFile(indexFile)) { - System.out.println("Deleting generated index file: " - + indexFile); - indexFile.delete(); - } - } + if (indexFile.exists()) + if (Utils.isMevizGeneratedIndexFile(indexFile)) { + System.out.println("Deleting generated index file: " + + indexFile); + indexFile.delete(); + } + } - } + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexer.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexer.java index 51d3504..86ad818 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexer.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/FilesystemIndexer.java @@ -9,21 +9,19 @@ package eu.svjatoslav.meviz.htmlindexer; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import org.apache.log4j.Logger; - import eu.svjatoslav.commons.file.IOHelper; import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; import eu.svjatoslav.meviz.htmlindexer.metadata.DirectoryMetadata; import eu.svjatoslav.meviz.htmlindexer.metadata.MetadadaHelper; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; +import org.apache.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; /** * Main class of HTML indexer. @@ -31,180 +29,173 @@ import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; public class FilesystemIndexer extends AbstractIndexer { - public static final Logger logger = Logger - .getLogger(FilesystemIndexer.class); - - private final HashSet validMetadataFiles = new HashSet(); - - private final File directoryToIndex; - - private File metadataFile; - - private DirectoryMetadata metadata; - - private final List pathElements; + public static final Logger logger = Logger + .getLogger(FilesystemIndexer.class); - private HashSet layouts; + private final HashSet validMetadataFiles = new HashSet(); - private final CommandlineHandler commandlineHandler; + private final File directoryToIndex; + private final List pathElements; + private final CommandlineHandler commandlineHandler; + private File metadataFile; + private DirectoryMetadata metadata; + private HashSet layouts; - public FilesystemIndexer(final File directoryToIndex, - final CommandlineHandler commandlineHandler, - final List pathElements) throws Exception { + public FilesystemIndexer(final File directoryToIndex, + final CommandlineHandler commandlineHandler, + final List pathElements) throws Exception { - this.directoryToIndex = directoryToIndex; - this.commandlineHandler = commandlineHandler; - this.pathElements = pathElements; + this.directoryToIndex = directoryToIndex; + this.commandlineHandler = commandlineHandler; + this.pathElements = pathElements; - if (!directoryToIndex.canRead()) - return; + if (!directoryToIndex.canRead()) + return; - validMetadataFiles.add(Constants.METADATA_FILE_NAME); + validMetadataFiles.add(Constants.METADATA_FILE_NAME); - initializeThumbnailsDirectory(); - loadOrCreateMetadata(); + initializeThumbnailsDirectory(); + loadOrCreateMetadata(); - initializeLayouts(); + initializeLayouts(); - updateMetadata(); + updateMetadata(); - metadata.removeUnusedMetadataEntries(); + metadata.removeUnusedMetadataEntries(); - generateHtmlFromMetadata(layouts); + generateHtmlFromMetadata(layouts); - removeUnusedThumbnailFiles(); + removeUnusedThumbnailFiles(); - // save directory metadata - if (metadata.changed) - MetadadaHelper.saveDirectoryMetadata(metadataFile, metadata); + // save directory metadata + if (metadata.changed) + MetadadaHelper.saveDirectoryMetadata(metadataFile, metadata); - } + } - public boolean canWriteIndexFile(final File indexFile) - throws FileNotFoundException, IOException { + public boolean canWriteIndexFile(final File indexFile) + throws IOException { - if (!indexFile.exists()) - return true; + return !indexFile.exists() || Utils.isMevizGeneratedIndexFile(indexFile); - return Utils.isMevizGeneratedIndexFile(indexFile); - } + } - public void generateHtmlFromMetadata(final HashSet layouts) { - // Generate HTML from metadata - for (final Layout layout : layouts) - try { - final File indexFile = Utils.getLayoutIndexFile(layout, - directoryToIndex); + public void generateHtmlFromMetadata(final HashSet layouts) { + // Generate HTML from metadata + for (final Layout layout : layouts) + try { + final File indexFile = Utils.getLayoutIndexFile(layout, + directoryToIndex); - if (canWriteIndexFile(indexFile)) { + if (canWriteIndexFile(indexFile)) { - compileHtml(layout, metadata); + compileHtml(layout, metadata); - IOHelper.overwriteFileIfContentDiffers(indexFile, layout - .getHtml(true, true, metadata).getBytes()); - } - } catch (final Exception e) { - logger.error("Error writing index file. ", e); - } - } + IOHelper.overwriteFileIfContentDiffers(indexFile, layout + .getHtml(true, true, metadata).getBytes()); + } + } catch (final Exception e) { + logger.error("Error writing index file. ", e); + } + } - public List getChildPath(final File file) { + public List getChildPath(final File file) { - final List result = new ArrayList(); - result.addAll(pathElements); - result.add(file.getName()); + final List result = new ArrayList(); + result.addAll(pathElements); + result.add(file.getName()); - return result; - } + return result; + } - @Override - public String getDirectoryUrl(final AbstractFile directory, - final IndexingContext context) { - return Utils.urlEncode(directory.fileName) + "/index.html"; - } + @Override + public String getDirectoryUrl(final AbstractFile directory, + final IndexingContext context) { + return Utils.urlEncode(directory.fileName) + "/index.html"; + } - @Override - public String getParentDirectoryUrl(final IndexingContext context) { - return "../index.html"; - } + @Override + public String getParentDirectoryUrl(final IndexingContext context) { + return "../index.html"; + } - @Override - public String getThumbnailUrl(final Picture picture, - final Dimension desiredDimension, final IndexingContext context) { + @Override + public String getThumbnailUrl(final Picture picture, + final Dimension desiredDimension, final IndexingContext context) { - // in case thumbnail size was equal to original, then return original - // file path - if (picture.getDimensions().equals(desiredDimension)) - return picture.fileName; + // in case thumbnail size was equal to original, then return original + // file path + if (picture.getDimensions().equals(desiredDimension)) + return picture.fileName; - final String thumbnailFileName = picture - .getRelativeThumbnailFileName(desiredDimension); + final String thumbnailFileName = picture + .getRelativeThumbnailFileName(desiredDimension); - validMetadataFiles.add(thumbnailFileName); - final File thumbnailFile = new File( - Utils.getThumbnailsDirectoryPath(directoryToIndex) - + thumbnailFileName); + validMetadataFiles.add(thumbnailFileName); + final File thumbnailFile = new File( + Utils.getThumbnailsDirectoryPath(directoryToIndex) + + thumbnailFileName); - if (!thumbnailFile.exists()) { + if (!thumbnailFile.exists()) { - final File originalFile = new File( - directoryToIndex.getAbsolutePath() + "/" + picture.fileName); + final File originalFile = new File( + directoryToIndex.getAbsolutePath() + "/" + picture.fileName); - // generate new thumbnail - Picture.makeThumbnail(originalFile, thumbnailFile, - desiredDimension.getAwtDimension()); - } - return Constants.THUMBNAILS_DIRECTORY_NAME + "/" - + Utils.urlEncode(thumbnailFileName); - } + // generate new thumbnail + Picture.makeThumbnail(originalFile, thumbnailFile, + desiredDimension.getAwtDimension()); + } + return Constants.THUMBNAILS_DIRECTORY_NAME + "/" + + Utils.urlEncode(thumbnailFileName); + } - public void initializeLayouts() { + public void initializeLayouts() { - layouts = Utils.getLayouts(); + layouts = Utils.getLayouts(); - final String galleryTitle = commandlineHandler.getGalleryTitle(); + final String galleryTitle = commandlineHandler.getGalleryTitle(); - for (final Layout layout : layouts) - layout.init(galleryTitle, pathElements, this, new IndexingContext( - "", ".")); - } + for (final Layout layout : layouts) + layout.init(galleryTitle, pathElements, this, new IndexingContext( + "", ".")); + } - public void initializeThumbnailsDirectory() { - final File thumbnailsDirectory = Utils - .getThumbnailsDirectory(directoryToIndex); + public void initializeThumbnailsDirectory() { + final File thumbnailsDirectory = Utils + .getThumbnailsDirectory(directoryToIndex); - if (!thumbnailsDirectory.exists()) - thumbnailsDirectory.mkdirs(); - } + if (!thumbnailsDirectory.exists()) + thumbnailsDirectory.mkdirs(); + } - public void loadOrCreateMetadata() { + public void loadOrCreateMetadata() { - metadataFile = new File( - Utils.getThumbnailsDirectoryPath(directoryToIndex) - + Constants.METADATA_FILE_NAME); + metadataFile = new File( + Utils.getThumbnailsDirectoryPath(directoryToIndex) + + Constants.METADATA_FILE_NAME); - metadata = MetadadaHelper.initDirectoryMetadata(metadataFile); - } + metadata = MetadadaHelper.initDirectoryMetadata(metadataFile); + } - private void removeUnusedThumbnailFiles() { + private void removeUnusedThumbnailFiles() { - for (final File file : Utils.getThumbnailsDirectory(directoryToIndex) - .listFiles()) - if (!validMetadataFiles.contains(file.getName())) - file.delete(); + for (final File file : Utils.getThumbnailsDirectory(directoryToIndex) + .listFiles()) + if (!validMetadataFiles.contains(file.getName())) + file.delete(); - } + } - public void updateMetadata() throws Exception { + public void updateMetadata() throws Exception { - for (final File file : directoryToIndex.listFiles()) - if (shallFileBeIndexed(file)) { + for (final File file : directoryToIndex.listFiles()) + if (shallFileBeIndexed(file)) { - metadata.ensureFileMetainfoIsUpToDate(directoryToIndex, file); + metadata.ensureFileMetainfoIsUpToDate(directoryToIndex, file); - if (file.isDirectory()) - new FilesystemIndexer(file, commandlineHandler, - getChildPath(file)); - } - } + if (file.isDirectory()) + new FilesystemIndexer(file, commandlineHandler, + getChildPath(file)); + } + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/ImageFormatError.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/ImageFormatError.java index 783f802..7d40bf4 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/ImageFormatError.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/ImageFormatError.java @@ -11,9 +11,9 @@ package eu.svjatoslav.meviz.htmlindexer; public class ImageFormatError extends Exception { - private static final long serialVersionUID = 4037233564457071385L; + private static final long serialVersionUID = 4037233564457071385L; - public ImageFormatError(final String message) { - super(message); - } + public ImageFormatError(final String message) { + super(message); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/IndexingContext.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/IndexingContext.java index 48c3be2..2ec1bed 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/IndexingContext.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/IndexingContext.java @@ -5,33 +5,33 @@ import java.util.List; public class IndexingContext { - private final String localUrl; - private final String globalUrl; + private final String localUrl; + private final String globalUrl; - public IndexingContext(final String globalUrl, final String localUrl) { - this.globalUrl = globalUrl; - this.localUrl = localUrl; - } + public IndexingContext(final String globalUrl, final String localUrl) { + this.globalUrl = globalUrl; + this.localUrl = localUrl; + } - public String getGlobalUrl() { - return globalUrl; - } + public String getGlobalUrl() { + return globalUrl; + } - public List getLocalPathComponents() { + public List getLocalPathComponents() { - final List result = new ArrayList(); + final List result = new ArrayList(); - final String[] strings = localUrl.split("/"); + final String[] strings = localUrl.split("/"); - for (final String pathElement : strings) - if (pathElement.length() > 0) - result.add(pathElement); + for (final String pathElement : strings) + if (pathElement.length() > 0) + result.add(pathElement); - return result; - } + return result; + } - public String getLocalUrl() { - return localUrl; - } + public String getLocalUrl() { + return localUrl; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Layout.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Layout.java index 4a21863..f9e0982 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Layout.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Layout.java @@ -9,73 +9,72 @@ package eu.svjatoslav.meviz.htmlindexer; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.List; - import eu.svjatoslav.meviz.htmlindexer.metadata.DirectoryMetadata; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.List; + /** * In order to have possibility of several different layouts per directory. * Universal interface is defined. - * + *

* Layout implementation is responsible for actual HTML generation. */ public interface Layout { - /** - * Enlist directory. - */ - public void enlistDirectory(AbstractFile directory, - DirectoryMetadata parentDirectoryMetadata); + /** + * Enlist directory. + */ + void enlistDirectory(AbstractFile directory, + DirectoryMetadata parentDirectoryMetadata); - /** - * Enlist simple file. - */ - public void enlistFile(AbstractFile file, - DirectoryMetadata parentDirectoryMetadata); + /** + * Enlist simple file. + */ + void enlistFile(AbstractFile file, + DirectoryMetadata parentDirectoryMetadata); - /** - * Enlist image file. - */ - public void enlistImage(Picture picture, - DirectoryMetadata parentDirectoryMetadata); + /** + * Enlist image file. + */ + void enlistImage(Picture picture, + DirectoryMetadata parentDirectoryMetadata); - /** - * Enlist video in OGV format. - * - * @throws UnsupportedEncodingException - */ - public void enlistOgv(AbstractFile file, - DirectoryMetadata parentDirectoryMetadata) - throws UnsupportedEncodingException; + /** + * Enlist video in OGV format. + * + * @throws UnsupportedEncodingException + */ + void enlistOgv(AbstractFile file, + DirectoryMetadata parentDirectoryMetadata) + throws UnsupportedEncodingException; - /** - * Return layout specific suffix that will be appended between - * index(suffix).html of generated file. This way multiple layouts can - * coexist in the same directory, each residing in its own HTML file. - */ - public String getFileNameSuffix(); + /** + * Return layout specific suffix that will be appended between + * index(suffix).html of generated file. This way multiple layouts can + * coexist in the same directory, each residing in its own HTML file. + */ + String getFileNameSuffix(); - /** - * After necessary files have been enlisted for particular directory, use - * this method to retrieve generated HTML result. - * - * @param metadata - * @throws IOException - */ - public String getHtml(final boolean showTitle, - final boolean doHtmlHeaderAndFooter, DirectoryMetadata metadata) - throws IOException; + /** + * After necessary files have been enlisted for particular directory, use + * this method to retrieve generated HTML result. + * + * @throws IOException + */ + String getHtml(final boolean showTitle, + final boolean doHtmlHeaderAndFooter, DirectoryMetadata metadata) + throws IOException; - /** - * Initialize layout for particular directory. - */ - public void init(String galleryTitle, List path, - final AbstractIndexer indexer, IndexingContext context); + /** + * Initialize layout for particular directory. + */ + void init(String galleryTitle, List path, + final AbstractIndexer indexer, IndexingContext context); - public void enlistWebm(AbstractFile file, DirectoryMetadata directory); + void enlistWebm(AbstractFile file, DirectoryMetadata directory); } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Main.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Main.java index 5c469d8..77eb377 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Main.java @@ -1,42 +1,50 @@ package eu.svjatoslav.meviz.htmlindexer; -import java.util.ArrayList; - import eu.svjatoslav.meviz.Module; +import java.util.ArrayList; + public class Main implements Module { - CommandlineHandler commandlineHandler = new CommandlineHandler(); - - /** {@inheritDoc} */ - @Override - public String getDescription() { - return "Generate HTML listing of directories."; - } - - /** {@inheritDoc} */ - @Override - public String getModuleCommand() { - return "index"; - } - - /** {@inheritDoc} */ - @Override - public void run(final String[] args) throws Exception { - - if (commandlineHandler.parseCommandlineArguments(args)) - if (commandlineHandler.removeIndex.isParameterSpecified()) - new FilesystemIndexRemover(commandlineHandler); - else - new FilesystemIndexer(commandlineHandler.getWorkingDirectory(), - commandlineHandler, new ArrayList()); - - } - - /** {@inheritDoc} */ - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - } + CommandlineHandler commandlineHandler = new CommandlineHandler(); + + /** + * {@inheritDoc} + */ + @Override + public String getDescription() { + return "Generate HTML listing of directories."; + } + + /** + * {@inheritDoc} + */ + @Override + public String getModuleCommand() { + return "index"; + } + + /** + * {@inheritDoc} + */ + @Override + public void run(final String[] args) throws Exception { + + if (commandlineHandler.parseCommandlineArguments(args)) + if (commandlineHandler.removeIndex.isParameterSpecified()) + new FilesystemIndexRemover(commandlineHandler); + else + new FilesystemIndexer(commandlineHandler.getWorkingDirectory(), + commandlineHandler, new ArrayList()); + + } + + /** + * {@inheritDoc} + */ + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Utils.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Utils.java index 5cccbc3..028995b 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/Utils.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/Utils.java @@ -9,133 +9,127 @@ package eu.svjatoslav.meviz.htmlindexer; +import eu.svjatoslav.meviz.htmlindexer.layouts.MixedLayout; + +import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.URLEncoder; import java.util.HashSet; import java.util.zip.CRC32; -import javax.imageio.ImageIO; - -import eu.svjatoslav.meviz.htmlindexer.layouts.MixedLayout; - public class Utils { - private static File lastLoadedFile; - private static final String UTF_8 = "UTF-8"; - - private static BufferedImage lastLoadedBufferedImage; - - /** - * Load image into {@link BufferedImage} and return it. Caches last loaded - * image to speed up subsequent loading attempts. - * - * @throws ImageFormatError - * @throws IOException - */ - public static BufferedImage getBufferedImage(final File file) - throws ImageFormatError, IOException { - if (file.equals(lastLoadedFile)) - return lastLoadedBufferedImage; - - System.out.println("Loading image: " + file.getPath()); - lastLoadedBufferedImage = ImageIO.read(file); - lastLoadedFile = file; - - if (lastLoadedBufferedImage == null) { - System.out.println("Error reading image: " + file); - throw new ImageFormatError("File: " + file - + " is not a valid image."); - - } - - return lastLoadedBufferedImage; - } - - public static File getLayoutIndexFile(final Layout layout, - final File directoryToIndex) { - - final String indexFilePath = directoryToIndex.getAbsolutePath() - + "/index" + layout.getFileNameSuffix() + ".html"; - - return new File(indexFilePath); - } - - public static HashSet getLayouts() { - final HashSet layouts = new HashSet(); - layouts.add(new MixedLayout()); - return layouts; - } - - public static String getStringCrcAsHex(final String input) { - - // create a new CRC-calculating object - final CRC32 crc = new CRC32(); - - // loop, calculating CRC for each byte of the string - // There is no CRC16.update(byte[]) method. - for (final byte b : input.getBytes()) - crc.update(b); - - // note use crc.value, not crc.getValue() - final String hex = Integer.toHexString((int) crc.getValue()) - .toUpperCase(); - - // System.out.println("Input string: " + input); - // System.out.println("Result: " + hex); - - return hex; - } - - public static File getThumbnailsDirectory(final File directoryToIndex) { - return new File(getThumbnailsDirectoryPath(directoryToIndex)); - } - - public static String getThumbnailsDirectoryPath(final File directoryToIndex) { - return directoryToIndex.getAbsolutePath() + "/" - + Constants.THUMBNAILS_DIRECTORY_NAME + "/"; - } - - public static boolean isMevizGeneratedIndexFile(final File indexFile) - throws FileNotFoundException, IOException { - - boolean isMevizFile = false; - - final FileReader fileReader = new FileReader(indexFile); - final BufferedReader reader = new BufferedReader(fileReader); - - parseFile: { - while (true) { - final String line = reader.readLine(); - - if (line == null) - break parseFile; - - if (line.contains(Constants.HTML_MAGIC_STRING)) { - isMevizFile = true; - break parseFile; - } - } - } - - reader.close(); - fileReader.close(); - return isMevizFile; - } + private static final String UTF_8 = "UTF-8"; + private static File lastLoadedFile; + private static BufferedImage lastLoadedBufferedImage; - public static String urlEncode(String string) { - if (string.startsWith("./")) - string = string.substring(2); - - try { - return URLEncoder.encode(string, UTF_8).replace("+", "%20"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } + /** + * Load image into {@link BufferedImage} and return it. Caches last loaded + * image to speed up subsequent loading attempts. + * + * @throws ImageFormatError + * @throws IOException + */ + public static BufferedImage getBufferedImage(final File file) + throws ImageFormatError, IOException { + if (file.equals(lastLoadedFile)) + return lastLoadedBufferedImage; + + System.out.println("Loading image: " + file.getPath()); + lastLoadedBufferedImage = ImageIO.read(file); + lastLoadedFile = file; + + if (lastLoadedBufferedImage == null) { + System.out.println("Error reading image: " + file); + throw new ImageFormatError("File: " + file + + " is not a valid image."); + + } + + return lastLoadedBufferedImage; + } + + public static File getLayoutIndexFile(final Layout layout, + final File directoryToIndex) { + + final String indexFilePath = directoryToIndex.getAbsolutePath() + + "/index" + layout.getFileNameSuffix() + ".html"; + + return new File(indexFilePath); + } + + public static HashSet getLayouts() { + final HashSet layouts = new HashSet(); + layouts.add(new MixedLayout()); + return layouts; + } + + public static String getStringCrcAsHex(final String input) { + + // create a new CRC-calculating object + final CRC32 crc = new CRC32(); + + // loop, calculating CRC for each byte of the string + // There is no CRC16.update(byte[]) method. + for (final byte b : input.getBytes()) + crc.update(b); + + // note use crc.value, not crc.getValue() + final String hex = Integer.toHexString((int) crc.getValue()) + .toUpperCase(); + + // System.out.println("Input string: " + input); + // System.out.println("Result: " + hex); + + return hex; + } + + public static File getThumbnailsDirectory(final File directoryToIndex) { + return new File(getThumbnailsDirectoryPath(directoryToIndex)); + } + + public static String getThumbnailsDirectoryPath(final File directoryToIndex) { + return directoryToIndex.getAbsolutePath() + "/" + + Constants.THUMBNAILS_DIRECTORY_NAME + "/"; + } + + public static boolean isMevizGeneratedIndexFile(final File indexFile) + throws IOException { + + boolean isMevizFile = false; + + final FileReader fileReader = new FileReader(indexFile); + final BufferedReader reader = new BufferedReader(fileReader); + + parseFile: + { + while (true) { + final String line = reader.readLine(); + + if (line == null) + break parseFile; + + if (line.contains(Constants.HTML_MAGIC_STRING)) { + isMevizFile = true; + break parseFile; + } + } + } + + reader.close(); + fileReader.close(); + return isMevizFile; + } + + public static String urlEncode(String string) { + if (string.startsWith("./")) + string = string.substring(2); + + try { + return URLEncoder.encode(string, UTF_8).replace("+", "%20"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/WebIndexer.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/WebIndexer.java index 7cf1d20..dd52973 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/WebIndexer.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/WebIndexer.java @@ -1,136 +1,131 @@ package eu.svjatoslav.meviz.htmlindexer; +import eu.svjatoslav.meviz.htmlindexer.layouts.MixedLayout; +import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; +import eu.svjatoslav.meviz.htmlindexer.metadata.DirectoryMetadata; +import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; +import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; + import java.io.BufferedInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.List; -import eu.svjatoslav.meviz.htmlindexer.layouts.MixedLayout; -import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; -import eu.svjatoslav.meviz.htmlindexer.metadata.DirectoryMetadata; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; - public class WebIndexer extends AbstractIndexer { - private static final int METADATA_LOAD_TRY_COUNT = 10; - private final String globalPrefix; - private final String jspPath; - - public WebIndexer(final String globalPrefix, final String jspPath) { - this.globalPrefix = globalPrefix; - this.jspPath = jspPath; - } - - @Override - public void compileHtml(final Layout layout, - final DirectoryMetadata directory) - throws UnsupportedEncodingException { - super.compileHtml(layout, directory); - } + private static final int METADATA_LOAD_TRY_COUNT = 10; + private final String globalPrefix; + private final String jspPath; - @Override - public String getDirectoryUrl(final AbstractFile directory, - final IndexingContext context) { + public WebIndexer(final String globalPrefix, final String jspPath) { + this.globalPrefix = globalPrefix; + this.jspPath = jspPath; + } - try { - return jspPath + context.getLocalUrl() + "/" - + URLEncoder.encode(directory.fileName, "UTF-8"); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } + @Override + public void compileHtml(final Layout layout, + final DirectoryMetadata directory) + throws UnsupportedEncodingException { + super.compileHtml(layout, directory); + } - public String getHtml(String requestPath) throws MalformedURLException, - IOException, ClassNotFoundException { + @Override + public String getDirectoryUrl(final AbstractFile directory, + final IndexingContext context) { - if (requestPath == null) - requestPath = ""; + try { + return jspPath + context.getLocalUrl() + "/" + + URLEncoder.encode(directory.fileName, "UTF-8"); + } catch (final UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } - if (requestPath.equals("/")) - requestPath = ""; + public String getHtml(String requestPath) throws + IOException, ClassNotFoundException { - final MixedLayout layout = new MixedLayout(); - final IndexingContext context = new IndexingContext(globalPrefix, - requestPath); - layout.init("Photos", context.getLocalPathComponents(), this, context); + if (requestPath == null) + requestPath = ""; - final DirectoryMetadata directory = getMetadataForPath(requestPath); + if (requestPath.equals("/")) + requestPath = ""; - compileHtml(layout, directory); + final MixedLayout layout = new MixedLayout(); + final IndexingContext context = new IndexingContext(globalPrefix, + requestPath); + layout.init("Photos", context.getLocalPathComponents(), this, context); - return layout.getHtml(false, false, directory); - } + final DirectoryMetadata directory = getMetadataForPath(requestPath); - public DirectoryMetadata getMetadataForPath(final String requestPath) - throws ClassNotFoundException, IOException { + compileHtml(layout, directory); - final StringBuffer urlStringBuffer = new StringBuffer(); + return layout.getHtml(false, false, directory); + } - urlStringBuffer.append(globalPrefix); - urlStringBuffer.append(Utils.urlEncode(requestPath)); - urlStringBuffer.append("/.thumbnails/metadata_6.dat"); + public DirectoryMetadata getMetadataForPath(final String requestPath) + throws ClassNotFoundException, IOException { - final String urlString = urlStringBuffer.toString(); + final String urlString = globalPrefix + + Utils.urlEncode(requestPath) + + "/.thumbnails/metadata_6.dat"; - IOException exception = null; + IOException exception = null; - for (int i = 0; i < METADATA_LOAD_TRY_COUNT; i++) - try { + for (int i = 0; i < METADATA_LOAD_TRY_COUNT; i++) + try { - final BufferedInputStream in = new BufferedInputStream(new URL( - urlString).openStream()); + final BufferedInputStream in = new BufferedInputStream(new URL( + urlString).openStream()); - final ObjectInputStream oin = new ObjectInputStream(in); - final DirectoryMetadata directory = (DirectoryMetadata) oin - .readObject(); - in.close(); + final ObjectInputStream oin = new ObjectInputStream(in); + final DirectoryMetadata directory = (DirectoryMetadata) oin + .readObject(); + in.close(); - return directory; - } catch (final IOException e) { - exception = e; - } + return directory; + } catch (final IOException e) { + exception = e; + } - throw exception; - } + throw exception; + } - @Override - public String getParentDirectoryUrl(final IndexingContext context) { - final StringBuffer result = new StringBuffer(); + @Override + public String getParentDirectoryUrl(final IndexingContext context) { + final StringBuilder result = new StringBuilder(); - result.append(jspPath); + result.append(jspPath); - final List components = context.getLocalPathComponents(); + final List components = context.getLocalPathComponents(); - for (final String pathComponent : components.subList(0, - components.size() - 1)) { - result.append("/"); - result.append(pathComponent); - } + for (final String pathComponent : components.subList(0, + components.size() - 1)) { + result.append("/"); + result.append(pathComponent); + } - return result.toString(); - } + return result.toString(); + } - @Override - public String getThumbnailUrl(final Picture picture, - final Dimension desiredDimension, final IndexingContext context) { + @Override + public String getThumbnailUrl(final Picture picture, + final Dimension desiredDimension, final IndexingContext context) { - // in case thumbnail size was equal to original, then return original - // file path - if (picture.getDimensions().equals(desiredDimension)) - return context.getGlobalUrl() + context.getLocalUrl() + "/" - + picture.fileName; + // in case thumbnail size was equal to original, then return original + // file path + if (picture.getDimensions().equals(desiredDimension)) + return context.getGlobalUrl() + context.getLocalUrl() + "/" + + picture.fileName; - final String thumbnailFileName = picture - .getRelativeThumbnailFileName(desiredDimension); + final String thumbnailFileName = picture + .getRelativeThumbnailFileName(desiredDimension); - return context.getGlobalUrl() + context.getLocalUrl() + "/" - + Constants.THUMBNAILS_DIRECTORY_NAME + "/" - + Utils.urlEncode(thumbnailFileName); - } + return context.getGlobalUrl() + context.getLocalUrl() + "/" + + Constants.THUMBNAILS_DIRECTORY_NAME + "/" + + Utils.urlEncode(thumbnailFileName); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/layouts/MixedLayout.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/layouts/MixedLayout.java index cf1285e..ebc5ca2 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/layouts/MixedLayout.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/layouts/MixedLayout.java @@ -9,304 +9,303 @@ package eu.svjatoslav.meviz.htmlindexer.layouts; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import org.apache.log4j.Logger; - import eu.svjatoslav.commons.file.FilePathParser; -import eu.svjatoslav.meviz.htmlindexer.AbstractIndexer; -import eu.svjatoslav.meviz.htmlindexer.Constants; -import eu.svjatoslav.meviz.htmlindexer.IndexingContext; -import eu.svjatoslav.meviz.htmlindexer.Layout; -import eu.svjatoslav.meviz.htmlindexer.Utils; +import eu.svjatoslav.meviz.htmlindexer.*; import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; import eu.svjatoslav.meviz.htmlindexer.metadata.DirectoryMetadata; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.GeneralFile; import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; +import org.apache.log4j.Logger; -public class MixedLayout implements Layout { +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.List; - public static final String encoding = "UTF-8"; +public class MixedLayout implements Layout { - Logger logger = Logger.getLogger(MixedLayout.class); + public static final String encoding = "UTF-8"; - StringBuffer dirHtml = new StringBuffer(); + Logger logger = Logger.getLogger(MixedLayout.class); - StringBuffer filesHtml = new StringBuffer(); + StringBuffer dirHtml = new StringBuffer(); - String galleryTitle; + StringBuffer filesHtml = new StringBuffer(); - List path; + String galleryTitle; - private AbstractIndexer indexer; + List path; - private IndexingContext indexingContext; + private AbstractIndexer indexer; - @Override - public void enlistDirectory(final AbstractFile directory, - final DirectoryMetadata parentDirectoryMetadata) { - dirHtml.append(""); - dirHtml.append("

==> " + directory.fileName + "

"); - dirHtml.append("\n"); + private IndexingContext indexingContext; - } - - @Override - public void enlistFile(final AbstractFile file, - final DirectoryMetadata parentDirectoryMetadata) { - - final String fullFileName = file.fileName; - - filesHtml.append("
" + fullFileName + "\n"); - filesHtml.append("  (" - + FilePathParser.getFileSizeDescription(file.getFileLength()) - + ")

\n"); - - } - - @Override - public void enlistImage(final Picture picture, - final DirectoryMetadata parentDirectoryMetadata) { - try { - enlistImageInternal(picture); - } catch (final Exception e) { - logger.error( - "Error generating thumbnails for image file: " - + e.toString() - + ", thumbnail generation skipped, enlisting as ordinary file instead.", - e); - enlistFile(picture, parentDirectoryMetadata); - } - } - - private String enlistImageDimensions(final Picture picture) { - final StringBuilder html = new StringBuilder(); - - final List recommendedDimensions = Picture - .getThumbnailDimensions(picture.getDimensions()); - - int count = 0; - for (final Dimension dimension : recommendedDimensions) { - count++; - if (count > 1) - html.append(", "); - html.append(""); - html.append(dimension.width + "x" + dimension.height); - html.append(""); - } - - return html.toString(); - } - - private void enlistImageInternal(final Picture picture) { - - filesHtml.append("
"); - - // clickable image thumbnail - filesHtml.append("\n"); - - filesHtml.append("
\n"); - - // file name - filesHtml.append("" - + FilePathParser.getFileNameWithoutExtension(picture.fileName) - + "
"); - - // links to thumbnails of various sizes - filesHtml.append("(" + enlistImageDimensions(picture) + ")\n"); - - filesHtml.append("
"); - } - - /** {@inheritDoc} */ - @Override - public void enlistOgv(final AbstractFile abstractFile, - final DirectoryMetadata parentDirectoryMetadata) - throws UnsupportedEncodingException { - - final GeneralFile file = (GeneralFile) abstractFile; - - filesHtml.append("
"); - - // watchable video - filesHtml - .append("\n"); - filesHtml.append("
\n"); - - // video title - filesHtml - .append("Video: " - + FilePathParser - .getFileNameWithoutExtension(file.fileName) - + "            "); - - // video download link - filesHtml.append("download as OGV file"); - - filesHtml.append("
\n"); - - filesHtml.append("\n"); - - } - - /** {@inheritDoc} */ - @Override - public String getFileNameSuffix() { - return ""; - } - - /** - * {@inheritDoc} - * - * @throws IOException - */ - @Override - public String getHtml(final boolean showTitle, - final boolean doHtmlHeaderAndFooter, - final DirectoryMetadata directory) { - - // assemble final page HTML - final StringBuffer html = new StringBuffer(); - - if (doHtmlHeaderAndFooter) { - // page header - html.append("\n"); - html.append("\n"); - html.append(" \n"); - html.append("\n"); - html.append("\n"); - html.append("\n"); - html.append("\n"); - html.append("\n"); - } - - if (showTitle) - html.append("

" + galleryTitle + "

\n"); - - html.append(showCurrentPath()); - html.append(listDirectories()); - html.append(directory.getHeaderMevizMetadataHtml()); - html.append(filesHtml.toString()); - - if (doHtmlHeaderAndFooter) - html.append("
\n"); - - return html.toString(); - } - - private String getImageThumbnailUrl(final Picture picture) { - final Dimension imageSize = picture.getDimensions(); - - Dimension listingDimension = new Dimension(1500, 450); - - if (listingDimension.width > imageSize.width) - if (listingDimension.height > imageSize.height) - listingDimension = imageSize; - - return indexer.getThumbnailUrl(picture, listingDimension, - indexingContext); - } - - @Override - public void init(final String galleryTitle, final List path, - final AbstractIndexer indexer, final IndexingContext indexingContext) { - - this.indexer = indexer; - this.galleryTitle = galleryTitle; - this.path = path; - this.indexingContext = indexingContext; - - dirHtml = new StringBuffer(); - filesHtml = new StringBuffer(); - } - - private String listDirectories() { - final StringBuilder html = new StringBuilder(); - html.append("\n"); - - if (path.size() > 0) { - html.append(""); - html.append(""); - html.append("\n"); - } - - html.append(dirHtml.toString()); - html.append("\n\n"); - html.append("

<== parent directory


\n"); - - return html.toString(); - } - - private String showCurrentPath() { - final StringBuilder html = new StringBuilder(); - html.append("

"); - for (final String p : path) - html.append(" / " + p); - html.append("

\n"); - - return html.toString(); - } - - @Override - public void enlistWebm(AbstractFile abstractFile, - DirectoryMetadata directory) { - final GeneralFile file = (GeneralFile) abstractFile; - - filesHtml.append("
"); - - // watchable video - - String fileUrl = indexingContext.getGlobalUrl() - + Utils.urlEncode(indexingContext.getLocalUrl() + "/" - + file.fileName); - - filesHtml.append("\n"); - filesHtml.append("
\n"); - - // video title - filesHtml - .append("Video: " - + FilePathParser - .getFileNameWithoutExtension(file.fileName) - + "            "); - - // video download link - filesHtml.append("download as WebM file"); - - filesHtml.append("
\n"); + @Override + public void enlistDirectory(final AbstractFile directory, + final DirectoryMetadata parentDirectoryMetadata) { + dirHtml.append(""); + dirHtml.append("

==> " + directory.fileName + "

"); + dirHtml.append("\n"); + + } + + @Override + public void enlistFile(final AbstractFile file, + final DirectoryMetadata parentDirectoryMetadata) { + + final String fullFileName = file.fileName; + + filesHtml.append("
" + fullFileName + "\n"); + filesHtml.append("  (" + + FilePathParser.getFileSizeDescription(file.getFileLength()) + + ")

\n"); + + } + + @Override + public void enlistImage(final Picture picture, + final DirectoryMetadata parentDirectoryMetadata) { + try { + enlistImageInternal(picture); + } catch (final Exception e) { + logger.error( + "Error generating thumbnails for image file: " + + e.toString() + + ", thumbnail generation skipped, enlisting as ordinary file instead.", + e); + enlistFile(picture, parentDirectoryMetadata); + } + } + + private String enlistImageDimensions(final Picture picture) { + final StringBuilder html = new StringBuilder(); + + final List recommendedDimensions = Picture + .getThumbnailDimensions(picture.getDimensions()); + + int count = 0; + for (final Dimension dimension : recommendedDimensions) { + count++; + if (count > 1) + html.append(", "); + html.append(""); + html.append(dimension.width + "x" + dimension.height); + html.append(""); + } + + return html.toString(); + } + + private void enlistImageInternal(final Picture picture) { + + filesHtml.append("
"); + + // clickable image thumbnail + filesHtml.append("\n"); + + filesHtml.append("
\n"); + + // file name + filesHtml.append("" + + FilePathParser.getFileNameWithoutExtension(picture.fileName) + + "
"); + + // links to thumbnails of various sizes + filesHtml.append("(" + enlistImageDimensions(picture) + ")\n"); + + filesHtml.append("
"); + } + + /** + * {@inheritDoc} + */ + @Override + public void enlistOgv(final AbstractFile abstractFile, + final DirectoryMetadata parentDirectoryMetadata) + throws UnsupportedEncodingException { + + final GeneralFile file = (GeneralFile) abstractFile; + + filesHtml.append("
"); + + // watchable video + filesHtml + .append("\n"); + filesHtml.append("
\n"); + + // video title + filesHtml + .append("Video: " + + FilePathParser + .getFileNameWithoutExtension(file.fileName) + + "            "); + + // video download link + filesHtml.append("download as OGV file"); + + filesHtml.append("
\n"); + + filesHtml.append("\n"); + + } + + /** + * {@inheritDoc} + */ + @Override + public String getFileNameSuffix() { + return ""; + } + + /** + * {@inheritDoc} + * + * @throws IOException + */ + @Override + public String getHtml(final boolean showTitle, + final boolean doHtmlHeaderAndFooter, + final DirectoryMetadata directory) { + + // assemble final page HTML + final StringBuilder html = new StringBuilder(); + + if (doHtmlHeaderAndFooter) { + // page header + html.append("\n"); + html.append("\n"); + html.append(" \n"); + html.append("\n"); + html.append("\n"); + html.append("\n"); + html.append("\n"); + html.append("\n"); + } + + if (showTitle) + html.append("

" + galleryTitle + "

\n"); + + html.append(showCurrentPath()); + html.append(listDirectories()); + html.append(directory.getHeaderMevizMetadataHtml()); + html.append(filesHtml.toString()); + + if (doHtmlHeaderAndFooter) + html.append("
\n"); + + return html.toString(); + } + + private String getImageThumbnailUrl(final Picture picture) { + final Dimension imageSize = picture.getDimensions(); + + Dimension listingDimension = new Dimension(1500, 450); + + if (listingDimension.width > imageSize.width) + if (listingDimension.height > imageSize.height) + listingDimension = imageSize; + + return indexer.getThumbnailUrl(picture, listingDimension, + indexingContext); + } + + @Override + public void init(final String galleryTitle, final List path, + final AbstractIndexer indexer, final IndexingContext indexingContext) { + + this.indexer = indexer; + this.galleryTitle = galleryTitle; + this.path = path; + this.indexingContext = indexingContext; + + dirHtml = new StringBuffer(); + filesHtml = new StringBuffer(); + } + + private String listDirectories() { + final StringBuilder html = new StringBuilder(); + html.append("\n"); + + if (path.size() > 0) { + html.append(""); + html.append(""); + html.append("\n"); + } + + html.append(dirHtml.toString()); + html.append("\n\n"); + html.append("

<== parent directory


\n"); + + return html.toString(); + } + + private String showCurrentPath() { + final StringBuilder html = new StringBuilder(); + html.append("

"); + for (final String p : path) + html.append(" / " + p); + html.append("

\n"); + + return html.toString(); + } + + @Override + public void enlistWebm(AbstractFile abstractFile, + DirectoryMetadata directory) { + final GeneralFile file = (GeneralFile) abstractFile; + + filesHtml.append("
"); + + // watchable video + + String fileUrl = indexingContext.getGlobalUrl() + + Utils.urlEncode(indexingContext.getLocalUrl() + "/" + + file.fileName); + + filesHtml.append("\n"); + filesHtml.append("
\n"); + + // video title + filesHtml + .append("Video: " + + FilePathParser + .getFileNameWithoutExtension(file.fileName) + + "            "); + + // video download link + filesHtml.append("download as WebM file"); + + filesHtml.append("
\n"); - filesHtml.append("\n"); - } + filesHtml.append("\n"); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/Dimension.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/Dimension.java index e9993b1..db51f50 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/Dimension.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/Dimension.java @@ -17,67 +17,65 @@ import java.io.Serializable; public class Dimension implements Serializable, Comparable { - private static final long serialVersionUID = -1039288266937331829L; - - public int width; - public int height; - - public Dimension() { - width = 0; - height = 0; - } - - public Dimension(final Dimension origial) { - width = origial.width; - height = origial.height; - } - - public Dimension(final int width, final int height) { - this.width = width; - this.height = height; - } - - @Override - public int compareTo(final Dimension anotherDimension) { - if (width < anotherDimension.width) - return -1; - if (width > anotherDimension.width) - return 1; - - if (height < anotherDimension.height) - return -1; - if (height > anotherDimension.height) - return 1; - - return 0; - } - - public boolean equals(final Dimension anotherDimension) { - if (compareTo(anotherDimension) == 0) - return true; - return false; - } - - public int getArea() { - return width * height; - } - - public java.awt.Dimension getAwtDimension() { - return new java.awt.Dimension(width, height); - } - - public Dimension getScaled(final double multiplicationFactor) { - final Dimension result = new Dimension(); - - result.width = (int) ((width) * multiplicationFactor); - result.height = (int) ((height) * multiplicationFactor); - - return result; - } - - @Override - public String toString() { - return "Dimension [width=" + width + ", height=" + height + "]"; - } + private static final long serialVersionUID = -1039288266937331829L; + + public int width; + public int height; + + public Dimension() { + width = 0; + height = 0; + } + + public Dimension(final Dimension origial) { + width = origial.width; + height = origial.height; + } + + public Dimension(final int width, final int height) { + this.width = width; + this.height = height; + } + + @Override + public int compareTo(final Dimension anotherDimension) { + if (width < anotherDimension.width) + return -1; + if (width > anotherDimension.width) + return 1; + + if (height < anotherDimension.height) + return -1; + if (height > anotherDimension.height) + return 1; + + return 0; + } + + public boolean equals(final Dimension anotherDimension) { + return compareTo(anotherDimension) == 0; + } + + public int getArea() { + return width * height; + } + + public java.awt.Dimension getAwtDimension() { + return new java.awt.Dimension(width, height); + } + + public Dimension getScaled(final double multiplicationFactor) { + final Dimension result = new Dimension(); + + result.width = (int) ((width) * multiplicationFactor); + result.height = (int) ((height) * multiplicationFactor); + + return result; + } + + @Override + public String toString() { + return "Dimension [width=" + width + ", height=" + height + "]"; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/DirectoryMetadata.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/DirectoryMetadata.java index 84fad12..0dcdf12 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/DirectoryMetadata.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/DirectoryMetadata.java @@ -9,146 +9,137 @@ package eu.svjatoslav.meviz.htmlindexer.metadata; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; - import eu.svjatoslav.commons.file.FilePathParser; import eu.svjatoslav.meviz.htmlindexer.AbstractIndexer; import eu.svjatoslav.meviz.htmlindexer.FileSortComparator; import eu.svjatoslav.meviz.htmlindexer.ImageFormatError; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.AbstractFile; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.DirectoryFile; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.GeneralFile; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.MevizSpecialFile; -import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.Picture; +import eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes.*; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.util.*; /** * Corresponds to single filesystem directory. */ public class DirectoryMetadata implements Serializable { - private static final long serialVersionUID = 3526489102725366334L; + private static final long serialVersionUID = 3526489102725366334L; - private final HashMap fileNameToFileMap = new HashMap(); + private final HashMap fileNameToFileMap = new HashMap(); - public transient boolean changed; + public transient boolean changed; - /** - * Performs cleanup of directory model. In particular removes metadata for - * images that no longer exist in the filesystem. - */ - public void cleanup() { - final Iterator fileIterator = fileNameToFileMap.values() - .iterator(); + /** + * Performs cleanup of directory model. In particular removes metadata for + * images that no longer exist in the filesystem. + */ + public void cleanup() { + final Iterator fileIterator = fileNameToFileMap.values() + .iterator(); - while (fileIterator.hasNext()) { - final AbstractFile file = fileIterator.next(); + while (fileIterator.hasNext()) { + final AbstractFile file = fileIterator.next(); - if (!file.isMetaInfoVerified()) - fileIterator.remove(); - } - } + if (!file.isMetaInfoVerified()) + fileIterator.remove(); + } + } - public void ensureFileMetainfoIsUpToDate(final File parentDirectory, - final File file) throws Exception { + public void ensureFileMetainfoIsUpToDate(final File parentDirectory, + final File file) throws Exception { - final String fileName = file.getName(); + final String fileName = file.getName(); - if (fileNameToFileMap.containsKey(fileName)) { - final boolean metainfoUpdated = fileNameToFileMap.get(fileName) - .ensureFileMetainfoIsUpToDate(parentDirectory); + if (fileNameToFileMap.containsKey(fileName)) { + final boolean metainfoUpdated = fileNameToFileMap.get(fileName) + .ensureFileMetainfoIsUpToDate(parentDirectory); - if (metainfoUpdated) - changed = true; - } else - registerFile(parentDirectory, file); + if (metainfoUpdated) + changed = true; + } else + registerFile(parentDirectory, file); - } + } - private AbstractFile getAbstractFile(final File parentDirectory, - final File file, final String fileName) throws Exception { + private AbstractFile getAbstractFile(final File parentDirectory, + final File file, final String fileName) throws Exception { - if (file.isDirectory()) - return new DirectoryFile(parentDirectory, fileName); + if (file.isDirectory()) + return new DirectoryFile(parentDirectory, fileName); - final String fileExtension = FilePathParser.getFileExtension(fileName) - .toLowerCase(); + final String fileExtension = FilePathParser.getFileExtension(fileName) + .toLowerCase(); - if (AbstractIndexer.isImage(fileExtension)) - try { - return new Picture(parentDirectory, fileName); - } catch (final Exception exception) { - // in case image decoding failed, handle image as general file - return new GeneralFile(parentDirectory, fileName); - } + if (AbstractIndexer.isImage(fileExtension)) + try { + return new Picture(parentDirectory, fileName); + } catch (final Exception exception) { + // in case image decoding failed, handle image as general file + return new GeneralFile(parentDirectory, fileName); + } - if (fileName.endsWith(".meviz.org")) - return new MevizSpecialFile(parentDirectory, fileName); + if (fileName.endsWith(".meviz.org")) + return new MevizSpecialFile(parentDirectory, fileName); - if (fileName.endsWith(".meviz.html")) - return new MevizSpecialFile(parentDirectory, fileName); + if (fileName.endsWith(".meviz.html")) + return new MevizSpecialFile(parentDirectory, fileName); - return new GeneralFile(parentDirectory, fileName); - } + return new GeneralFile(parentDirectory, fileName); + } - public AbstractFile getFile(final String fileName) { - return fileNameToFileMap.get(fileName); - } + public AbstractFile getFile(final String fileName) { + return fileNameToFileMap.get(fileName); + } - public Collection getFiles() { + public Collection getFiles() { - final ArrayList files = new ArrayList( - fileNameToFileMap.values()); + final ArrayList files = new ArrayList( + fileNameToFileMap.values()); - Collections.sort(files, new FileSortComparator()); + Collections.sort(files, new FileSortComparator()); - return files; - } + return files; + } - public String getHeaderMevizMetadataHtml() { - final AbstractFile headerFile = getFile("header.meviz.html"); - if (headerFile == null) - return ""; + public String getHeaderMevizMetadataHtml() { + final AbstractFile headerFile = getFile("header.meviz.html"); + if (headerFile == null) + return ""; - final MevizSpecialFile mevizSpecialFile = (MevizSpecialFile) headerFile; - return mevizSpecialFile.getFileContent(); - } + final MevizSpecialFile mevizSpecialFile = (MevizSpecialFile) headerFile; + return mevizSpecialFile.getFileContent(); + } - public Dimension getImageDimensions(final String fileName) - throws IOException, ImageFormatError { + public Dimension getImageDimensions(final String fileName) + throws IOException, ImageFormatError { - return ((Picture) getFile(fileName)).getDimensions(); - } + return ((Picture) getFile(fileName)).getDimensions(); + } - public AbstractFile registerFile(final File parentDirectory, final File file) - throws Exception { + public AbstractFile registerFile(final File parentDirectory, final File file) + throws Exception { - final String fileName = file.getName(); + final String fileName = file.getName(); - final AbstractFile abstractFile = getAbstractFile(parentDirectory, - file, fileName); + final AbstractFile abstractFile = getAbstractFile(parentDirectory, + file, fileName); - fileNameToFileMap.put(fileName, abstractFile); + fileNameToFileMap.put(fileName, abstractFile); - changed = true; + changed = true; - return abstractFile; - } + return abstractFile; + } - public void removeUnusedMetadataEntries() { + public void removeUnusedMetadataEntries() { - for (final String key : new HashSet(fileNameToFileMap.keySet())) - if (!fileNameToFileMap.get(key).isMetaInfoVerified()) { - fileNameToFileMap.remove(key); - changed = true; - } + for (final String key : new HashSet(fileNameToFileMap.keySet())) + if (!fileNameToFileMap.get(key).isMetaInfoVerified()) { + fileNameToFileMap.remove(key); + changed = true; + } - } + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/MetadadaHelper.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/MetadadaHelper.java index 0877a98..0013d1c 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/MetadadaHelper.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/MetadadaHelper.java @@ -9,60 +9,54 @@ package eu.svjatoslav.meviz.htmlindexer.metadata; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - +import eu.svjatoslav.commons.file.IOHelper; import org.apache.log4j.Logger; -import eu.svjatoslav.commons.file.IOHelper; +import java.io.*; public class MetadadaHelper { - public static final Logger logger = Logger.getLogger(MetadadaHelper.class); - - /** - * Load previously generated or initialize new directory metadata. - */ - public static DirectoryMetadata initDirectoryMetadata( - final File metadataFile) { - - if (!metadataFile.exists()) - return new DirectoryMetadata(); - else - try { - - final ObjectInputStream in = new ObjectInputStream( - new FileInputStream(metadataFile)); - final DirectoryMetadata directory = (DirectoryMetadata) in - .readObject(); - in.close(); - - return directory; - - } catch (final Exception exception) { - logger.error("Cannot load existing directory metadata.", - exception); - - return new DirectoryMetadata(); - } - } - - public static void saveDirectoryMetadata(final File persistanceFile, - final DirectoryMetadata directory) throws IOException { - // serialize directory metadata into byte array - final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - final ObjectOutputStream out = new ObjectOutputStream( - byteArrayOutputStream); - out.writeObject(directory); - out.close(); - - // store byte array into file - IOHelper.saveToFile(persistanceFile, - byteArrayOutputStream.toByteArray()); - } + public static final Logger logger = Logger.getLogger(MetadadaHelper.class); + + /** + * Load previously generated or initialize new directory metadata. + */ + public static DirectoryMetadata initDirectoryMetadata( + final File metadataFile) { + + if (!metadataFile.exists()) + return new DirectoryMetadata(); + else + try { + + final ObjectInputStream in = new ObjectInputStream( + new FileInputStream(metadataFile)); + final DirectoryMetadata directory = (DirectoryMetadata) in + .readObject(); + in.close(); + + return directory; + + } catch (final Exception exception) { + logger.error("Cannot load existing directory metadata.", + exception); + + return new DirectoryMetadata(); + } + } + + public static void saveDirectoryMetadata(final File persistanceFile, + final DirectoryMetadata directory) throws IOException { + // serialize directory metadata into byte array + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + final ObjectOutputStream out = new ObjectOutputStream( + byteArrayOutputStream); + out.writeObject(directory); + out.close(); + + // store byte array into file + IOHelper.saveToFile(persistanceFile, + byteArrayOutputStream.toByteArray()); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/AbstractFile.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/AbstractFile.java index 5c8b105..9c35a32 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/AbstractFile.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/AbstractFile.java @@ -1,92 +1,92 @@ package eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes; +import eu.svjatoslav.commons.file.FilePathParser; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import eu.svjatoslav.commons.file.FilePathParser; - public abstract class AbstractFile implements Serializable { - private static final long serialVersionUID = -2547388204667088033L; - - /** - * File name relative to the immediate parent directory. - */ - public final String fileName; - - /** - * File length in bytes. - */ - private long fileLength = -1; - - private transient boolean metaInfoVerified; - - public AbstractFile(final File parentDirectory, final String fileName) - throws Exception { - this.fileName = fileName; - ensureFileMetainfoIsUpToDate(parentDirectory); - } - - /** - * @return true if file metadata was updated. - */ - public boolean ensureFileMetainfoIsUpToDate(final File parentDirectory) - throws Exception { - if (!isMetainfoUpToDate(parentDirectory)) { - fileLength = getFile(parentDirectory).length(); - updateFileMetainfo(parentDirectory); - metaInfoVerified = true; - return true; - } - return false; - }; - - public boolean fileExists(final File parentDirectory) { - return getFile(parentDirectory).exists(); - } - - public File getFile(final File parentDirectory) { - return new File(parentDirectory.getAbsolutePath(), fileName); - } - - public String getFileExtension() { - return FilePathParser.getFileExtension(fileName); - } - - public long getFileLength() { - return fileLength; - } - - private boolean isMetainfoUpToDate(final java.io.File parentDirectory) - throws IOException { - - if (metaInfoVerified) - return true; - - final File file = getFile(parentDirectory); - - // first check that file exists at all - if (!file.exists()) { - System.out.println(file); - throw new RuntimeException("Picture file by name \"" + fileName - + "\" does not exist in the parent directory \"" - + parentDirectory.getAbsolutePath() + "\""); - } - - // check that file length is the same as before - if (file.length() != fileLength) - return false; - - metaInfoVerified = true; - return true; - } - - public boolean isMetaInfoVerified() { - return metaInfoVerified; - } - - protected abstract void updateFileMetainfo(final File parentDirectory) - throws Exception; + private static final long serialVersionUID = -2547388204667088033L; + + /** + * File name relative to the immediate parent directory. + */ + public final String fileName; + + /** + * File length in bytes. + */ + private long fileLength = -1; + + private transient boolean metaInfoVerified; + + public AbstractFile(final File parentDirectory, final String fileName) + throws Exception { + this.fileName = fileName; + ensureFileMetainfoIsUpToDate(parentDirectory); + } + + /** + * @return true if file metadata was updated. + */ + public boolean ensureFileMetainfoIsUpToDate(final File parentDirectory) + throws Exception { + if (!isMetainfoUpToDate(parentDirectory)) { + fileLength = getFile(parentDirectory).length(); + updateFileMetainfo(parentDirectory); + metaInfoVerified = true; + return true; + } + return false; + } + + public boolean fileExists(final File parentDirectory) { + return getFile(parentDirectory).exists(); + } + + public File getFile(final File parentDirectory) { + return new File(parentDirectory.getAbsolutePath(), fileName); + } + + public String getFileExtension() { + return FilePathParser.getFileExtension(fileName); + } + + public long getFileLength() { + return fileLength; + } + + private boolean isMetainfoUpToDate(final java.io.File parentDirectory) + throws IOException { + + if (metaInfoVerified) + return true; + + final File file = getFile(parentDirectory); + + // first check that file exists at all + if (!file.exists()) { + System.out.println(file); + throw new RuntimeException("Picture file by name \"" + fileName + + "\" does not exist in the parent directory \"" + + parentDirectory.getAbsolutePath() + "\""); + } + + // check that file length is the same as before + if (file.length() != fileLength) + return false; + + metaInfoVerified = true; + return true; + } + + public boolean isMetaInfoVerified() { + return metaInfoVerified; + } + + protected abstract void updateFileMetainfo(final File parentDirectory) + throws Exception; } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/DirectoryFile.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/DirectoryFile.java index c2f252a..5eff260 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/DirectoryFile.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/DirectoryFile.java @@ -5,16 +5,16 @@ import java.io.IOException; public class DirectoryFile extends AbstractFile { - private static final long serialVersionUID = 2387153281300820532L; + private static final long serialVersionUID = 2387153281300820532L; - public DirectoryFile(final File parentDirectory, final String fileName) - throws Exception { - super(parentDirectory, fileName); - } + public DirectoryFile(final File parentDirectory, final String fileName) + throws Exception { + super(parentDirectory, fileName); + } - @Override - protected void updateFileMetainfo(final File parentDirectory) - throws IOException { - } + @Override + protected void updateFileMetainfo(final File parentDirectory) + throws IOException { + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/GeneralFile.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/GeneralFile.java index 43db928..e449ff0 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/GeneralFile.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/GeneralFile.java @@ -5,16 +5,16 @@ import java.io.IOException; public class GeneralFile extends AbstractFile { - private static final long serialVersionUID = -2373609481729401415L; + private static final long serialVersionUID = -2373609481729401415L; - public GeneralFile(final File parentDirectory, final String fileName) - throws Exception { - super(parentDirectory, fileName); - } + public GeneralFile(final File parentDirectory, final String fileName) + throws Exception { + super(parentDirectory, fileName); + } - @Override - protected void updateFileMetainfo(final File parentDirectory) - throws IOException { - } + @Override + protected void updateFileMetainfo(final File parentDirectory) + throws IOException { + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/MevizSpecialFile.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/MevizSpecialFile.java index 2d3f29d..5973d9d 100644 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/MevizSpecialFile.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/MevizSpecialFile.java @@ -1,31 +1,31 @@ package eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes; +import eu.svjatoslav.commons.file.IOHelper; + import java.io.File; import java.io.IOException; -import eu.svjatoslav.commons.file.IOHelper; - public class MevizSpecialFile extends AbstractFile { - private static final long serialVersionUID = -8749190459653455640L; + private static final long serialVersionUID = -8749190459653455640L; - private String fileContent; + private String fileContent; - public MevizSpecialFile(final File parentDirectory, final String fileName) - throws Exception { - super(parentDirectory, fileName); - } + public MevizSpecialFile(final File parentDirectory, final String fileName) + throws Exception { + super(parentDirectory, fileName); + } - public String getFileContent() { - return fileContent; - } + public String getFileContent() { + return fileContent; + } - @Override - protected void updateFileMetainfo(final File parentDirectory) - throws IOException { + @Override + protected void updateFileMetainfo(final File parentDirectory) + throws IOException { - fileContent = IOHelper - .getFileContentsAsString(getFile(parentDirectory)); - } + fileContent = IOHelper + .getFileContentsAsString(getFile(parentDirectory)); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/Picture.java b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/Picture.java index 274b8ca..7ed4d09 100755 --- a/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/Picture.java +++ b/src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/Picture.java @@ -9,9 +9,14 @@ package eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Toolkit; +import eu.svjatoslav.commons.file.FilePathParser; +import eu.svjatoslav.meviz.htmlindexer.Constants; +import eu.svjatoslav.meviz.htmlindexer.Utils; +import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; @@ -22,171 +27,162 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.List; -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; - -import eu.svjatoslav.commons.file.FilePathParser; -import eu.svjatoslav.meviz.htmlindexer.Constants; -import eu.svjatoslav.meviz.htmlindexer.Utils; -import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension; - public class Picture extends AbstractFile { - private static final long serialVersionUID = -4156533490858298387L; - - private static void ensureNonzeroImageArea(final java.awt.Dimension result) { - if (result.width < 1) - result.width = 1; - if (result.height < 1) - result.height = 1; - } - - /** - * Actual returned target thumbnail size will be adjusted from desired one - * by attempting to generate as large as possible thumbnail, while not - * exceeding provided thumbnail width and height, and preserving aspect - * ratio of original image. - */ - public static java.awt.Dimension getTargetThumbnailDimension( - final java.awt.Dimension originalImageDimension, - final java.awt.Dimension desiredTargetDimension) { - - final double thumbWidthToHeightRatio = (double) desiredTargetDimension.width - / (double) desiredTargetDimension.height; - final double inputImageWidthToHeightRatio = (double) originalImageDimension.width - / (double) originalImageDimension.height; - - if (thumbWidthToHeightRatio < inputImageWidthToHeightRatio) { - - final java.awt.Dimension result = new java.awt.Dimension( - desiredTargetDimension.width, - (int) (desiredTargetDimension.width / inputImageWidthToHeightRatio)); - - ensureNonzeroImageArea(result); - - return result; - } else { - - final java.awt.Dimension result = new java.awt.Dimension( - (int) (desiredTargetDimension.height * inputImageWidthToHeightRatio), - desiredTargetDimension.height); - - ensureNonzeroImageArea(result); - - return result; - } - } - - /** - * Propose list of thumbnail dimensions. - */ - public static List getThumbnailDimensions(Dimension current) { - final ArrayList result = new ArrayList(); - result.add(current); - - while (current.getArea() > 1000000) { - current = current.getScaled(0.5d); - result.add(current); - } - - return result; - - } - - public static void makeThumbnail(final File inputFile, - final File outputFile, - final java.awt.Dimension preferredTargetDimensions) { + private static final long serialVersionUID = -4156533490858298387L; + /** + * Picture dimensions. + */ + private Dimension dimensions; - try { + public Picture(final File parentDirectory, final String fileName) + throws Exception { + super(parentDirectory, fileName); + } - final BufferedImage inputImage = Utils.getBufferedImage(inputFile); + private static void ensureNonzeroImageArea(final java.awt.Dimension result) { + if (result.width < 1) + result.width = 1; + if (result.height < 1) + result.height = 1; + } - final java.awt.Dimension sourceImageDimension = new java.awt.Dimension( - inputImage.getWidth(), inputImage.getHeight()); + /** + * Actual returned target thumbnail size will be adjusted from desired one + * by attempting to generate as large as possible thumbnail, while not + * exceeding provided thumbnail width and height, and preserving aspect + * ratio of original image. + */ + public static java.awt.Dimension getTargetThumbnailDimension( + final java.awt.Dimension originalImageDimension, + final java.awt.Dimension desiredTargetDimension) { - final java.awt.Dimension targetDimensions = getTargetThumbnailDimension( - sourceImageDimension, preferredTargetDimensions); + final double thumbWidthToHeightRatio = (double) desiredTargetDimension.width + / (double) desiredTargetDimension.height; + final double inputImageWidthToHeightRatio = (double) originalImageDimension.width + / (double) originalImageDimension.height; - final OutputStream out = new FileOutputStream(outputFile); + if (thumbWidthToHeightRatio < inputImageWidthToHeightRatio) { - final Image scaledImage = scaleImage(inputImage, - targetDimensions.width, targetDimensions.height); + final java.awt.Dimension result = new java.awt.Dimension( + desiredTargetDimension.width, + (int) (desiredTargetDimension.width / inputImageWidthToHeightRatio)); - final BufferedImage bufferedImage = new BufferedImage( - scaledImage.getWidth(null), scaledImage.getHeight(null), - BufferedImage.TYPE_INT_RGB); + ensureNonzeroImageArea(result); - final Graphics2D g = bufferedImage.createGraphics(); - g.drawImage(scaledImage, 0, 0, null); - g.dispose(); + return result; + } else { - ImageIO.write(bufferedImage, "jpg", out); - out.close(); + final java.awt.Dimension result = new java.awt.Dimension( + (int) (desiredTargetDimension.height * inputImageWidthToHeightRatio), + desiredTargetDimension.height); - } catch (final Exception exception) { - System.out.println(exception.toString()); - exception.printStackTrace(); - } - } + ensureNonzeroImageArea(result); - /** - * @return new image scaled to desired dimensions - */ - public static Image scaleImage(final Image srcImage, final int width, - final int height) { - - final ImageFilter filter = new java.awt.image.AreaAveragingScaleFilter( - width, height); + return result; + } + } - final ImageProducer prod = new FilteredImageSource( - srcImage.getSource(), filter); + /** + * Propose list of thumbnail dimensions. + */ + public static List getThumbnailDimensions(Dimension current) { + final ArrayList result = new ArrayList(); + result.add(current); + + while (current.getArea() > 1000000) { + current = current.getScaled(0.5d); + result.add(current); + } + + return result; + + } + + public static void makeThumbnail(final File inputFile, + final File outputFile, + final java.awt.Dimension preferredTargetDimensions) { + + try { + + final BufferedImage inputImage = Utils.getBufferedImage(inputFile); + + final java.awt.Dimension sourceImageDimension = new java.awt.Dimension( + inputImage.getWidth(), inputImage.getHeight()); + + final java.awt.Dimension targetDimensions = getTargetThumbnailDimension( + sourceImageDimension, preferredTargetDimensions); + + final OutputStream out = new FileOutputStream(outputFile); + + final Image scaledImage = scaleImage(inputImage, + targetDimensions.width, targetDimensions.height); + + final BufferedImage bufferedImage = new BufferedImage( + scaledImage.getWidth(null), scaledImage.getHeight(null), + BufferedImage.TYPE_INT_RGB); + + final Graphics2D g = bufferedImage.createGraphics(); + g.drawImage(scaledImage, 0, 0, null); + g.dispose(); + + ImageIO.write(bufferedImage, "jpg", out); + out.close(); + + } catch (final Exception exception) { + System.out.println(exception.toString()); + exception.printStackTrace(); + } + } - final Image newImage = Toolkit.getDefaultToolkit().createImage(prod); + /** + * @return new image scaled to desired dimensions + */ + public static Image scaleImage(final Image srcImage, final int width, + final int height) { + + final ImageFilter filter = new java.awt.image.AreaAveragingScaleFilter( + width, height); - return new ImageIcon(newImage).getImage(); - }; + final ImageProducer prod = new FilteredImageSource( + srcImage.getSource(), filter); - /** - * Picture dimensions. - */ - private Dimension dimensions; + final Image newImage = Toolkit.getDefaultToolkit().createImage(prod); - public Picture(final File parentDirectory, final String fileName) - throws Exception { - super(parentDirectory, fileName); - } + return new ImageIcon(newImage).getImage(); + } - private String computeThumbnailHash(final Dimension targetDimension) { + private String computeThumbnailHash(final Dimension targetDimension) { - // compute new thumbnails hash number - final String forMagicHash = fileName + " " - + String.valueOf(targetDimension.width) + " " - + String.valueOf(targetDimension.height) + " " - + String.valueOf(getFileLength()) + " " - + Constants.THUMBNAIL_VERSION; + // compute new thumbnails hash number + final String forMagicHash = fileName + " " + + String.valueOf(targetDimension.width) + " " + + String.valueOf(targetDimension.height) + " " + + String.valueOf(getFileLength()) + " " + + Constants.THUMBNAIL_VERSION; - // System.out.println("Computing hash from: " + forMagicHash); - return Utils.getStringCrcAsHex(forMagicHash); - } + // System.out.println("Computing hash from: " + forMagicHash); + return Utils.getStringCrcAsHex(forMagicHash); + } - public Dimension getDimensions() { - return dimensions; - } + public Dimension getDimensions() { + return dimensions; + } - /** - * Get thumbnail file name for this image and desired thumbnail dimensions - * relative to designated thumbnails directory within parent directory. - */ - public String getRelativeThumbnailFileName(final Dimension targetDimension) { - return FilePathParser.getFileNameWithoutExtension(fileName) + " (" - + computeThumbnailHash(targetDimension) + ").jpeg"; - } + /** + * Get thumbnail file name for this image and desired thumbnail dimensions + * relative to designated thumbnails directory within parent directory. + */ + public String getRelativeThumbnailFileName(final Dimension targetDimension) { + return FilePathParser.getFileNameWithoutExtension(fileName) + " (" + + computeThumbnailHash(targetDimension) + ").jpeg"; + } - @Override - public void updateFileMetainfo(final File parentDirectory) throws Exception { - final BufferedImage image = Utils - .getBufferedImage(getFile(parentDirectory)); - dimensions = new Dimension(image.getWidth(), image.getHeight()); - } + @Override + public void updateFileMetainfo(final File parentDirectory) throws Exception { + final BufferedImage image = Utils + .getBufferedImage(getFile(parentDirectory)); + dimensions = new Dimension(image.getWidth(), image.getHeight()); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/renamer/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/renamer/CommandlineHandler.java index 817d5e5..708cf16 100755 --- a/src/main/java/eu/svjatoslav/meviz/renamer/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/renamer/CommandlineHandler.java @@ -9,8 +9,6 @@ package eu.svjatoslav.meviz.renamer; -import java.io.File; - import eu.svjatoslav.commons.commandline.parameterparser.Parser; import eu.svjatoslav.commons.commandline.parameterparser.parameter.DirectoryParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.NullParameter; @@ -18,61 +16,63 @@ import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParamet import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameters; import eu.svjatoslav.meviz.encoder.EncodingOptions; +import java.io.File; + public class CommandlineHandler { - Parser parser = new Parser(); + Parser parser = new Parser(); - NullParameter recursiveParameter = parser.add( - new NullParameter("Enable recursive mode.")).addAliases("-r", - "--recursive"); + NullParameter recursiveParameter = parser.add( + new NullParameter("Enable recursive mode.")).addAliases("-r", + "--recursive"); - NullParameter testParameter = parser.add( - new NullParameter( - "Simulate renaming (no changes will be actually done).")) - .addAliases("-t", "--test"); + NullParameter testParameter = parser.add( + new NullParameter( + "Simulate renaming (no changes will be actually done).")) + .addAliases("-t", "--test"); - StringParameter outputPatternParameter = parser.add( - new StringParameter("Output pattern.")).addAliases("-o", - "--output-pattern"); + StringParameter outputPatternParameter = parser.add( + new StringParameter("Output pattern.")).addAliases("-o", + "--output-pattern"); - StringParameters inputPatternParameter = parser.add( - new StringParameters("File input pattern.")).addAliases("-i", - "--input-pattern"); + StringParameters inputPatternParameter = parser.add( + new StringParameters("File input pattern.")).addAliases("-i", + "--input-pattern"); - DirectoryParameter workingDirectoryParameter = parser - .add(new DirectoryParameter("Working directory.")) - .addAliases("-w", "--working-directory").mustExist(); + DirectoryParameter workingDirectoryParameter = parser + .add(new DirectoryParameter("Working directory.")) + .addAliases("-w", "--working-directory").mustExist(); - /** - * @return {@link EncodingOptions} if commandline arguments were - * successfully parsed, or null if parsing error - * occurred. - */ - public RenamingOptions parseCommandlineArguments(final String[] args) { + /** + * @return {@link EncodingOptions} if commandline arguments were + * successfully parsed, or null if parsing error + * occurred. + */ + public RenamingOptions parseCommandlineArguments(final String[] args) { - final RenamingOptions options = new RenamingOptions(); + final RenamingOptions options = new RenamingOptions(); - if (!parser.parse(args)) - return null; + if (!parser.parse(args)) + return null; - if (testParameter.isParameterSpecified()) - options.testOnly = true; + if (testParameter.isParameterSpecified()) + options.testOnly = true; - if (recursiveParameter.isParameterSpecified()) - options.recursive = true; + if (recursiveParameter.isParameterSpecified()) + options.recursive = true; - if (outputPatternParameter.isParameterSpecified()) - options.outputPattern = outputPatternParameter.getValue(); + if (outputPatternParameter.isParameterSpecified()) + options.outputPattern = outputPatternParameter.getValue(); - if (workingDirectoryParameter.isParameterSpecified()) - options.targetDirectory = workingDirectoryParameter.getValue(); - else - options.targetDirectory = new File(System.getProperty("user.dir")); + if (workingDirectoryParameter.isParameterSpecified()) + options.targetDirectory = workingDirectoryParameter.getValue(); + else + options.targetDirectory = new File(System.getProperty("user.dir")); - // TODO: add multiple input patterns support - if (inputPatternParameter.isParameterSpecified()) - options.inputPatterns.addAll(inputPatternParameter.getValue()); + // TODO: add multiple input patterns support + if (inputPatternParameter.isParameterSpecified()) + options.inputPatterns.addAll(inputPatternParameter.getValue()); - return options; - } + return options; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/renamer/Main.java b/src/main/java/eu/svjatoslav/meviz/renamer/Main.java index 8818889..6495e0f 100755 --- a/src/main/java/eu/svjatoslav/meviz/renamer/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/renamer/Main.java @@ -9,165 +9,163 @@ package eu.svjatoslav.meviz.renamer; -import java.io.File; -import java.util.Arrays; - import eu.svjatoslav.commons.string.WildCardMatcher; import eu.svjatoslav.meviz.Module; -public class Main implements Module { - - CommandlineHandler commandlineHandler = new CommandlineHandler(); - - public int processedFilesCount; - - RenamingOptions options; - - /** - * Verify that program has enough information to start executing - * - * @return true if all is ok, false if errors were found - */ - public boolean checkThatThereIsEnoughDataToProceed() { - if (options.inputPatterns.size() == 0) { - System.out.println("Error: no input patterns given."); - return false; - } - - if (options.outputPattern == null) { - System.out.println("Error: no output pattern given."); - return false; - } - - return true; - } - - public boolean fileMatchesInputPattern(final File file) { - final String fileName = file.getName(); - - for (final String inputPattern : options.inputPatterns) - if (WildCardMatcher.match(fileName, inputPattern)) - return true; +import java.io.File; +import java.util.Arrays; - return false; - } +public class Main implements Module { - @Override - public String getDescription() { - return "Mass rename files according to given pattern."; - } + public int processedFilesCount; + CommandlineHandler commandlineHandler = new CommandlineHandler(); + RenamingOptions options; + + /** + * Verify that program has enough information to start executing + * + * @return true if all is ok, false if errors were found + */ + public boolean checkThatThereIsEnoughDataToProceed() { + if (options.inputPatterns.size() == 0) { + System.out.println("Error: no input patterns given."); + return false; + } + + if (options.outputPattern == null) { + System.out.println("Error: no output pattern given."); + return false; + } + + return true; + } + + public boolean fileMatchesInputPattern(final File file) { + final String fileName = file.getName(); - @Override - public String getModuleCommand() { - return "rename"; - }; + for (final String inputPattern : options.inputPatterns) + if (WildCardMatcher.match(fileName, inputPattern)) + return true; + + return false; + } - private void processDirectory(final File directory) { - final File[] directoryContents = directory.listFiles(); + @Override + public String getDescription() { + return "Mass rename files according to given pattern."; + } - // sort directory contents alphabetically - Arrays.sort(directoryContents); - - for (final File subFile : directoryContents) - if (subFile.isDirectory()) { - if (options.recursive) - processFileOrDirectory(subFile); - } else - processFileOrDirectory(subFile); - } - - private void processFile(final File file) { - final StringBuffer targetFilePath = new StringBuffer(); - - targetFilePath.append(file.getParent()); - targetFilePath.append("/"); - - for (int i = 0; i < options.outputPattern.length(); i++) { - - final char c = options.outputPattern.charAt(i); - - if (c == '*') - targetFilePath.append(file.getName()); - else if (c == '%') { - - final String processedFileCountString = String - .valueOf(processedFilesCount); - - for (int j = 0; j < (5 - processedFileCountString.length()); j++) - targetFilePath.append(0); - - targetFilePath.append(processedFileCountString); - processedFilesCount++; - } else if (c == '_') - targetFilePath.append(" "); - else - targetFilePath.append(c); - } - - final File targetFile = new File(targetFilePath.toString()); - - if (!options.testOnly) { - - if (targetFile.exists()) - System.out.println("Renaming aborted because target file: " - + targetFile.getAbsolutePath() + " already exists."); - else - file.renameTo(targetFile); - - } else { - System.out.println("About to rename file: " - + file.getAbsolutePath()); - System.out.println("into: " + targetFile.getAbsolutePath()); - } - } - - public void processFileOrDirectory(final File file) { - if (!file.exists()) { - System.out.println("Error: file \"" + file.getAbsolutePath() - + "\" does not exist."); - return; - } - - if (file.isDirectory()) - processDirectory(file); - else if (file.isFile()) - if (fileMatchesInputPattern(file)) - processFile(file); - - } - - public void rename() { - processFileOrDirectory(options.targetDirectory); - } - - @Override - public void run(final String[] args) { - - options = commandlineHandler.parseCommandlineArguments(args); - - if (options == null) { - showCommandlineHelp(); - return; - } - - if (checkThatThereIsEnoughDataToProceed()) { - - System.out.println("Renaming using input patterns: "); - for (final String inputPattern : options.inputPatterns) - System.out.println(" " + inputPattern); - - rename(); - } else - showCommandlineHelp(); - } - - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - System.out.println(""); - System.out.println("Output pattern special symbols:"); - System.out.println(" % - file number"); - System.out.println(" * - original file name"); - } + @Override + public String getModuleCommand() { + return "rename"; + } + + private void processDirectory(final File directory) { + final File[] directoryContents = directory.listFiles(); + + // sort directory contents alphabetically + Arrays.sort(directoryContents); + + for (final File subFile : directoryContents) + if (subFile.isDirectory()) { + if (options.recursive) + processFileOrDirectory(subFile); + } else + processFileOrDirectory(subFile); + } + + private void processFile(final File file) { + final StringBuilder targetFilePath = new StringBuilder(); + + targetFilePath.append(file.getParent()); + targetFilePath.append("/"); + + for (int i = 0; i < options.outputPattern.length(); i++) { + + final char c = options.outputPattern.charAt(i); + + if (c == '*') + targetFilePath.append(file.getName()); + else if (c == '%') { + + final String processedFileCountString = String + .valueOf(processedFilesCount); + + for (int j = 0; j < (5 - processedFileCountString.length()); j++) + targetFilePath.append(0); + + targetFilePath.append(processedFileCountString); + processedFilesCount++; + } else if (c == '_') + targetFilePath.append(" "); + else + targetFilePath.append(c); + } + + final File targetFile = new File(targetFilePath.toString()); + + if (!options.testOnly) { + + if (targetFile.exists()) + System.out.println("Renaming aborted because target file: " + + targetFile.getAbsolutePath() + " already exists."); + else + file.renameTo(targetFile); + + } else { + System.out.println("About to rename file: " + + file.getAbsolutePath()); + System.out.println("into: " + targetFile.getAbsolutePath()); + } + } + + public void processFileOrDirectory(final File file) { + if (!file.exists()) { + System.out.println("Error: file \"" + file.getAbsolutePath() + + "\" does not exist."); + return; + } + + if (file.isDirectory()) + processDirectory(file); + else if (file.isFile()) + if (fileMatchesInputPattern(file)) + processFile(file); + + } + + public void rename() { + processFileOrDirectory(options.targetDirectory); + } + + @Override + public void run(final String[] args) { + + options = commandlineHandler.parseCommandlineArguments(args); + + if (options == null) { + showCommandlineHelp(); + return; + } + + if (checkThatThereIsEnoughDataToProceed()) { + + System.out.println("Renaming using input patterns: "); + for (final String inputPattern : options.inputPatterns) + System.out.println(" " + inputPattern); + + rename(); + } else + showCommandlineHelp(); + } + + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + System.out.println(""); + System.out.println("Output pattern special symbols:"); + System.out.println(" % - file number"); + System.out.println(" * - original file name"); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/renamer/RenamingOptions.java b/src/main/java/eu/svjatoslav/meviz/renamer/RenamingOptions.java index 6b74c86..a9a1c04 100755 --- a/src/main/java/eu/svjatoslav/meviz/renamer/RenamingOptions.java +++ b/src/main/java/eu/svjatoslav/meviz/renamer/RenamingOptions.java @@ -14,14 +14,14 @@ import java.util.ArrayList; public class RenamingOptions { - public ArrayList inputPatterns = new ArrayList(); + public ArrayList inputPatterns = new ArrayList(); - public boolean recursive = false; + public boolean recursive = false; - public boolean testOnly = false; + public boolean testOnly = false; - public String outputPattern; + public String outputPattern; - public File targetDirectory; + public File targetDirectory; } diff --git a/src/main/java/eu/svjatoslav/meviz/replace/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/replace/CommandlineHandler.java index 3c4cc56..d8147a1 100755 --- a/src/main/java/eu/svjatoslav/meviz/replace/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/replace/CommandlineHandler.java @@ -9,54 +9,54 @@ package eu.svjatoslav.meviz.replace; -import java.io.File; - import eu.svjatoslav.commons.commandline.parameterparser.Parser; import eu.svjatoslav.commons.commandline.parameterparser.parameter.DirectoryParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.NullParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameter; +import java.io.File; + public class CommandlineHandler { - Parser parser = new Parser(); + Parser parser = new Parser(); - NullParameter recursiveParameter = parser.add( - new NullParameter("Enable recursive mode.")).addAliases("-r", - "--recursive"); + NullParameter recursiveParameter = parser.add( + new NullParameter("Enable recursive mode.")).addAliases("-r", + "--recursive"); - StringParameter searchForPattern = parser - .add(new StringParameter("String to search for")) - .addAliases("-s", "--search-pattern").setMandatory(); + StringParameter searchForPattern = parser + .add(new StringParameter("String to search for")) + .addAliases("-s", "--search-pattern").setMandatory(); - StringParameter replaceWithPattern = parser.add( - new StringParameter("String to place instead")).addAliases("-p", - "--replace-pattern"); + StringParameter replaceWithPattern = parser.add( + new StringParameter("String to place instead")).addAliases("-p", + "--replace-pattern"); - DirectoryParameter directoryParameter = parser - .add(new DirectoryParameter("Working directory.")) - .addAliases("-w", "--working-directory").mustExist(); + DirectoryParameter directoryParameter = parser + .add(new DirectoryParameter("Working directory.")) + .addAliases("-w", "--working-directory").mustExist(); - public CommandlineOptions parseCommandlineArguments(final String[] args) { + public CommandlineOptions parseCommandlineArguments(final String[] args) { - final CommandlineOptions options = new CommandlineOptions(); + final CommandlineOptions options = new CommandlineOptions(); - if (!parser.parse(args)) - return null; + if (!parser.parse(args)) + return null; - if (recursiveParameter.isParameterSpecified()) - options.recursive = true; + if (recursiveParameter.isParameterSpecified()) + options.recursive = true; - if (directoryParameter.isParameterSpecified()) - options.targetDirectory = directoryParameter.getValue(); - else - options.targetDirectory = new File(System.getProperty("user.dir")); + if (directoryParameter.isParameterSpecified()) + options.targetDirectory = directoryParameter.getValue(); + else + options.targetDirectory = new File(System.getProperty("user.dir")); - if (searchForPattern.isParameterSpecified()) - options.searchForPattern = searchForPattern.getValue(); + if (searchForPattern.isParameterSpecified()) + options.searchForPattern = searchForPattern.getValue(); - if (replaceWithPattern.isParameterSpecified()) - options.replaceWithPattern = replaceWithPattern.getValue(); + if (replaceWithPattern.isParameterSpecified()) + options.replaceWithPattern = replaceWithPattern.getValue(); - return options; - } + return options; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/replace/CommandlineOptions.java b/src/main/java/eu/svjatoslav/meviz/replace/CommandlineOptions.java index 3e93006..a522225 100755 --- a/src/main/java/eu/svjatoslav/meviz/replace/CommandlineOptions.java +++ b/src/main/java/eu/svjatoslav/meviz/replace/CommandlineOptions.java @@ -13,12 +13,12 @@ import java.io.File; public class CommandlineOptions { - public String searchForPattern; + public String searchForPattern; - public String replaceWithPattern; + public String replaceWithPattern; - public boolean recursive = false; + public boolean recursive = false; - public File targetDirectory; + public File targetDirectory; } diff --git a/src/main/java/eu/svjatoslav/meviz/replace/Main.java b/src/main/java/eu/svjatoslav/meviz/replace/Main.java index 81ab76d..3f42a9a 100755 --- a/src/main/java/eu/svjatoslav/meviz/replace/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/replace/Main.java @@ -9,101 +9,97 @@ package eu.svjatoslav.meviz.replace; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - import eu.svjatoslav.meviz.Module; +import java.io.*; + public class Main implements Module { - CommandlineHandler commandlineHandler = new CommandlineHandler(); + CommandlineHandler commandlineHandler = new CommandlineHandler(); - CommandlineOptions options; + CommandlineOptions options; - @Override - public String getDescription() { - return "Replace one string to another string in all occurrances and all files recursively."; - } + @Override + public String getDescription() { + return "Replace one string to another string in all occurrances and all files recursively."; + } - @Override - public String getModuleCommand() { - return "replace"; - } + @Override + public String getModuleCommand() { + return "replace"; + } - public void processDirectory(final File directory) { + public void processDirectory(final File directory) { - for (final File file : directory.listFiles()) - if (file.isDirectory()) { - if (options.recursive) - processDirectory(file); - } else - try { - processFile(file); - } catch (final IOException exception) { - System.out.println("Error processing file: " - + file.getAbsolutePath()); - System.out.println(" exception: " - + exception.getMessage()); - } + for (final File file : directory.listFiles()) + if (file.isDirectory()) { + if (options.recursive) + processDirectory(file); + } else + try { + processFile(file); + } catch (final IOException exception) { + System.out.println("Error processing file: " + + file.getAbsolutePath()); + System.out.println(" exception: " + + exception.getMessage()); + } - } + } - public void processFile(final File file) throws IOException { + public void processFile(final File file) throws IOException { - final FileReader fileReader = new FileReader(file); - final BufferedReader bufferedReader = new BufferedReader(fileReader); + final FileReader fileReader = new FileReader(file); + final BufferedReader bufferedReader = new BufferedReader(fileReader); - final StringBuffer result = new StringBuffer(); + final StringBuilder result = new StringBuilder(); - boolean contentChanged = false; + boolean contentChanged = false; - while (true) { - final String line = bufferedReader.readLine(); - if (line == null) - break; + while (true) { + final String line = bufferedReader.readLine(); + if (line == null) + break; - final String newLine = line.replace(options.searchForPattern, - options.replaceWithPattern); + final String newLine = line.replace(options.searchForPattern, + options.replaceWithPattern); - if (!contentChanged) - if (!newLine.equals(line)) - contentChanged = true; + if (!contentChanged) + if (!newLine.equals(line)) + contentChanged = true; - result.append(newLine); - result.append("\n"); - } + result.append(newLine); + result.append("\n"); + } - bufferedReader.close(); - fileReader.close(); + bufferedReader.close(); + fileReader.close(); - if (contentChanged) { - final FileWriter fileWriter = new FileWriter(file); - fileWriter.write(result.toString()); - fileWriter.close(); - } + if (contentChanged) { + final FileWriter fileWriter = new FileWriter(file); + fileWriter.write(result.toString()); + fileWriter.close(); + } - } + } - @Override - public void run(final String[] args) throws IOException { + @Override + public void run(final String[] args) throws IOException { - options = commandlineHandler.parseCommandlineArguments(args); + options = commandlineHandler.parseCommandlineArguments(args); - if (options == null) { - showCommandlineHelp(); - return; - } + if (options == null) { + showCommandlineHelp(); + return; + } - processDirectory(options.targetDirectory); + processDirectory(options.targetDirectory); - } + } - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - } + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/textsplitter/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/textsplitter/CommandlineHandler.java index 713e10f..322d56c 100755 --- a/src/main/java/eu/svjatoslav/meviz/textsplitter/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/textsplitter/CommandlineHandler.java @@ -9,55 +9,55 @@ package eu.svjatoslav.meviz.textsplitter; -import java.io.File; - import eu.svjatoslav.commons.commandline.parameterparser.Parser; import eu.svjatoslav.commons.commandline.parameterparser.parameter.DirectoryParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.NullParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameters; +import java.io.File; + public class CommandlineHandler { - Parser parser = new Parser(); + Parser parser = new Parser(); - NullParameter recursiveParameter = parser.add( - new NullParameter("Enable recursive mode.")).addAliases("-r", - "--recursive"); + NullParameter recursiveParameter = parser.add( + new NullParameter("Enable recursive mode.")).addAliases("-r", + "--recursive"); - StringParameters fileInputPatternsParameter = parser.add( - new StringParameters("File input pattern.").addAliases("-i", - "--input-pattern")).setMandatory(); + StringParameters fileInputPatternsParameter = parser.add( + new StringParameters("File input pattern.").addAliases("-i", + "--input-pattern")).setMandatory(); - StringParameters splitPatternsParameter = parser - .add(new StringParameters("File split regular expression.")) - .addAliases("-s", "--split-pattern").setMandatory(); + StringParameters splitPatternsParameter = parser + .add(new StringParameters("File split regular expression.")) + .addAliases("-s", "--split-pattern").setMandatory(); - DirectoryParameter workingDirectoryParameter = parser.add( - new DirectoryParameter("Working directory.")).addAliases("-w", - "--working-directory"); + DirectoryParameter workingDirectoryParameter = parser.add( + new DirectoryParameter("Working directory.")).addAliases("-w", + "--working-directory"); - public TextSplittingOptions parseCommandlineArguments(final String[] args) { + public TextSplittingOptions parseCommandlineArguments(final String[] args) { - final TextSplittingOptions options = new TextSplittingOptions(); + final TextSplittingOptions options = new TextSplittingOptions(); - if (!parser.parse(args)) - return null; + if (!parser.parse(args)) + return null; - if (recursiveParameter.isParameterSpecified()) - options.recursive = true; + if (recursiveParameter.isParameterSpecified()) + options.recursive = true; - if (workingDirectoryParameter.isParameterSpecified()) - options.targetDirectory = workingDirectoryParameter.getValue(); - else - options.targetDirectory = new File(System.getProperty("user.dir")); + if (workingDirectoryParameter.isParameterSpecified()) + options.targetDirectory = workingDirectoryParameter.getValue(); + else + options.targetDirectory = new File(System.getProperty("user.dir")); - if (fileInputPatternsParameter.isParameterSpecified()) - options.fileInputPatterns.addAll(fileInputPatternsParameter - .getValue()); + if (fileInputPatternsParameter.isParameterSpecified()) + options.fileInputPatterns.addAll(fileInputPatternsParameter + .getValue()); - if (splitPatternsParameter.isParameterSpecified()) - options.textSplitPatterns.addAll(splitPatternsParameter.getValue()); + if (splitPatternsParameter.isParameterSpecified()) + options.textSplitPatterns.addAll(splitPatternsParameter.getValue()); - return options; - } + return options; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/textsplitter/Main.java b/src/main/java/eu/svjatoslav/meviz/textsplitter/Main.java index 5d8082e..5b0e3c9 100755 --- a/src/main/java/eu/svjatoslav/meviz/textsplitter/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/textsplitter/Main.java @@ -9,132 +9,127 @@ package eu.svjatoslav.meviz.textsplitter; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - import eu.svjatoslav.commons.file.FilePathParser; import eu.svjatoslav.commons.string.String2; import eu.svjatoslav.commons.string.WildCardMatcher; import eu.svjatoslav.meviz.Module; +import java.io.*; + public class Main implements Module { - CommandlineHandler commandlineHandler = new CommandlineHandler(); + CommandlineHandler commandlineHandler = new CommandlineHandler(); - TextSplittingOptions options; + TextSplittingOptions options; - public boolean fileMatchesInputPattern(final File file) { - final String fileName = file.getName().toLowerCase(); + public boolean fileMatchesInputPattern(final File file) { + final String fileName = file.getName().toLowerCase(); - for (final String inputPattern : options.fileInputPatterns) - if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) - return true; + for (final String inputPattern : options.fileInputPatterns) + if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) + return true; - return false; - } + return false; + } - @Override - public String getDescription() { - return "Split text with long lines into multiple shorter lines."; - } + @Override + public String getDescription() { + return "Split text with long lines into multiple shorter lines."; + } - @Override - public String getModuleCommand() { - return "splittext"; - } + @Override + public String getModuleCommand() { + return "splittext"; + } - private File getTargetFile(final File sourceFile) { - final StringBuffer targetFilePath = new StringBuffer(); - targetFilePath.append(sourceFile.getParent()); - targetFilePath.append("/"); - targetFilePath.append(FilePathParser - .getFileNameWithoutExtension(sourceFile)); + private File getTargetFile(final File sourceFile) { + final StringBuilder targetFilePath = new StringBuilder(); + targetFilePath.append(sourceFile.getParent()); + targetFilePath.append("/"); + targetFilePath.append(FilePathParser + .getFileNameWithoutExtension(sourceFile)); - targetFilePath.append(".splitted"); + targetFilePath.append(".splitted"); - // add file extension - { - final String fileExtension = FilePathParser - .getFileExtension(sourceFile); + // add file extension + { + final String fileExtension = FilePathParser + .getFileExtension(sourceFile); - if (fileExtension.length() > 0) - targetFilePath.append("." + fileExtension); - } - return new File(targetFilePath.toString()); - } + if (fileExtension.length() > 0) + targetFilePath.append("." + fileExtension); + } + return new File(targetFilePath.toString()); + } - public void processDirectory(final File directory) { + public void processDirectory(final File directory) { - for (final File subFile : directory.listFiles()) - if (subFile.isDirectory()) { - if (options.recursive) - processDirectory(subFile); - } else if (fileMatchesInputPattern(subFile)) - try { - processFile(subFile); - } catch (final IOException exception) { - System.out.println("Error processing file: " - + subFile.getAbsolutePath()); - System.out.println(" exception: " - + exception.getMessage()); - } + for (final File subFile : directory.listFiles()) + if (subFile.isDirectory()) { + if (options.recursive) + processDirectory(subFile); + } else if (fileMatchesInputPattern(subFile)) + try { + processFile(subFile); + } catch (final IOException exception) { + System.out.println("Error processing file: " + + subFile.getAbsolutePath()); + System.out.println(" exception: " + + exception.getMessage()); + } - } + } - public void processFile(final File file) throws IOException { - final File targetFile = getTargetFile(file); + public void processFile(final File file) throws IOException { + final File targetFile = getTargetFile(file); - final BufferedReader bufferedReader = new BufferedReader( - new FileReader(file)); + final BufferedReader bufferedReader = new BufferedReader( + new FileReader(file)); - final BufferedWriter bufferedWriter = new BufferedWriter( - new FileWriter(targetFile)); + final BufferedWriter bufferedWriter = new BufferedWriter( + new FileWriter(targetFile)); - while (true) { - final String readLine = bufferedReader.readLine(); - if (readLine == null) - break; + while (true) { + final String readLine = bufferedReader.readLine(); + if (readLine == null) + break; - final String2 cuttableString = new String2(readLine); + final String2 cuttableString = new String2(readLine); - while (!cuttableString.isEmpty()) { - for (final String pattern : options.textSplitPatterns) - if (WildCardMatcher.match(cuttableString.toString(), - pattern)) - bufferedWriter.write("\n"); + while (!cuttableString.isEmpty()) { + for (final String pattern : options.textSplitPatterns) + if (WildCardMatcher.match(cuttableString.toString(), + pattern)) + bufferedWriter.write("\n"); - final String character = cuttableString.cutLeft(1); - bufferedWriter.append(character); - } + final String character = cuttableString.cutLeft(1); + bufferedWriter.append(character); + } - bufferedWriter.write("\n"); - } + bufferedWriter.write("\n"); + } - bufferedReader.close(); - bufferedWriter.close(); - } + bufferedReader.close(); + bufferedWriter.close(); + } - @Override - public void run(final String[] args) throws IOException { + @Override + public void run(final String[] args) throws IOException { - options = commandlineHandler.parseCommandlineArguments(args); + options = commandlineHandler.parseCommandlineArguments(args); - if (options == null) { - showCommandlineHelp(); - return; - } - - processDirectory(options.targetDirectory); + if (options == null) { + showCommandlineHelp(); + return; + } + + processDirectory(options.targetDirectory); - } - - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - } + } + + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/textsplitter/TextSplittingOptions.java b/src/main/java/eu/svjatoslav/meviz/textsplitter/TextSplittingOptions.java index f6353e6..0f0cd42 100755 --- a/src/main/java/eu/svjatoslav/meviz/textsplitter/TextSplittingOptions.java +++ b/src/main/java/eu/svjatoslav/meviz/textsplitter/TextSplittingOptions.java @@ -14,12 +14,12 @@ import java.util.ArrayList; public class TextSplittingOptions { - public ArrayList fileInputPatterns = new ArrayList(); + public ArrayList fileInputPatterns = new ArrayList(); - public ArrayList textSplitPatterns = new ArrayList(); + public ArrayList textSplitPatterns = new ArrayList(); - public boolean recursive = false; + public boolean recursive = false; - public File targetDirectory; + public File targetDirectory; } diff --git a/src/main/java/eu/svjatoslav/meviz/texttruncate/CommandlineHandler.java b/src/main/java/eu/svjatoslav/meviz/texttruncate/CommandlineHandler.java index 303c607..dc294d6 100755 --- a/src/main/java/eu/svjatoslav/meviz/texttruncate/CommandlineHandler.java +++ b/src/main/java/eu/svjatoslav/meviz/texttruncate/CommandlineHandler.java @@ -9,47 +9,47 @@ package eu.svjatoslav.meviz.texttruncate; -import java.io.File; - import eu.svjatoslav.commons.commandline.parameterparser.Parser; import eu.svjatoslav.commons.commandline.parameterparser.parameter.DirectoryParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.NullParameter; import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameters; +import java.io.File; + public class CommandlineHandler { - Parser parser = new Parser(); + Parser parser = new Parser(); - NullParameter recursiveParameter = parser.add( - new NullParameter("Enable recursive mode.")).addAliases("-r", - "--recursive"); + NullParameter recursiveParameter = parser.add( + new NullParameter("Enable recursive mode.")).addAliases("-r", + "--recursive"); - StringParameters inputPatternParameter = parser.add( - new StringParameters("File input pattern.")).addAliases("-i", - "--input-pattern"); + StringParameters inputPatternParameter = parser.add( + new StringParameters("File input pattern.")).addAliases("-i", + "--input-pattern"); - DirectoryParameter workingDirectoryParameter = parser.add( - new DirectoryParameter("Working directory.")).addAliases("-w", - "--working-directory"); + DirectoryParameter workingDirectoryParameter = parser.add( + new DirectoryParameter("Working directory.")).addAliases("-w", + "--working-directory"); - public TextTruncatingOptions parseCommandlineArguments(final String[] args) { + public TextTruncatingOptions parseCommandlineArguments(final String[] args) { - final TextTruncatingOptions options = new TextTruncatingOptions(); + final TextTruncatingOptions options = new TextTruncatingOptions(); - if (!parser.parse(args)) - return null; + if (!parser.parse(args)) + return null; - if (recursiveParameter.isParameterSpecified()) - options.recursive = true; + if (recursiveParameter.isParameterSpecified()) + options.recursive = true; - if (workingDirectoryParameter.isParameterSpecified()) - options.targetDirectory = workingDirectoryParameter.getValue(); - else - options.targetDirectory = new File(System.getProperty("user.dir")); + if (workingDirectoryParameter.isParameterSpecified()) + options.targetDirectory = workingDirectoryParameter.getValue(); + else + options.targetDirectory = new File(System.getProperty("user.dir")); - if (inputPatternParameter.isParameterSpecified()) - options.inputPatterns.addAll(inputPatternParameter.getValue()); + if (inputPatternParameter.isParameterSpecified()) + options.inputPatterns.addAll(inputPatternParameter.getValue()); - return options; - } + return options; + } } diff --git a/src/main/java/eu/svjatoslav/meviz/texttruncate/Main.java b/src/main/java/eu/svjatoslav/meviz/texttruncate/Main.java index a578234..11e1098 100755 --- a/src/main/java/eu/svjatoslav/meviz/texttruncate/Main.java +++ b/src/main/java/eu/svjatoslav/meviz/texttruncate/Main.java @@ -9,147 +9,142 @@ package eu.svjatoslav.meviz.texttruncate; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - import eu.svjatoslav.commons.file.FilePathParser; import eu.svjatoslav.commons.string.String2; import eu.svjatoslav.commons.string.WildCardMatcher; import eu.svjatoslav.meviz.Module; +import java.io.*; + public class Main implements Module { - public static final int targetLineLength = 200; + public static final int targetLineLength = 200; - public static final int maxSplittedLines = 3; + public static final int maxSplittedLines = 3; - public static final String splitLinePrefix = " "; + public static final String splitLinePrefix = " "; - CommandlineHandler commandlineHandler = new CommandlineHandler(); + CommandlineHandler commandlineHandler = new CommandlineHandler(); - TextTruncatingOptions options; + TextTruncatingOptions options; - public boolean fileMatchesInputPattern(final File file) { - final String fileName = file.getName().toLowerCase(); + public boolean fileMatchesInputPattern(final File file) { + final String fileName = file.getName().toLowerCase(); - for (final String inputPattern : options.inputPatterns) - if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) - return true; + for (final String inputPattern : options.inputPatterns) + if (WildCardMatcher.match(fileName, inputPattern.toLowerCase())) + return true; - return false; - } + return false; + } - @Override - public String getDescription() { - return "Truncate text with long lines into multiple shorter lines."; - } + @Override + public String getDescription() { + return "Truncate text with long lines into multiple shorter lines."; + } - @Override - public String getModuleCommand() { - return "trunctext"; - } + @Override + public String getModuleCommand() { + return "trunctext"; + } - private File getTargetFile(final File sourceFile) { - final StringBuffer targetFilePath = new StringBuffer(); - targetFilePath.append(sourceFile.getParent()); - targetFilePath.append("/"); - targetFilePath.append(FilePathParser - .getFileNameWithoutExtension(sourceFile)); + private File getTargetFile(final File sourceFile) { + final StringBuilder targetFilePath = new StringBuilder(); + targetFilePath.append(sourceFile.getParent()); + targetFilePath.append("/"); + targetFilePath.append(FilePathParser + .getFileNameWithoutExtension(sourceFile)); - targetFilePath.append(".truncated"); + targetFilePath.append(".truncated"); - // add file extension - { - final String fileExtension = FilePathParser - .getFileExtension(sourceFile); + // add file extension + { + final String fileExtension = FilePathParser + .getFileExtension(sourceFile); - if (fileExtension.length() > 0) - targetFilePath.append("." + fileExtension); - } - return new File(targetFilePath.toString()); - } + if (fileExtension.length() > 0) + targetFilePath.append("." + fileExtension); + } + return new File(targetFilePath.toString()); + } - public void processDirectory(final File directory) { + public void processDirectory(final File directory) { - for (final File subFile : directory.listFiles()) - if (subFile.isDirectory()) { - if (options.recursive) - processDirectory(subFile); - } else if (fileMatchesInputPattern(subFile)) - try { - processFile(subFile); - } catch (final IOException exception) { - System.out.println("Error processing file: " - + subFile.getAbsolutePath()); - System.out.println(" exception: " - + exception.getMessage()); - } + for (final File subFile : directory.listFiles()) + if (subFile.isDirectory()) { + if (options.recursive) + processDirectory(subFile); + } else if (fileMatchesInputPattern(subFile)) + try { + processFile(subFile); + } catch (final IOException exception) { + System.out.println("Error processing file: " + + subFile.getAbsolutePath()); + System.out.println(" exception: " + + exception.getMessage()); + } - } + } - public void processFile(final File file) throws IOException { - final File targetFile = getTargetFile(file); + public void processFile(final File file) throws IOException { + final File targetFile = getTargetFile(file); - final BufferedReader bufferedReader = new BufferedReader( - new FileReader(file)); + final BufferedReader bufferedReader = new BufferedReader( + new FileReader(file)); - final BufferedWriter bufferedWriter = new BufferedWriter( - new FileWriter(targetFile)); + final BufferedWriter bufferedWriter = new BufferedWriter( + new FileWriter(targetFile)); - while (true) { - final String readLine = bufferedReader.readLine(); - if (readLine == null) - break; + while (true) { + final String readLine = bufferedReader.readLine(); + if (readLine == null) + break; - if (readLine.length() <= targetLineLength) - bufferedWriter.write(readLine + "\n"); - else { + if (readLine.length() <= targetLineLength) + bufferedWriter.write(readLine + "\n"); + else { - final String2 cuttableString = new String2(readLine); + final String2 cuttableString = new String2(readLine); - bufferedWriter.write(cuttableString.cutLeft(targetLineLength) - + "\n"); + bufferedWriter.write(cuttableString.cutLeft(targetLineLength) + + "\n"); - int splittedLinesCount = 0; + int splittedLinesCount = 0; - while (!cuttableString.isEmpty()) { - splittedLinesCount++; - if (splittedLinesCount >= maxSplittedLines) - break; + while (!cuttableString.isEmpty()) { + splittedLinesCount++; + if (splittedLinesCount >= maxSplittedLines) + break; - bufferedWriter.write(splitLinePrefix - + cuttableString.cutLeft(targetLineLength - - splitLinePrefix.length()) + "\n"); - } - } + bufferedWriter.write(splitLinePrefix + + cuttableString.cutLeft(targetLineLength + - splitLinePrefix.length()) + "\n"); + } + } - } + } - bufferedReader.close(); - bufferedWriter.close(); - } + bufferedReader.close(); + bufferedWriter.close(); + } - @Override - public void run(final String[] args) throws IOException { + @Override + public void run(final String[] args) throws IOException { - options = commandlineHandler.parseCommandlineArguments(args); + options = commandlineHandler.parseCommandlineArguments(args); - if (options == null) { - showCommandlineHelp(); - return; - } + if (options == null) { + showCommandlineHelp(); + return; + } - processDirectory(options.targetDirectory); + processDirectory(options.targetDirectory); - } + } - @Override - public void showCommandlineHelp() { - commandlineHandler.parser.showHelp(); - } + @Override + public void showCommandlineHelp() { + commandlineHandler.parser.showHelp(); + } } diff --git a/src/main/java/eu/svjatoslav/meviz/texttruncate/TextTruncatingOptions.java b/src/main/java/eu/svjatoslav/meviz/texttruncate/TextTruncatingOptions.java index 25d1ab5..229443c 100755 --- a/src/main/java/eu/svjatoslav/meviz/texttruncate/TextTruncatingOptions.java +++ b/src/main/java/eu/svjatoslav/meviz/texttruncate/TextTruncatingOptions.java @@ -14,10 +14,10 @@ import java.util.ArrayList; public class TextTruncatingOptions { - public ArrayList inputPatterns = new ArrayList(); + public ArrayList inputPatterns = new ArrayList(); - public boolean recursive = false; + public boolean recursive = false; - public File targetDirectory; + public File targetDirectory; } diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml index a9b5a88..62431c1 100644 --- a/src/main/resources/log4j.xml +++ b/src/main/resources/log4j.xml @@ -1,16 +1,16 @@ - - - + + + - - - - - - - + + + + + + + \ No newline at end of file