List of usage examples for java.nio.file Paths get
public static Path get(URI uri)
From source file:com.chigix.autosftp.Application.java
public static void main(String[] args) { Options options = new Options(); options.addOption(Option.builder("P").longOpt("port").hasArg().build()) .addOption(Option.builder("h").longOpt("help").desc("Print this message").build()) .addOption(Option.builder("i").argName("identity_file").hasArg().build()); int port = 22; CommandLine line;//w w w. jav a 2 s .c o m try { line = new DefaultParser().parse(options, args); } catch (UnrecognizedOptionException ex) { System.err.println(ex.getMessage()); return; } catch (ParseException ex) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex); return; } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("autosftp /path/to/watch [user@]host2:[file2]", options, true); return; } String givenPort; if (line.hasOption("port") && StringUtils.isNumeric(givenPort = line.getOptionValue("port"))) { port = Integer.valueOf(givenPort); } if (line.getArgs().length < 0) { System.err.println("Please provide a path to watch."); return; } localPath = Paths.get(line.getArgs()[0]); if (line.getArgs().length < 1) { System.err.println("Please provide remote ssh information."); return; } SshAddressParser addressParse; try { addressParse = new SshAddressParser().parse(line.getArgs()[1]); } catch (SshAddressParser.InvalidAddressException ex) { System.err.println(ex.getMessage()); return; } if (addressParse.getDefaultDirectory() != null) { remotePath = Paths.get(addressParse.getDefaultDirectory()); } try { sshSession = new JSch().getSession(addressParse.getUsername(), addressParse.getHost(), port); } catch (JSchException ex) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex); return; } try { sshOpen(); } catch (JSchException ex) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex); sshClose(); } System.out.println("Remote Default Path: " + remotePath); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { sshClose(); System.out.println("Bye~~~"); } }); try { watchDir(Paths.get(line.getArgs()[0])); } catch (Exception ex) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java
/** * @param args the command line arguments *///from w w w .j a v a 2 s . c om public static void main(String[] args) { // TODO code application logic here try { OaiPmhServer server = new OaiPmhServer("http://vivliothmmy.ee.auth.gr/cgi/oai2"); RecordsList listRecords = server.listRecords("oai_dc");//we capture all the records in oai dc format List<VivlioCrawlerMavenMain> listtotal = new ArrayList<VivlioCrawlerMavenMain>(); //we capture all the names of the professors and former professor of ECE of AUTH from a txt file //change the directory to yours List<String> profs = Files.readAllLines(Paths.get( "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/profs.txt")); boolean more = true;//it is a flag used if we encounter more entries than the initial capture JSONArray array = new JSONArray();//it is going to be our final total json array JSONObject jsonObject = new JSONObject();//it is going to be our final total json object while (more) { for (Record rec : listRecords.asList()) { VivlioCrawlerMavenMain vc = new VivlioCrawlerMavenMain(); Element metadata = rec.getMetadata(); if (metadata != null) { //System.out.println(rec.getMetadataAsString()); List<Element> elements = metadata.elements(); //System.out.println(metadata.getStringValue()); for (Element element : elements) { String name = element.getName(); //we get the title, remove \r, \n and beginning and trailing whitespace if (name.equalsIgnoreCase("title")) { vc.title = element.getStringValue(); vc.title = vc.title.trim(); vc.title = vc.title.replaceAll("(\\r|\\n)", ""); if (!(vc.title.endsWith("."))) { vc.title = vc.title + ".";//we also add dot in the end for the titles to be uniformed } } if (name.equalsIgnoreCase("creator")) { vc.creators.add(element.getStringValue());//we capture the students' names } if (name.equalsIgnoreCase("subject")) { vc.subjects.add(element.getStringValue());//we capture the subjects } if (name.equalsIgnoreCase("description")) { vc.description = element.getStringValue();//we capture the abstract } if (name.equalsIgnoreCase("date")) { vc.datestring = element.getStringValue(); } if (name.equalsIgnoreCase("identifier")) { if (element.getStringValue().contains("http://")) { vc.thesisFiles.add(element.getStringValue());//we capture the url of the thesis whole file if (vc.thesisURL == null) { vc.thesisURL = element.getStringValue().substring(0, 32); } } //if the identifier contains the title then it must be the citation //out of the citation we need to extract the supevisor's name if (element.getStringValue().contains(vc.title.substring(0, 10))) { vc.citation = element.getStringValue(); vc.supervisor = element.getStringValue(); Iterator profsIterator = profs.iterator(); vc.supervisor = vc.supervisor.replace(vc.title, "");//we remove the title out of the citation //if we have two students we remove the first occurence of "" which stands for "and" if (vc.creators.size() == 2) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } //we remove the students' names Iterator creatorsIterator = vc.creators.iterator(); while (creatorsIterator.hasNext()) { vc.supervisor = vc.supervisor.replace(creatorsIterator.next().toString(), ""); } boolean profFlag = false;//flag used that declares that we found the professor that was supervisor while (profsIterator.hasNext() && !profFlag) { String prof = profsIterator.next().toString(); //we split the professor's name to surname and name //because some entries have first the surname and others first the name String[] profSplitted = prof.split("\\s+"); String supervisorCleared = vc.supervisor; supervisorCleared = supervisorCleared.replaceAll("\\s+", "");//we clear the white space supervisorCleared = supervisorCleared.replaceAll("(\\r|\\n)", "");//we remove the \r\n //now we check if the citation includes any name of the professors from the txt if (supervisorCleared.contains(profSplitted[0]) && supervisorCleared.contains(profSplitted[1])) { vc.supervisor = prof; profFlag = true; } } //if we don't find the name of the supervisor, we have to perform string manipulation to extract it if (!profFlag) { vc.supervisor = vc.supervisor.trim(); //we remove the word "" which stands for "Thessaloniki" and "" which stands for Greece if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } //we remove the year and then we should be left only with the supervisor's name vc.supervisor = vc.supervisor.replace("(", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(")", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(",", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(".", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(vc.datestring.substring(0, 4), ""); vc.supervisor = vc.supervisor.trim(); } //we put everything in a json object JSONObject obj = new JSONObject(); obj.put("title", vc.title); obj.put("description", vc.description); JSONArray creatorsArray = new JSONArray(); creatorsArray.add(vc.creators); obj.put("creators", creatorsArray); JSONArray subjectsArray = new JSONArray(); List<String> subjectsList = new ArrayList<String>(vc.subjects); subjectsArray.add(subjectsList); obj.put("subjects", subjectsArray); obj.put("datestring", vc.datestring); JSONArray thesisFilesArray = new JSONArray(); thesisFilesArray.add(vc.thesisFiles); obj.put("thesisFiles", thesisFilesArray); obj.put("thesisURL", vc.thesisURL); obj.put("supervisor", vc.supervisor); obj.put("citation", vc.citation); //if you are using JSON.simple do this array.add(obj); } } } listtotal.add(vc);//a list containing all the objects //it is not used for now, but created for potential extension of the work } } //the following if clause searches for new records if (listRecords.getResumptionToken() != null) { listRecords = server.listRecords(listRecords.getResumptionToken()); } else { more = false; } } //we print which records did not have a supervisor for (VivlioCrawlerMavenMain vctest : listtotal) { if (vctest.supervisor == null) { System.out.println(vctest.title); System.out.println(vctest.citation); } } //we create a pretty json with GSON and we write it into a file jsonObject.put("VivliothmmyOldArray", array); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(jsonObject.toJSONString()).getAsJsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String prettyJson = gson.toJson(json); try { FileWriter file = new FileWriter( "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/VivliothmmyOldRecords.json"); file.write(prettyJson); file.flush(); file.close(); } catch (IOException e) { System.out.println("Exception: " + e); } //System.out.print(prettyJson); //int j=0; } catch (OAIException | IOException e) { System.out.println("Exception: " + e); } }
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception/*from w w w. ja va 2s . c o m*/ */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
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;/*w ww . ja v a 2s . 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(); } }
From source file:org.hbz.oerworldmap.NtToEs.java
public static void main(String... args) throws FileNotFoundException, IOException { if (args.length != 1 && args.length != 2) { System.out.println("Pass the root directory to crawl. " + "Will recursively gather all content from *.nt " + "files with identical names, convert these to " + "compact JSON-LD and index it in ES. " + "If a second argument is passed it is processed " + "as a TSV file that maps file names (w/o " + "extensions) to IDs to be used for ES. Else the " + "file names (w/o extensions) are used."); args = new String[] { "output", "src/main/resources/internalId2uuid.tsv" }; System.out.println("Using defaults: " + Arrays.asList(args)); }//from www. ja v a 2 s .co m if (args.length == 2) initMap(args[1]); TripleCrawler crawler = new TripleCrawler(); Files.walkFileTree(Paths.get(args[0]), crawler); createIndex(config(), INDEX); process(crawler.data); }
From source file:fr.cnrs.sharp.Main.java
public static void main(String args[]) { Options options = new Options(); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option helpOpt = new Option("h", "help", false, "print the help"); Option inProvFileOpt = OptionBuilder.withArgName("input_PROV_file_1> ... <input_PROV_file_n") .withLongOpt("input_PROV_files").withDescription("The list of PROV input files, in RDF Turtle.") .hasArgs().create("i"); Option inRawFileOpt = OptionBuilder.withArgName("input_raw_file_1> ... <input_raw_file_n") .withLongOpt("input_raw_files") .withDescription(/* w ww. java 2 s . c o m*/ "The list of raw files to be fingerprinted and possibly interlinked with owl:sameAs.") .hasArgs().create("ri"); Option summaryOpt = OptionBuilder.withArgName("summary").withLongOpt("summary") .withDescription("Materialization of wasInfluencedBy relations.").create("s"); options.addOption(inProvFileOpt); options.addOption(inRawFileOpt); options.addOption(versionOpt); options.addOption(helpOpt); options.addOption(summaryOpt); String header = "SharpTB is a tool to maturate provenance based on PROV inferences"; String footer = "\nPlease report any issue to alban.gaignard@univ-nantes.fr"; try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpTB", header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { logger.info("SharpTB version 0.1.0"); System.exit(0); } if (cmd.hasOption("ri")) { String[] inFiles = cmd.getOptionValues("ri"); Model model = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { //1. fingerprint try { model.add(Interlinking.fingerprint(p)); } catch (IOException e) { logger.error("Cannot fingerprint file " + inFile); } } } //2. genSameAs Model sameAs = Interlinking.generateSameAs(model); sameAs.write(System.out, "TTL"); } if (cmd.hasOption("i")) { String[] inFiles = cmd.getOptionValues("i"); Model data = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { RDFDataMgr.read(data, inFile, Lang.TTL); } } Model res = Harmonization.harmonizeProv(data); try { Path pathInfProv = Files.createTempFile("PROV-inf-tgd-egd-", ".ttl"); res.write(new FileWriter(pathInfProv.toFile()), "TTL"); System.out.println("Harmonized PROV written to file " + pathInfProv.toString()); //if the summary option is activated, then save the subgraph and generate a visualization if (cmd.hasOption("s")) { String queryInfluence = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" + "PREFIX prov: <http://www.w3.org/ns/prov#> \n" + "CONSTRUCT { \n" + " ?x ?p ?y .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "} WHERE {\n" + " ?x ?p ?y .\n" + " FILTER (?p IN (prov:wasInfluencedBy)) .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "}"; Query query = QueryFactory.create(queryInfluence); QueryExecution queryExec = QueryExecutionFactory.create(query, res); Model summary = queryExec.execConstruct(); queryExec.close(); Util.writeHtmlViz(summary); } } catch (IOException ex) { logger.error("Impossible to write the harmonized provenance file."); System.exit(1); } } else { // logger.info("Please fill the -i input parameter."); // HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("SharpTB", header, options, footer, true); // System.exit(0); } } catch (ParseException ex) { logger.error("Error while parsing command line arguments. Please check the following help:"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpToolBox", header, options, footer, true); System.exit(1); } }
From source file:io.github.azige.whitespace.Cli.java
public static void main(String[] args) { Options options = new Options().addOption("h", "help", false, "??") .addOptionGroup(new OptionGroup() .addOption(new Option("p", "????????")) .addOption(new Option("c", "?????"))) .addOption(null, "szm", false, "????") .addOption("e", "encoding", true, "??" + DEFAULT_ENCODING); try {//from w w w. j a v a 2s. c om CommandLineParser parser = new BasicParser(); CommandLine cl = parser.parse(options, args); if (cl.hasOption('h')) { printHelp(System.out, options); return; } if (cl.hasOption('e')) { encoding = Charset.forName(cl.getOptionValue('e')); } else { encoding = Charset.forName(DEFAULT_ENCODING); } if (cl.hasOption("szm")) { useSzm = true; } String[] fileArgs = cl.getArgs(); if (fileArgs.length != 1) { printHelp(System.err, options); return; } try (InputStream input = Files.newInputStream(Paths.get(fileArgs[0]))) { if (cl.hasOption('p')) { printPseudoCode(input); } else if (cl.hasOption('c')) { compile(input, fileArgs[0]); } else { execute(input, fileArgs[0]); } } } catch (ParseException ex) { ex.printStackTrace(); printHelp(System.err, options); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:api.wiki.WikiGenerator.java
public static void main(String[] args) throws URISyntaxException, IOException, ParseException, NoSuchMethodException, XmlPullParserException { MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader(); Model model = mavenXpp3Reader.read(newBufferedReader(Paths.get("pom.xml"), UTF_8)); WikiGenerator wikiGenerator = new WikiGenerator(model.getGroupId(), model.getArtifactId(), model.getVersion());/*from w w w. j ava2 s. c o m*/ if (wikiGenerator.weAreReleasing()) { wikiGenerator.copyDocsToReleaseDirectory(); } wikiGenerator.generateCurrentDocumentation(); wikiGenerator.generateVersionsIndexPage(); }
From source file:client.tools.ClientRecovery.java
/** * Starts the recovery process at the given client folder. * /* w ww. j av a 2 s . co m*/ * @param args * the path to the configuration file. */ public static void main(String[] args) { Path configPath; if (args.length != 1) { throw new IllegalArgumentException("Path to configuration file must be present!"); } configPath = Paths.get(args[0]); try { ClientConfiguration config = ClientConfiguration.parse(configPath); ClientRecovery recovery = new ClientRecovery(Paths.get(config.getRootPath()), Paths.get(config.getSyncPath())); recovery.execute(); } catch (IOException | ParseException e) { e.printStackTrace(); } }
From source file:com.lagrange.LabelApp.java
/** * Annotates an image using the Vision API. */// w w w . jav a 2 s .c o m public static void main(String[] args) throws IOException, GeneralSecurityException { if (args.length != 1) { System.err.println("Missing imagePath argument."); System.err.println("Usage:"); System.err.printf("\tjava %s imagePath\n", LabelApp.class.getCanonicalName()); System.exit(1); } pathToImage = Paths.get(args[0]); LabelApp app = new LabelApp(getVisionService()); printLabels(System.out, pathToImage, app.labelImage(pathToImage, MAX_LABELS)); }