List of usage examples for java.lang String endsWith
public boolean endsWith(String suffix)
From source file:JpegImagesToMovie.java
public static void main(String args[]) { if (args.length == 0) prUsage();/*from www . j av a 2 s . c om*/ // Parse the arguments. int i = 0; int width = -1, height = -1, frameRate = 1; Vector inputFiles = new Vector(); String outputURL = null; while (i < args.length) { if (args[i].equals("-w")) { i++; if (i >= args.length) prUsage(); width = new Integer(args[i]).intValue(); } else if (args[i].equals("-h")) { i++; if (i >= args.length) prUsage(); height = new Integer(args[i]).intValue(); } else if (args[i].equals("-f")) { i++; if (i >= args.length) prUsage(); frameRate = new Integer(args[i]).intValue(); } else if (args[i].equals("-o")) { i++; if (i >= args.length) prUsage(); outputURL = args[i]; } else { for (int j = 0; j < 120; j++) { inputFiles.addElement(args[i]); } } i++; } if (outputURL == null || inputFiles.size() == 0) prUsage(); // Check for output file extension. if (!outputURL.endsWith(".mov") && !outputURL.endsWith(".MOV")) { System.err.println("The output file extension should end with a .mov extension"); prUsage(); } if (width < 0 || height < 0) { System.err.println("Please specify the correct image size."); prUsage(); } // Check the frame rate. if (frameRate < 1) frameRate = 1; // Generate the output media locators. MediaLocator oml; if ((oml = createMediaLocator(outputURL)) == null) { System.err.println("Cannot build media locator from: " + outputURL); System.exit(0); } JpegImagesToMovie imageToMovie = new JpegImagesToMovie(); imageToMovie.doIt(width, height, frameRate, inputFiles, oml); System.exit(0); }
From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java
public static void main(String[] args) throws FileNotFoundException, IOException { for (String s : args) { System.out.println(s);//ww w .j a v a2 s .c o m } String inputFile = "D:\\datasets\\kissmetrics\\input\\2250.json"; String outputFile = "D:\\datasets\\kissmetrics\\output\\2250.json"; // String inputFile ="D:\\datasets\\kissmetrics\\input\\"; //String inputFile = "D:\\datasets\\kissmetrics\\input5\\"; //String outputFile = "D:\\datasets\\kissmetrics\\output5\\"; if (args.length == 2) { try { inputFile = args[0]; outputFile = args[1]; } catch (Exception e) { System.err.println( "Error unable to extract arguments, valid arguments are inputFilePath inputFilePath"); System.exit(1); } } else if (args == null || args.length == 0) { logger.info("using defaul values for inputFile=" + inputFile + " outputFile=" + outputFile); } String logConfigPath = Paths.get(System.getProperty("user.dir"), "log4j.properties").toString(); File f = new File(logConfigPath); if (f.exists() && !f.isDirectory()) { System.out.println("log config file used: " + logConfigPath); PropertyConfigurator.configure(logConfigPath); logger.info("log config file used: " + logConfigPath); } else { System.out.println( "no log file detected, please copy the log4j.properties to the same folder as the JAR"); } if (inputFile.endsWith("\\")) { logger.info("Detected folder"); processFolder(inputFile, outputFile); } else { logger.info("Detected file"); runonfileValidJson(inputFile, outputFile); } }
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments *//*from w w w . ja va 2s .co m*/ public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.sun.faban.harness.util.CLI.java
/** * The first argument to the CLI is the action. It can be:<ul> * <li>pending</li>/*w w w .j a va2 s.c om*/ * <li>status runId</li> * <li>submit benchmark profile configfile.xml</ul> * </ul> * * @param args The command line arguments. */ public static void main(String[] args) { if (args.length == 0) { printUsage(); System.exit(1); } ArrayList<String> argList = new ArrayList<String>(); // Do the getopt thing. char opt = (char) -1; String master = null; String user = null; String password = null; for (String arg : args) { if (arg.startsWith("-M")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'M'; continue; } master = optArg; } else if (arg.startsWith("-U")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'U'; continue; } user = optArg; } else if (arg.startsWith("-P")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'P'; continue; } password = optArg; } else if (opt != (char) -1) { switch (opt) { case 'M': master = arg; opt = (char) -1; break; case 'U': user = arg; opt = (char) -1; break; case 'P': password = arg; opt = (char) -1; break; } } else { argList.add(arg); opt = (char) -1; } } if (master == null) master = "http://localhost:9980/"; else if (!master.endsWith("/")) master += '/'; CLI cli = new CLI(); String action = argList.get(0); try { if ("pending".equals(action)) { cli.doGet(master + "pending"); } else if ("status".equals(action)) { if (argList.size() > 1) cli.doGet(master + "status/" + argList.get(1)); else printUsage(); } else if ("submit".equals(action)) { if (argList.size() > 3) { cli.doPostSubmit(master, user, password, argList); } else { printUsage(); System.exit(1); } } else if ("kill".equals(action)) { if (argList.size() > 1) { cli.doPostKill(master, user, password, argList); } else { printUsage(); System.exit(1); } } else if ("wait".equals(action)) { if (argList.size() > 1) { cli.pollStatus(master + "status/" + argList.get(1)); } else { printUsage(); System.exit(1); } } else if ("showlogs".equals(action)) { StringBuilder url = new StringBuilder(); if (argList.size() > 1) { url.append(master).append("logs/"); url.append(argList.get(1)); } else { printUsage(); } for (int i = 2; i < argList.size(); i++) { if ("-t".equals(argList.get(i))) url.append("/tail"); if ("-f".equals(argList.get(i))) url.append("/follow"); if ("-ft".equals(argList.get(i))) url.append("/tail/follow"); if ("-tf".equals(argList.get(i))) url.append("/tail/follow"); } cli.doGet(url.toString()); } else { printUsage(); } } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
From source file:Jpeg.java
public static void main(String args[]) { Image image = null;//from www. j a v a 2 s . co m FileOutputStream dataOut = null; File file, outFile; JpegEncoder jpg; String string = ""; int i, Quality = 80; // Check to see if the input file name has one of the extensions: // .tif, .gif, .jpg // If not, print the standard use info. if (args.length < 2) StandardUsage(); if (!args[0].endsWith(".jpg") && !args[0].endsWith(".tif") && !args[0].endsWith(".gif")) StandardUsage(); // First check to see if there is an OutputFile argument. If there isn't // then name the file "InputFile".jpg // Second check to see if the .jpg extension is on the OutputFile argument. // If there isn't one, add it. // Need to check for the existence of the output file. If it exists already, // rename the file with a # after the file name, then the .jpg extension. if (args.length < 3) { string = args[0].substring(0, args[0].lastIndexOf(".")) + ".jpg"; } else { string = args[2]; if (string.endsWith(".tif") || string.endsWith(".gif")) string = string.substring(0, string.lastIndexOf(".")); if (!string.endsWith(".jpg")) string = string.concat(".jpg"); } outFile = new File(string); i = 1; while (outFile.exists()) { outFile = new File(string.substring(0, string.lastIndexOf(".")) + (i++) + ".jpg"); if (i > 100) System.exit(0); } file = new File(args[0]); if (file.exists()) { try { dataOut = new FileOutputStream(outFile); } catch (IOException e) { } try { Quality = Integer.parseInt(args[1]); } catch (NumberFormatException e) { StandardUsage(); } image = Toolkit.getDefaultToolkit().getImage(args[0]); jpg = new JpegEncoder(image, Quality, dataOut); jpg.Compress(); try { dataOut.close(); } catch (IOException e) { } } else { System.out.println("I couldn't find " + args[0] + ". Is it in another directory?"); } System.exit(0); }
From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java
public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Option fileOpt = OptionBuilder.withArgName("file").hasArg().withLongOpt("file") .withDescription("Path to a single file").create('f'); Option dirOpt = OptionBuilder.withArgName("directory").hasArg().withLongOpt("dir") .withDescription("A directory with image files in it").create('d'); Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h'); Option pathFileOpt = OptionBuilder.withArgName("path file").hasArg().withLongOpt("pathfile") .withDescription(/*from ww w. j a va 2 s . c o m*/ "A file containing full absolute paths to videos. Previous default was memex-index_temp.txt") .create('p'); Option outputFileOpt = OptionBuilder.withArgName("output file").withLongOpt("outputfile").hasArg() .withDescription("File containing similarity results. Defaults to ./similarity.txt").create('o'); Option jsonOutputFlag = OptionBuilder.withArgName("json output").withLongOpt("json") .withDescription("Set similarity output format to JSON. Defaults to .txt").create('j'); Option similarityFromFeatureVectorsOpt = OptionBuilder .withArgName("similarity from FeatureVectors directory") .withLongOpt("similarityFromFeatureVectorsDirectory").hasArg() .withDescription("calculate similarity matrix from given directory of feature vectors").create('s'); Options options = new Options(); options.addOption(dirOpt); options.addOption(pathFileOpt); options.addOption(fileOpt); options.addOption(helpOpt); options.addOption(outputFileOpt); options.addOption(jsonOutputFlag); options.addOption(similarityFromFeatureVectorsOpt); // create the parser CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String directoryPath = null; String pathFile = null; String singleFilePath = null; String similarityFromFeatureVectorsDirectory = null; ArrayList<Path> videoFiles = null; if (line.hasOption("dir")) { directoryPath = line.getOptionValue("dir"); } if (line.hasOption("pathfile")) { pathFile = line.getOptionValue("pathfile"); } if (line.hasOption("file")) { singleFilePath = line.getOptionValue("file"); } if (line.hasOption("outputfile")) { outputFile = line.getOptionValue("outputfile"); } if (line.hasOption("json")) { outputFormat = OUTPUT_FORMATS.JSON; } if (line.hasOption("similarityFromFeatureVectorsDirectory")) { similarityFromFeatureVectorsDirectory = line .getOptionValue("similarityFromFeatureVectorsDirectory"); } if (line.hasOption("help") || (line.getOptions() == null || (line.getOptions() != null && line.getOptions().length == 0)) || (directoryPath != null && pathFile != null && !directoryPath.equals("") && !pathFile.equals(""))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pooled_time_series", options); System.exit(1); } if (directoryPath != null) { File dir = new File(directoryPath); List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); videoFiles = new ArrayList<Path>(files.size()); for (File file : files) { String filePath = file.toString(); // When given a directory to load videos from we need to ensure that we // don't try to load the of.txt and hog.txt intermediate result files // that results from previous processing runs. if (!filePath.contains(".txt")) { videoFiles.add(file.toPath()); } } LOG.info("Added " + videoFiles.size() + " video files from " + directoryPath); } if (pathFile != null) { Path list_file = Paths.get(pathFile); videoFiles = loadFiles(list_file); LOG.info("Loaded " + videoFiles.size() + " video files from " + pathFile); } if (singleFilePath != null) { Path singleFile = Paths.get(singleFilePath); LOG.info("Loaded file: " + singleFile); videoFiles = new ArrayList<Path>(1); videoFiles.add(singleFile); } if (similarityFromFeatureVectorsDirectory != null) { File dir = new File(similarityFromFeatureVectorsDirectory); List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); videoFiles = new ArrayList<Path>(files.size()); for (File file : files) { String filePath = file.toString(); // We need to load only the *.of.txt and *.hog.txt values if (filePath.endsWith(".of.txt")) { videoFiles.add(file.toPath()); } if (filePath.endsWith(".hog.txt")) { videoFiles.add(file.toPath()); } } LOG.info("Added " + videoFiles.size() + " feature vectors from " + similarityFromFeatureVectorsDirectory); evaluateSimilarity(videoFiles, 1); } else { evaluateSimilarity(videoFiles, 1); } LOG.info("done."); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } }
From source file:net.sf.firemox.xml.magic.Oracle2Xml.java
/** * <ul>/* w w w .j a v a 2 s. c om*/ * Argument are (in this order : * <li>Oracle source file * <li>destination directory * </ul> * * @param args */ public static void main(String... args) { options = new Options(); final CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { // Display help if (!options.isHelp()) { System.out.println("Wrong parameters : " + e.getMessage()); } else { System.out.println("Usage"); } parser.setUsageWidth(100); parser.printUsage(System.out); System.exit(-1); return; } if (options.isVersion()) { // Display version System.out.println("Version is " + IdConst.VERSION); System.exit(-1); return; } if (options.isHelp()) { // Display help System.out.println("Usage"); parser.setUsageWidth(100); parser.printUsage(System.out); System.exit(-1); return; } // The oracle source file final String oracle = options.getOracleFile(); // the directory destination end with the file separator String destination = FilenameUtils.separatorsToWindows(options.getDestination()); if (!destination.endsWith("/")) { destination += "/"; } // Create the destination directories try { new File(destination).mkdirs(); } catch (Exception e) { // Ignore this error and continue } new Oracle2Xml().serialize(MToolKit.getFile(oracle), MToolKit.getFile(destination), MToolKit.getFile("tbs/" + TBS_NAME + "/recycled/")); }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public static void main(String[] args) throws Exception { RunJasperReports runJasperReports = new RunJasperReports(); // Set up command line parser Options options = new Options(); Option reports = OptionBuilder.withArgName("reportlist").hasArg() .withDescription("Comma separated list of JasperReport XML input files").create("reports"); options.addOption(reports);/* www . j ava2 s .c o m*/ Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg() .withDescription("Email address to send generated reports to").create("emailto"); options.addOption(emailTo); Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg() .withDescription("Sender email address").create("emailfrom"); options.addOption(emailFrom); Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg() .withDescription("Subject line of email").create("emailsubject"); options.addOption(emailSubjectLine); Option emailHostOption = OptionBuilder.withArgName("emailhost").hasArg() .withDescription("Address of email server").create("emailhost"); options.addOption(emailHostOption); Option emailUsernameOption = OptionBuilder.withArgName("emailuser").hasArg() .withDescription("Username if email server requires authentication").create("emailuser"); options.addOption(emailUsernameOption); Option emailPasswordOption = OptionBuilder.withArgName("emailpass").hasArg() .withDescription("Password if email server requires authentication").create("emailpass"); options.addOption(emailPasswordOption); Option outputFolder = OptionBuilder.withArgName("foldername").hasArg() .withDescription( "Folder to write generated reports to, with trailing separator (slash or backslash)") .create("folder"); options.addOption(outputFolder); Option dbTypeOption = OptionBuilder.withArgName("databasetype").hasArg() .withDescription("Currently supported types are: " + Arrays.asList(DatabaseType.values())) .create("dbtype"); options.addOption(dbTypeOption); Option dbNameOption = OptionBuilder.withArgName("databasename").hasArg() .withDescription("Name of the database to run reports against").create("dbname"); options.addOption(dbNameOption); Option dbUserOption = OptionBuilder.withArgName("username").hasArg() .withDescription("Username to connect to databasewith").create("dbuser"); options.addOption(dbUserOption); Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password") .create("dbpass"); options.addOption(dbPassOption); Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg() .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output"); options.addOption(outputTypeOption); Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg() .withDescription("Output filename (excluding filetype suffix)").create("filename"); options.addOption(outputFilenameOption); Option dbHostOption = OptionBuilder.withArgName("host").hasArg().withDescription("Database host address") .create("dbhost"); options.addOption(dbHostOption); Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription( "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85") .create("params"); options.addOption(paramsOption); // Parse command line CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports"); if (reportsDefinitionFileNamesCvs == null) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar RunJasperReports.jar", options); System.out.println(); System.out.println("See www.agilebase.co.uk/opensource for further documentation"); System.out.println(); throw new IllegalArgumentException("No reports specified"); } String outputPath = commandLine.getOptionValue("folder"); List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(",")); List<String> outputFileNames = new ArrayList<String>(); DatabaseType databaseType = DatabaseType.POSTGRESQL; String databaseTypeString = commandLine.getOptionValue("dbtype"); if (databaseTypeString != null) { databaseType = DatabaseType.valueOf(commandLine.getOptionValue("dbtype").toUpperCase()); } String databaseName = commandLine.getOptionValue("dbname"); String databaseUsername = commandLine.getOptionValue("dbuser"); String databasePassword = commandLine.getOptionValue("dbpass"); String databaseHost = commandLine.getOptionValue("dbhost"); if (databaseHost == null) { databaseHost = "localhost"; } OutputType outputType = OutputType.PDF; String outputTypeString = commandLine.getOptionValue("output"); if (outputTypeString != null) { outputType = OutputType.valueOf(outputTypeString.toUpperCase()); } String parametersString = commandLine.getOptionValue("params"); Map parameters = runJasperReports.prepareParameters(parametersString); String outputFilenameSpecified = commandLine.getOptionValue("filename"); if (outputFilenameSpecified == null) { outputFilenameSpecified = ""; } // Iterate over reports, generating output for each for (String reportsDefinitionFileName : reportDefinitionFileNames) { String outputFilename = null; if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) { outputFilename = outputFilenameSpecified; } else { outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", ""); outputFilename = outputFilename.replaceAll("^.*\\/", ""); outputFilename = outputFilename.replaceAll("^.*\\\\", ""); } outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "." + outputType.toString().toLowerCase(); if (outputPath != null) { if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) { outputPath += java.io.File.separator; } outputFilename = outputPath + outputFilename; } System.out.println("Going to generate report " + outputFilename); if (outputType.equals(OutputType.PDF)) { runJasperReports.generatePdfReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } else if (outputType.equals(OutputType.TEXT)) { runJasperReports.generateTextReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } else if (outputType.equals(OutputType.CSV)) { runJasperReports.generateCSVReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } else if (outputType.equals(OutputType.XLS)) { // NB: parameters are in a different order for XLS for some reasons runJasperReports.generateJxlsReport(reportsDefinitionFileName, outputFilename, databaseType, databaseHost, databaseName, databaseUsername, databasePassword, parameters); } else { runJasperReports.generateHtmlReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } outputFileNames.add(outputFilename); } String emailRecipientList = commandLine.getOptionValue("emailto"); if (emailRecipientList != null) { Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(","))); String emailSender = commandLine.getOptionValue("emailfrom"); String emailSubject = commandLine.getOptionValue("emailsubject"); if (emailSubject == null) { emailSubject = "Report attached"; } String emailHost = commandLine.getOptionValue("emailhost"); if (emailHost == null) { emailHost = "localhost"; } String emailUser = commandLine.getOptionValue("emailuser"); String emailPass = commandLine.getOptionValue("emailpass"); System.out.println("Emailing reports to " + emailRecipients); runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender, emailSubject, outputFileNames); } else { System.out.println("Email not generated (no recipients specified)"); } }
From source file:com.moviejukebox.MovieJukebox.java
public static void main(String[] args) throws Throwable { JukeboxStatistics.setTimeStart(System.currentTimeMillis()); // Create the log file name here, so we can change it later (because it's locked System.setProperty("file.name", LOG_FILENAME); PropertyConfigurator.configure("properties/log4j.properties"); LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion()); LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length())); LOG.info("https://github.com/YAMJ/yamj-v2"); LOG.info("Copyright (c) 2004-2016 YAMJ Members"); LOG.info(""); LOG.info("This software is licensed under the GNU General Public License v3+"); LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License"); LOG.info(""); LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : ""); LOG.info(" Commit Date: {}", GIT.getCommitTime()); LOG.info(" Build Date: {}", GIT.getBuildTime()); LOG.info(""); LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion()); LOG.info(""); if (!SystemTools.validateInstallation()) { LOG.info("ABORTING."); return;/* ww w . j a va 2s . c o m*/ } String movieLibraryRoot = null; String jukeboxRoot = null; Map<String, String> cmdLineProps = new LinkedHashMap<>(); try { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-v".equalsIgnoreCase(arg)) { // We've printed the version, so quit now return; } else if ("-t".equalsIgnoreCase(arg)) { String pin = args[++i]; // load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // authorize to Trakt.TV TraktTV.getInstance().initialize().authorizeWithPin(pin); // We've authorized access to Trakt.TV, so quit now return; } else if ("-o".equalsIgnoreCase(arg)) { jukeboxRoot = args[++i]; PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot); } else if ("-c".equalsIgnoreCase(arg)) { jukeboxClean = Boolean.TRUE; PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE); } else if ("-k".equalsIgnoreCase(arg)) { setJukeboxPreserve(Boolean.TRUE); } else if ("-p".equalsIgnoreCase(arg)) { userPropertiesName = args[++i]; } else if ("-i".equalsIgnoreCase(arg)) { skipIndexGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE); } else if ("-h".equalsIgnoreCase(arg)) { skipHtmlGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE); } else if ("-dump".equalsIgnoreCase(arg)) { dumpLibraryStructure = Boolean.TRUE; } else if ("-memory".equalsIgnoreCase(arg)) { showMemory = Boolean.TRUE; PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE); } else if (arg.startsWith("-D")) { String propLine = arg.length() > 2 ? arg.substring(2) : args[++i]; int propDiv = propLine.indexOf('='); if (-1 != propDiv) { cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1)); } } else if (arg.startsWith("-")) { help(); return; } else { movieLibraryRoot = args[i]; } } } catch (Exception error) { LOG.error("Wrong arguments specified"); help(); return; } // Save the name of the properties file for use later setProperty("userPropertiesName", userPropertiesName); LOG.info("Processing started at {}", new Date()); LOG.info(""); // Load the moviejukebox-default.properties file if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) { return; } // Load the user properties file "moviejukebox.properties" // No need to abort if we don't find this file // Must be read before the skin, because this may contain an override skin setPropertiesStreamName(userPropertiesName, Boolean.FALSE); // Grab the skin from the command-line properties if (cmdLineProps.containsKey(SKIN_DIR)) { setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR)); } // Load the skin.properties file if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) { return; } // Load the skin-user.properties file (ignore the error) setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE); // Load the overlay.properties file (ignore the error) String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN); overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE) ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator) : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : ""); setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE); // Load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // This is needed to update the static reference for the API Keys in the pattern formatter // because the formatter is initialised before the properties files are read FilteringLayout.addApiKeys(); // Load the rest of the command-line properties for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) { setProperty(propEntry.getKey(), propEntry.getValue()); } // Read the information about the skin SkinProperties.readSkinVersion(); // Display the information about the skin SkinProperties.printSkinVersion(); StringBuilder properties = new StringBuilder("{"); for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) { properties.append(propEntry.getKey()); properties.append("="); properties.append(propEntry.getValue()); properties.append(","); } properties.replace(properties.length() - 1, properties.length(), "}"); // Print out the properties to the log file. LOG.debug("Properties: {}", properties.toString()); // Check for mjb.skipIndexGeneration and set as necessary // This duplicates the "-i" functionality, but allows you to have it in the property file skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE); if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) { peopleScan = Boolean.TRUE; peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE); peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10); popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5); // Issue 1947: Cast enhancement - option to save all related files to a specific folder peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", ""); if (isNotValidString(peopleFolder)) { peopleFolder = ""; } else if (!peopleFolder.endsWith(File.separator)) { peopleFolder += File.separator; } StringTokenizer st = new StringTokenizer( PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| "); while (st.hasMoreTokens()) { PHOTO_EXTENSIONS.add(st.nextToken()); } } // Check for mjb.skipHtmlGeneration and set as necessary // This duplicates the "-h" functionality, but allows you to have it in the property file skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE); // Look for the parameter in the properties file if it's not been set on the command line // This way we don't overwrite the setting if it's not found and defaults to FALSE showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE); // This duplicates the "-c" functionality, but allows you to have it in the property file jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE); MovieFilenameScanner.setSkipKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE)); MovieFilenameScanner.setSkipRegexKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE)); MovieFilenameScanner.setExtrasKeywords( tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| ")); MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray( getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"), ",;|")); MovieFilenameScanner.setLanguageDetection( PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE)); final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null); if (!languages.isEmpty()) { MovieFilenameScanner.clearLanguages(); for (String lang : languages.getKeywords()) { String values = languages.get(lang); if (values != null) { MovieFilenameScanner.addLanguage(lang, values, values); } else { LOG.info("No values found for language code '{}'", lang); } } } final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords", "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV"); MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords); String temp = getProperty("sorting.strip.prefixes"); if (temp != null) { StringTokenizer st = new StringTokenizer(temp, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("\"") && token.endsWith("\"")) { token = token.substring(1, token.length() - 1); } Movie.addSortIgnorePrefixes(token.toLowerCase()); } } enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE); enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE); enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE); // Check to see if don't have a root, check the property file if (StringTools.isNotValidString(movieLibraryRoot)) { movieLibraryRoot = getProperty("mjb.libraryRoot"); if (StringTools.isValidString(movieLibraryRoot)) { LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot); } else { LOG.error("No library root found!"); help(); return; } } if (jukeboxRoot == null) { jukeboxRoot = getProperty("mjb.jukeboxRoot"); if (jukeboxRoot == null) { LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors."); } else { LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot); } } File f = new File(movieLibraryRoot); if (f.exists() && f.isDirectory() && jukeboxRoot == null) { jukeboxRoot = movieLibraryRoot; } if (movieLibraryRoot == null) { help(); return; } if (jukeboxRoot == null) { LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !"); help(); return; } if (!f.exists()) { LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot); return; } FileTools.initUnsafeChars(); FileTools.initSubtitleExtensions(); // make canonical names jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot); movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot); MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot); if (dumpLibraryStructure) { LOG.warn( "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated"); ml.makeDumpStructure(); } else { ml.generateLibrary(); } // Now rename the log files renameLogFile(); if (ScanningLimit.isLimitReached()) { LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.", ScanningLimit.getLimit()); System.exit(EXIT_SCAN_LIMIT); } else { System.exit(EXIT_NORMAL); } }
From source file:ca.uqac.info.Job.Launcher.JobLauncher.java
public static void main(final String[] args) { // Parse command line arguments Options options = setupOptions();/*w w w.jav a 2 s . c o m*/ CommandLine c_line = setupCommandLine(args, options); String batFolder = ""; String outFolderStr = ""; File folderBat = null; File[] listOfFiles = null; String files = ""; String username = ""; String password = ""; String recipient = ""; String message = ""; boolean emailOpt = false; GoogleMail Gmail = null; if (c_line.hasOption("e")) { emailOpt = Boolean.parseBoolean(c_line.getOptionValue("email")); } if (emailOpt == true) { Gmail = new GoogleMail(); } // boolean nextJob = true; if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } //Contains a bat folder if (c_line.hasOption("b")) { batFolder = c_line.getOptionValue("BatFolder"); } else { System.err.println("No Bat Folder in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains a Output folder if (c_line.hasOption("o")) { outFolderStr = c_line.getOptionValue("OutputFolder"); } else { System.err.println("No Output Folder in Arguments"); System.exit(ERR_ARGUMENTS); } //Use the email option if (emailOpt == true) { //Contains the username if (c_line.hasOption("username")) { username = c_line.getOptionValue("u"); } else { System.err.println("No username in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains the password if (c_line.hasOption("password")) { password = c_line.getOptionValue("p"); } else { System.err.println("No password in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains the recipient Email if (c_line.hasOption("recipientEmail")) { recipient = c_line.getOptionValue("r"); } else { System.err.println("No recipient Email in Arguments"); System.exit(ERR_ARGUMENTS); } } folderBat = new File(batFolder); listOfFiles = folderBat.listFiles(); File outFolder = new File(outFolderStr); //Make sure to test all of the files for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName(); String outName = outFolderStr + "\\Results_" + files + ".txt"; message = outName; //Make sure to use only the bat files if (files.endsWith(".bat") || files.endsWith(".Bat")) { try { String StartDay = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date()); long timeBefore = new Date().getTime(); int exitStatus = launchJob(listOfFiles[i].getAbsolutePath(), outName, outFolder); long timeAfter = new Date().getTime(); String EndDay = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date()); long timeLaunch = timeAfter - timeBefore; if (exitStatus != 0)// An error arrived in the job launch { message += " exitStatus : " + exitStatus; message += " \n Total : " + timeLaunch + " ms"; message += " \n Start : " + StartDay; message += "\n End : " + EndDay; //Send the email to tell the launch job status sendEmail(Gmail, emailOpt, username, password, recipient, "Error :" + files, message); } else // Every things is fine { message += " \n Total : " + timeLaunch + " ms"; message += " \n Start : " + StartDay; message += "\n End : " + EndDay; //Send the email to tell the launch job status sendEmail(Gmail, emailOpt, username, password, recipient, files + " Done !!!", message); } } catch (Exception e) { //Send a email for the error from the launch of the job sendEmail(Gmail, emailOpt, username, password, recipient, "Error :" + files, "Launch Job and/or SMTP error !!!"); e.printStackTrace(); } } // if files .bat } // if isFile } // For listOfFiles }