List of usage examples for java.nio.file Path toFile
default File toFile()
From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java
public static void main(String[] args) throws InterruptedException { // create Options object Options options = new Options(); // add conf file option options.addOption("c", true, "config file"); CommandLineParser parser = new BasicParser(); CommandLine cmd;//from www . j a v a 2 s . co m try { cmd = parser.parse(options, args); String configFile = cmd.getOptionValue("c"); if (configFile == null) { Log.e(TAG, "The config file option was not provided"); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("d", options); System.exit(-1); } else { try { HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile); Path libdir = Paths.get(hubConfig.getLibdir()); if (hubConfig.isDebugMode()) { File dir = libdir.toFile(); if (dir.exists() && dir.isDirectory()) for (File file : dir.listFiles()) file.delete(); } final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost()); init(hubConfig); try { server.start(); } catch (IOException ioe) { Log.e(TAG, "Couldn't start server:\n" + ioe); System.exit(-1); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.stop(); Log.i(TAG, "Server stopped"); } }); while (true) { Thread.sleep(1000); } } catch (ConfigurationParsingException | IOException e) { System.out.println("1:" + e.getMessage()); Log.e(TAG, e.getMessage()); System.exit(-1); } } } catch (ParseException e) { System.out.println(e.getMessage()); Log.e(TAG, e.getMessage()); System.exit(-1); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDir = args[0];/*from www.j av a 2 s .com*/ File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // we will process only a subset first List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); for (File file : files) { allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file)); } // collect turkers and csv List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs); String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs); // save CSV and run MACE Path tmpDir = Files.createTempDirectory("mace"); File maceInputFile = new File(tmpDir.toFile(), "input.csv"); FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8"); File outputPredictions = new File(tmpDir.toFile(), "predictions.txt"); File outputCompetence = new File(tmpDir.toFile(), "competence.txt"); // run MACE MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts", "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence", outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() }); // read back the predictions and competence List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8"); // check the output if (predictions.size() != allArgumentPairs.size()) { throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size() + " lines but was " + predictions.size()); } String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8"); String[] competence = competenceRaw.split("\t"); if (competence.length != turkerIDs.size()) { throw new IllegalStateException( "Expected " + turkerIDs.size() + " competence number, got " + competence.length); } // rank turkers by competence Map<String, Double> turkerIDCompetenceMap = new TreeMap<>(); for (int i = 0; i < turkerIDs.size(); i++) { turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i])); } // sort by value descending Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false); System.out.println("Sorted turker competences: " + sortedCompetences); // assign the gold label and competence for (int i = 0; i < allArgumentPairs.size(); i++) { AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i); String goldLabel = predictions.get(i).trim(); // might be empty if (!goldLabel.isEmpty()) { // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only the gold label annotatedArgumentPair.setGoldLabel(goldLabel); } // update turker competence for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) { String turkID = assignment.getTurkID(); int turkRank = getTurkerRank(turkID, sortedCompetences); assignment.setTurkRank(turkRank); double turkCompetence = turkerIDCompetenceMap.get(turkID); assignment.setTurkCompetence(turkCompetence); } } // now sort the data back according to their original file name Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>(); for (AnnotatedArgumentPair argumentPair : allArgumentPairs) { String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(), argumentPair.getArg1().getStance()); if (!fileNameAnnotatedPairsMap.containsKey(fileName)) { fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>()); } fileNameAnnotatedPairsMap.get(fileName).add(argumentPair); } // and save them to the output file for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) { String fileName = entry.getKey(); List<AnnotatedArgumentPair> argumentPairs = entry.getValue(); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); } }
From source file:com.seleniumtests.util.helper.AppTestDocumentation.java
public static void main(String[] args) throws IOException { File srcDir = Paths.get(args[0].replace(File.separator, "/"), "src", "test", "java").toFile(); javadoc = new StringBuilder( "Cette page rfrence l'ensemble des tests et des opration disponible pour l'application\n"); javadoc.append("\n{toc}\n\n"); javadoc.append("${project.summary}\n"); javadoc.append("h1. Tests\n"); try {/* w w w . jav a 2 s . c om*/ Path testsFolders = Files.walk(Paths.get(srcDir.getAbsolutePath())).filter(Files::isDirectory) .filter(p -> p.getFileName().toString().equals("tests")).collect(Collectors.toList()).get(0); exploreTests(testsFolders.toFile()); } catch (IndexOutOfBoundsException e) { throw new ConfigurationException("no 'tests' sub-package found"); } javadoc.append("----"); javadoc.append("h1. Pages\n"); try { Path pagesFolders = Files.walk(Paths.get(srcDir.getAbsolutePath())).filter(Files::isDirectory) .filter(p -> p.getFileName().toString().equals("webpage")).collect(Collectors.toList()).get(0); explorePages(pagesFolders.toFile()); } catch (IndexOutOfBoundsException e) { throw new ConfigurationException("no 'webpage' sub-package found"); } javadoc.append("${project.scmManager}\n"); FileUtils.write(Paths.get(args[0], "src/site/confluence/template.confluence").toFile(), javadoc, Charset.forName("UTF-8")); }
From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java
/** * @param args//from ww w . j a v a 2 s. c o m */ public static void main(String[] args) { // process command-line options Options options = new Options(); options.addOption("n", "noaddr", false, "do not do any address matching (for testing)"); options.addOption("i", "info", false, "create and populate address information table"); options.addOption("h", "help", false, "this message"); // database connection options.addOption("s", "server", true, "database server to connect to"); options.addOption("d", "database", true, "OSM database name"); options.addOption("u", "user", true, "OSM database user name"); options.addOption("p", "pass", true, "OSM database password"); // logging options options.addOption("l", "logdir", true, "log file directory (default './logs')"); options.addOption("e", "loglevel", true, "log level (default 'FINEST')"); // automatically generate the help statement HelpFormatter help_formatter = new HelpFormatter(); // database URI for connection String dburi = null; // Information message for help screen String info_msg = "IzbirkomExtractor [options] <html_directory>"; try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h') || cmd.getArgs().length != 1) { help_formatter.printHelp(info_msg, options); System.exit(1); } /* prohibit n and i together */ if (cmd.hasOption('n') && cmd.hasOption('i')) { System.err.println("Options 'n' and 'i' cannot be used together."); System.exit(1); } /* require database arguments without -n */ if (cmd.hasOption('n') && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) { System.err.println("Options 'n' and does not need any databse parameters."); System.exit(1); } /* require all 4 database options to be used together */ if (!cmd.hasOption('n') && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) { System.err.println( "For database access all of the following arguments have to be specified: server, database, user, pass"); System.exit(1); } /* useful variables */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm"); String dateString = formatter.format(new Date()); /* setup logging */ File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs"); FileUtils.forceMkdir(logdir); File log_file_name = new File( logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log"); FileHandler log_file = new FileHandler(log_file_name.getPath()); /* create "latest" link to currently created log file */ Path latest_log_link = Paths.get(logdir + "/latest"); Files.deleteIfExists(latest_log_link); Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName())); log_file.setFormatter(new SimpleFormatter()); LogManager.getLogManager().reset(); // prevents logging to console logger.addHandler(log_file); logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST); // open directory with HTML files and create file list File dir = new File(cmd.getArgs()[0]); if (!dir.isDirectory()) { System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting"); System.exit(1); } PathMatcher pmatcher = FileSystems.getDefault() .getPathMatcher("glob:? * ?*.html"); ArrayList<File> html_files = new ArrayList<>(); for (Path file : Files.newDirectoryStream(dir.toPath())) if (pmatcher.matches(file.getFileName())) html_files.add(file.toFile()); if (html_files.size() == 0) { System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting"); System.exit(1); } // create csvResultSink FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv"); OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8"); ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#')); // Connect to DB and osmAddressMatcher AddressMatcher osmAddressMatcher; DBSink dbSink = null; DBInfoSink dbInfoSink = null; if (cmd.hasOption('n')) { osmAddressMatcher = new DummyAddressMatcher(); } else { dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d'); Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'), cmd.getOptionValue('p')); osmAddressMatcher = new OsmAddressMatcher(con); dbSink = new DBSink(con); if (cmd.hasOption('i')) dbInfoSink = new DBInfoSink(con); } /* create resultsinks */ SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor(); sm.addResultSink(csvResultSink); if (dbSink != null) { sm.addResultSink(dbSink); if (dbInfoSink != null) sm.addResultSink(dbInfoSink); } // create tableExtractor TableExtractor te = new TableExtractor(osmAddressMatcher, sm); // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters // iterate through files logger.info("Start processing " + html_files.size() + " files in " + dir); for (int i = 0; i < html_files.size(); i++) { System.err.println("Parsing #" + i + ": " + html_files.get(i)); te.processHTMLfile(html_files.get(i)); } System.err.println("Processed " + html_files.size() + " HTML files"); logger.info("Finished processing " + html_files.size() + " files in " + dir); } catch (ParseException e1) { System.err.println("Failed to parse CLI: " + e1.getMessage()); help_formatter.printHelp(info_msg, options); System.exit(1); } catch (IOException e) { System.err.println("I/O Exception: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (SQLException e) { System.err.println("Database '" + dburi + "': " + e.getMessage()); System.exit(1); } catch (ResultSinkException e) { System.err.println("Failed to initialize ResultSink: " + e.getMessage()); System.exit(1); } catch (TableExtractorException e) { System.err.println("Failed to initialize Table Extractor: " + e.getMessage()); System.exit(1); } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) { System.err.println("Something really odd happened: " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:hdfs.MiniHDFS.java
public static void main(String[] args) throws Exception { if (args.length != 1 && args.length != 3) { throw new IllegalArgumentException( "Expected: MiniHDFS <baseDirectory> [<kerberosPrincipal> <kerberosKeytab>], " + "got: " + Arrays.toString(args)); }//from ww w . j ava2 s.com boolean secure = args.length == 3; // configure Paths Path baseDir = Paths.get(args[0]); // hadoop-home/, so logs will not complain if (System.getenv("HADOOP_HOME") == null) { Path hadoopHome = baseDir.resolve("hadoop-home"); Files.createDirectories(hadoopHome); System.setProperty("hadoop.home.dir", hadoopHome.toAbsolutePath().toString()); } // hdfs-data/, where any data is going Path hdfsHome = baseDir.resolve("hdfs-data"); // configure cluster Configuration cfg = new Configuration(); cfg.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsHome.toAbsolutePath().toString()); // lower default permission: TODO: needed? cfg.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY, "766"); // optionally configure security if (secure) { String kerberosPrincipal = args[1]; String keytabFile = args[2]; cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true"); cfg.set(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal); cfg.set(DFSConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal); cfg.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal); cfg.set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, keytabFile); cfg.set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, keytabFile); cfg.set(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, "true"); cfg.set(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, "true"); cfg.set(DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY, "true"); } UserGroupInformation.setConfiguration(cfg); // TODO: remove hardcoded port! MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(cfg); if (secure) { builder.nameNodePort(9998); } else { builder.nameNodePort(9999); } MiniDFSCluster dfs = builder.build(); // Configure contents of the filesystem org.apache.hadoop.fs.Path esUserPath = new org.apache.hadoop.fs.Path("/user/elasticsearch"); try (FileSystem fs = dfs.getFileSystem()) { // Set the elasticsearch user directory up fs.mkdirs(esUserPath); if (UserGroupInformation.isSecurityEnabled()) { List<AclEntry> acls = new ArrayList<>(); acls.add(new AclEntry.Builder().setType(AclEntryType.USER).setName("elasticsearch") .setPermission(FsAction.ALL).build()); fs.modifyAclEntries(esUserPath, acls); } // Install a pre-existing repository into HDFS String directoryName = "readonly-repository"; String archiveName = directoryName + ".tar.gz"; URL readOnlyRepositoryArchiveURL = MiniHDFS.class.getClassLoader().getResource(archiveName); if (readOnlyRepositoryArchiveURL != null) { Path tempDirectory = Files.createTempDirectory(MiniHDFS.class.getName()); File readOnlyRepositoryArchive = tempDirectory.resolve(archiveName).toFile(); FileUtils.copyURLToFile(readOnlyRepositoryArchiveURL, readOnlyRepositoryArchive); FileUtil.unTar(readOnlyRepositoryArchive, tempDirectory.toFile()); fs.copyFromLocalFile(true, true, new org.apache.hadoop.fs.Path( tempDirectory.resolve(directoryName).toAbsolutePath().toUri()), esUserPath.suffix("/existing/" + directoryName)); FileUtils.deleteDirectory(tempDirectory.toFile()); } } // write our PID file Path tmp = Files.createTempFile(baseDir, null, null); String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; Files.write(tmp, pid.getBytes(StandardCharsets.UTF_8)); Files.move(tmp, baseDir.resolve(PID_FILE_NAME), StandardCopyOption.ATOMIC_MOVE); // write our port file tmp = Files.createTempFile(baseDir, null, null); Files.write(tmp, Integer.toString(dfs.getNameNodePort()).getBytes(StandardCharsets.UTF_8)); Files.move(tmp, baseDir.resolve(PORT_FILE_NAME), StandardCopyOption.ATOMIC_MOVE); }
From source file:Pong.java
public static void main(String... args) throws Exception { System.setProperty("os.max.pid.bits", "16"); Options options = new Options(); options.addOption("i", true, "Input chronicle path"); options.addOption("n", true, "Number of entries to write"); options.addOption("w", true, "Number of writer threads"); options.addOption("r", true, "Number of reader threads"); options.addOption("x", false, "Delete the output chronicle at startup"); CommandLine cmd = new DefaultParser().parse(options, args); final Path output = Paths.get(cmd.getOptionValue("o", "/tmp/__test/chr")); final long maxCount = Long.parseLong(cmd.getOptionValue("n", "10000000")); final int writerThreadCount = Integer.parseInt(cmd.getOptionValue("w", "4")); final int readerThreadCount = Integer.parseInt(cmd.getOptionValue("r", "4")); final boolean deleteOnStartup = cmd.hasOption("x"); if (deleteOnStartup) { FileUtil.removeRecursive(output); }/*from ww w. j a v a 2 s.c o m*/ final Chronicle chr = ChronicleQueueBuilder.vanilla(output.toFile()).build(); final ExecutorService executor = Executors.newFixedThreadPool(4); final List<Future<?>> futures = new ArrayList<>(); final long totalCount = writerThreadCount * maxCount; final long t0 = System.nanoTime(); for (int i = 0; i != readerThreadCount; ++i) { final int tid = i; futures.add(executor.submit((Runnable) () -> { try { IntLongMap counts = HashIntLongMaps.newMutableMap(); ExcerptTailer tailer = chr.createTailer(); final StringBuilder sb1 = new StringBuilder(); final StringBuilder sb2 = new StringBuilder(); long count = 0; while (count != totalCount) { if (!tailer.nextIndex()) continue; final int id = tailer.readInt(); final long val = tailer.readStopBit(); final long longValue = tailer.readLong(); sb1.setLength(0); sb2.setLength(0); tailer.read8bitText(sb1); tailer.read8bitText(sb2); if (counts.addValue(id, 1) - 1 != val || longValue != 0x0badcafedeadbeefL || !StringInterner.isEqual("FooBar", sb1) || !StringInterner.isEqual("AnotherFooBar", sb2)) { System.out.println("Unexpected value " + id + ", " + val + ", " + Long.toHexString(longValue) + ", " + sb1.toString() + ", " + sb2.toString()); return; } ++count; if (count % 1_000_000 == 0) { long t1 = System.nanoTime(); System.out.println(tid + " " + (t1 - t0) / 1e6 + " ms"); } } } catch (IOException e) { e.printStackTrace(); } })); } for (Future f : futures) { f.get(); } executor.shutdownNow(); final long t1 = System.nanoTime(); System.out.println("Done. Rough time=" + (t1 - t0) / 1e6 + " ms"); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java
public static void main(String[] args) throws IOException { if (logger == null) { System.out.println("About to initialize Log4j"); logger = LogManager.getLogger(); System.out.println("Finished initializing Log4j"); }/* w w w.j a v a 2 s . co m*/ logger.debug("Entering main()"); // WIP: the following command line code was pulled from FITS Options options = new Options(); Option inputFileOption = new Option(PARAM_I, true, "input file"); options.addOption(inputFileOption); options.addOption(PARAM_V, false, "print version information"); options.addOption(PARAM_H, false, "help information"); options.addOption(PARAM_O, true, "output sub-directory"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args, true); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(1); } // print version info if (cmd.hasOption(PARAM_V)) { if (StringUtils.isEmpty(applicationVersion)) { applicationVersion = "<not set>"; System.exit(1); } System.out.println("Version: " + applicationVersion); System.exit(0); } // print help info if (cmd.hasOption(PARAM_H)) { displayHelp(); System.exit(0); } // input parameter if (cmd.hasOption(PARAM_I)) { String input = cmd.getOptionValue(PARAM_I); boolean hasValue = cmd.hasOption(PARAM_I); logger.debug("Has option {} value: [{}]", PARAM_I, hasValue); String paramVal = cmd.getOptionValue(PARAM_I); logger.debug("value of option: [{}] ****", paramVal); File inputFile = new File(input); if (!inputFile.exists()) { logger.warn("{} does not exist or is not readable.", input); System.exit(1); } String subDir = cmd.getOptionValue(PARAM_O); PdfaConvert convert; if (!StringUtils.isEmpty(subDir)) { convert = new PdfaConvert(subDir); } else { convert = new PdfaConvert(); } if (inputFile.isDirectory()) { if (inputFile.listFiles() == null || inputFile.listFiles().length < 1) { logger.warn("Input directory is empty, nothing to process."); System.exit(1); } else { logger.debug("Have directory: [{}] with file count: {}", inputFile.getAbsolutePath(), inputFile.listFiles().length); DirectoryStream<Path> dirStream = null; dirStream = Files.newDirectoryStream(inputFile.toPath()); for (Path filePath : dirStream) { logger.debug("Have file name: {}", filePath.toString()); // Note: only handling files, not recursively going into sub-directories if (filePath.toFile().isFile()) { // Catch possible exception for each file so can handle other files in directory. try { convert.examine(filePath.toFile()); } catch (Exception e) { logger.error("Problem processing file: {} -- Error message: {}", filePath.getFileName(), e.getMessage()); } } else { logger.warn("Not a file so not processing: {}", filePath.toString()); // could be a directory but not recursing } } dirStream.close(); } } else { logger.debug("About to process file: {}", inputFile.getPath()); try { convert.examine(inputFile); } catch (Exception e) { logger.error("Problem processing file: {} -- Error message: {}", inputFile.getName(), e.getMessage()); logger.debug("Problem processing file: {} -- Error message: {}", inputFile.getName(), e.getMessage(), e); } } } else { System.err.println("Missing required option: " + PARAM_I); displayHelp(); System.exit(-1); } System.exit(0); }
From source file:com.textocat.textokit.postagger.opennlp.PackageModelZipAsArtifact.java
public static void main(String[] args) throws IOException { PackageModelZipAsArtifact cli = new PackageModelZipAsArtifact(); new JCommander(cli, args); Path inputZipPath = Paths.get(cli.inputZipPathStr); if (!Files.isRegularFile(inputZipPath)) { System.err.println(inputZipPath + " is not an existing file."); System.exit(1);//www .j a v a 2s .c om } POSModelJarManifestBean manifestBean = new POSModelJarManifestBean(cli.languageCode, cli.modelVariant); Path outputJarPath = inputZipPath .resolveSibling(FilenameUtils.getBaseName(inputZipPath.getFileName().toString()) + ".jar"); try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(outputJarPath))) { JarOutputStream jout = new JarOutputStream(out, manifestBean.toManifest()); jout.putNextEntry(new ZipEntry(ClasspathPOSModelHolder.getClassPath(manifestBean.getLanguageCode(), manifestBean.getModelVariant()))); FileUtils.copyFile(inputZipPath.toFile(), jout); jout.closeEntry(); jout.close(); } }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br>/* w ww. j a v a2 s .c o m*/ * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (") .append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (") .append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); }
From source file:com.github.houbin217jz.thumbnail.Thumbnail.java
public static void main(String[] args) { Options options = new Options(); options.addOption("s", "src", true, "????????????"); options.addOption("d", "dst", true, ""); options.addOption("r", "ratio", true, "/??, 30%???0.3????????"); options.addOption("w", "width", true, "(px)"); options.addOption("h", "height", true, "?(px)"); options.addOption("R", "recursive", false, "???????"); HelpFormatter formatter = new HelpFormatter(); String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] " + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] "; CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/*www. j av a2 s. c o m*/ try { cmd = parser.parse(options, args); } catch (ParseException e1) { formatter.printHelp(formatstr, options); return; } final Path srcDir, dstDir; final Integer width, height; final Double ratio; // if (cmd.hasOption("s")) { srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath(); } else { srcDir = Paths.get("").toAbsolutePath(); //?? } // if (cmd.hasOption("d")) { dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath(); } else { formatter.printHelp(formatstr, options); return; } if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS) || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) { System.out.println("[" + srcDir.toAbsolutePath() + "]??????"); return; } if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) { if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) { //???????? System.out.println("????????"); return; } } else { //???????? try { Files.createDirectories(dstDir); } catch (IOException e) { e.printStackTrace(); return; } } //?? if (cmd.hasOption("w") && cmd.hasOption("h")) { try { width = Integer.valueOf(cmd.getOptionValue("width")); height = Integer.valueOf(cmd.getOptionValue("height")); } catch (NumberFormatException e) { System.out.println("??????"); return; } } else { width = null; height = null; } //? if (cmd.hasOption("r")) { try { ratio = Double.valueOf(cmd.getOptionValue("r")); } catch (NumberFormatException e) { System.out.println("?????"); return; } } else { ratio = null; } if (width != null && ratio != null) { System.out.println("??????????????"); return; } if (width == null && ratio == null) { System.out.println("????????????"); return; } // int maxDepth = 1; if (cmd.hasOption("R")) { maxDepth = Integer.MAX_VALUE; } try { //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException { //???&??? String filename = path.getFileName().toString().toLowerCase(); if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) { //Jpeg?? /* * relative??: * rootPath: /a/b/c/d * filePath: /a/b/c/d/e/f.jpg * rootPath.relativize(filePath) = e/f.jpg */ /* * resolve?? * rootPath: /a/b/c/output * relativePath: e/f.jpg * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg */ Path dst = dstDir.resolve(srcDir.relativize(path)); if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) { Files.createDirectories(dst.getParent()); } doResize(path.toFile(), dst.toFile(), width, height, ratio); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } }