List of usage examples for java.lang String endsWith
public boolean endsWith(String suffix)
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;//from ww w . j av a2 s.com 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:net.ontopia.topicmaps.db2tm.CSVImport.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();/* ww w .ja va 2 s .c o m*/ // Initialize command line option parser and listeners CmdlineOptions options = new CmdlineOptions("CSVImport", argv); OptionsListener ohandler = new OptionsListener(); // Register local options options.addLong(ohandler, "separator", 's', true); options.addLong(ohandler, "stripquotes", 'q'); options.addLong(ohandler, "ignorelines", 'i', true); // Register logging options CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length < 2) { System.err.println("Error: wrong number of arguments."); usage(); System.exit(1); } String dbprops = args[0]; String csvfile = args[1]; String table = (args.length >= 3 ? args[2] : null); if (table == null) { if (csvfile.endsWith(".csv")) table = csvfile.substring(0, csvfile.length() - 4); else table = csvfile; } String[] columns = (args.length >= 4 ? StringUtils.split(args[3], ",") : null); // Load property file Properties props = new Properties(); props.load(new FileInputStream(dbprops)); // Create database connection DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false); Connection conn = cfactory.requestConnection(); CSVImport ci = new CSVImport(conn); ci.setTable(table); ci.setColumns(columns); ci.setSeparator(ohandler.separator); ci.setClearTable(true); ci.setStripQuotes(ohandler.stripquotes); ci.setIgnoreColumns(true); ci.setIgnoreLines(ohandler.ignorelines); ci.importCSV(new FileInputStream(csvfile)); }
From source file:com.glaf.jbpm.action.MultiPooledTaskInstanceAction.java
public static void main(String[] args) throws Exception { String actorIdxy = "{joy,sam},{pp,qq},{kit,cora},{eyb2000,huangcw}"; StringTokenizer st2 = new StringTokenizer(actorIdxy, ";"); while (st2.hasMoreTokens()) { String elem2 = st2.nextToken(); if (StringUtils.isNotEmpty(elem2)) { elem2 = elem2.trim();/*from w w w. j a v a 2s . c om*/ if ((elem2.length() > 0 && elem2.charAt(0) == '{') && elem2.endsWith("}")) { elem2 = elem2.substring(elem2.indexOf("{") + 1, elem2.indexOf("}")); Set<String> actorIds = new HashSet<String>(); StringTokenizer st4 = new StringTokenizer(elem2, ","); while (st4.hasMoreTokens()) { String elem4 = st4.nextToken(); elem4 = elem4.trim(); if (elem4.length() > 0) { actorIds.add(elem4); } } System.out.println(actorIds); } } } }
From source file:FileLister.java
/** * A main() method so FileLister can be run standalone. Parse command line * arguments and create the FileLister object. If an extension is specified, * create a FilenameFilter for it. If no directory is specified, use the * current directory./*w w w. j a va2s . c o m*/ */ public static void main(String args[]) throws IOException { FileLister f; FilenameFilter filter = null; // The filter, if any String directory = null; // The specified dir, or the current dir // Loop through args array, parsing arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-e")) { if (++i >= args.length) usage(); final String suffix = args[i]; // final for anon. class below // This class is a simple FilenameFilter. It defines the // accept() method required to determine whether a specified // file should be listed. A file will be listed if its name // ends with the specified extension, or if it is a directory. filter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith(suffix)) return true; else return (new File(dir, name)).isDirectory(); } }; } else { if (directory != null) usage(); // If already specified, fail. else directory = args[i]; } } // if no directory specified, use the current directory if (directory == null) directory = System.getProperty("user.dir"); // Create the FileLister object, with directory and filter specified. f = new FileLister(directory, filter); // Arrange for the application to exit when the window is closed f.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { System.exit(0); } }); // Finally, pop the window up up. f.show(); }
From source file:kilim.tools.DumpClass.java
public static void main(String[] args) throws IOException { String name = args.length == 2 ? args[1] : args[0]; if (name.endsWith(".jar")) { try {//from w ww .jav a 2 s . c o m Enumeration<JarEntry> e = new JarFile(name).entries(); while (e.hasMoreElements()) { ZipEntry en = (ZipEntry) e.nextElement(); String n = en.getName(); if (!n.endsWith(".class")) continue; n = n.substring(0, n.length() - 6).replace('/', '.'); new DumpClass(n); } } catch (Exception e) { e.printStackTrace(); } } else { new DumpClass(name); } }
From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.Test.java
public static void main(String[] args) throws IOException, ClassNotFoundException { String path = DBpediaOntology.DBPEDIA_CSV_FOLDER; if (args != null && args.length > 0) { path = args[0];// w w w . j a v a 2s. c o m if (!path.endsWith("/")) { path = path + "/"; } } stopAttributes.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); stopAttributes.add("http://www.w3.org/2002/07/owl#sameAs"); stopAttributes.add("http://dbpedia.org/ontology/wikiPageRevisionID"); stopAttributes.add("http://dbpedia.org/ontology/wikiPageID"); stopAttributes.add("http://purl.org/dc/elements/1.1/description"); stopAttributes.add("http://dbpedia.org/ontology/thumbnail"); stopAttributes.add("http://dbpedia.org/ontology/type"); try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path + "counts.bin"))) { categories = (HashSet<String>) ois.readObject(); attributes = (HashSet<String>) ois.readObject(); categoryCount = (HashMap<String, Integer>) ois.readObject(); attributeCount = (HashMap<String, Integer>) ois.readObject(); categoryAttributeCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject(); attributeCategoryCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject(); } System.out.println(categories.size() + " categories found"); System.out.println(attributes.size() + " attributes found"); n = 0; for (Map.Entry<String, Integer> e : categoryCount.entrySet()) { n += e.getValue(); } System.out.println(n); HashMap<String, ArrayList<Pair>> sortedCategoryAttributes = new HashMap<>(); for (String category : categories) { //System.out.println(category); //System.out.println("-----------"); ArrayList<Pair> attributesRank = new ArrayList<Pair>(); Integer c = categoryCount.get(category); if (c == null || c == 0) { continue; } HashMap<String, Integer> thisCategoryAttributeCount = categoryAttributeCount.get(category); for (Map.Entry<String, Integer> e : thisCategoryAttributeCount.entrySet()) { attributesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / c)); } Collections.sort(attributesRank); for (Pair p : attributesRank) { //System.out.println("A:" + p.getS() + "\t" + p.getP()); } //System.out.println("==============================="); sortedCategoryAttributes.put(category, attributesRank); } for (String attribute : attributes) { //System.out.println(attribute); //System.out.println("-----------"); ArrayList<Pair> categoriesRank = new ArrayList<>(); Integer a = attributeCount.get(attribute); if (a == null || a == 0) { continue; } HashMap<String, Integer> thisAttributeCategoryCount = attributeCategoryCount.get(attribute); for (Map.Entry<String, Integer> e : thisAttributeCategoryCount.entrySet()) { categoriesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / a)); } Collections.sort(categoriesRank); for (Pair p : categoriesRank) { //System.out.println("C:" + p.getS() + "\t" + p.getP()); } //System.out.println("==============================="); } HashMap<Integer, Integer> histogram = new HashMap<>(); histogram.put(0, 0); histogram.put(1, 0); histogram.put(2, 0); histogram.put(Integer.MAX_VALUE, 0); int nTest = 0; if (args != null && args.length > 0) { path = args[0]; if (!path.endsWith("/")) { path = path + "/"; } } for (File f : new File(path).listFiles()) { if (f.isFile() && f.getName().endsWith(".csv")) { String category = f.getName().replaceFirst("\\.csv", ""); System.out.println("Category: " + category); ArrayList<HashSet<String>> entities = extractEntities(f, 2); for (HashSet<String> attributesOfThisEntity : entities) { nTest++; ArrayList<String> rankedCategories = rankedCategories(attributesOfThisEntity); boolean found = false; for (int i = 0; i < rankedCategories.size() && !found; i++) { if (rankedCategories.get(i).equals(category)) { Integer count = histogram.get(i); if (count == null) { histogram.put(i, 1); } else { histogram.put(i, count + 1); } found = true; } } if (!found) { histogram.put(Integer.MAX_VALUE, histogram.get(Integer.MAX_VALUE) + 1); } } System.out.println("Tested entities: " + nTest); System.out.println("1: " + histogram.get(0)); System.out.println("2: " + histogram.get(1)); System.out.println("3: " + histogram.get(2)); System.out.println("+3: " + (nTest - histogram.get(2) - histogram.get(1) - histogram.get(0) - histogram.get(Integer.MAX_VALUE))); System.out.println("NF: " + histogram.get(Integer.MAX_VALUE)); } } }
From source file:com.manning.blogapps.chapter10.examples.AuthPut.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authput <username> <password> <filepath> <url>"); System.exit(-1);/*from w w w . jav a2s.com*/ } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; String url = args[3]; HttpClient httpClient = new HttpClient(); EntityEnclosingMethod method = new PutMethod(url); method.setRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); method.setRequestHeader("name", upload.getName()); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; method.setRequestHeader("Content-type", contentType); method.setRequestBody(new FileInputStream(filepath)); httpClient.executeMethod(method); System.out.println(method.getResponseBodyAsString()); }
From source file:esiptestbed.mudrod.main.MudrodEngine.java
/** * Main program invocation. Accepts one argument denoting location (on disk) * to a log file which is to be ingested. Help will be provided if invoked * with incorrect parameters.//www . java 2 s . c o m * * @param args * {@link java.lang.String} array contaning correct parameters. */ public static void main(String[] args) { // boolean options Option helpOpt = new Option("h", "help", false, "show this help message"); // preprocessing + processing Option fullIngestOpt = new Option("f", FULL_INGEST, false, "begin full ingest Mudrod workflow"); // processing only, assuming that preprocessing results is in logDir Option processingOpt = new Option("p", PROCESSING, false, "begin processing with preprocessing results"); // import raw web log into Elasticsearch Option logIngestOpt = new Option("l", LOG_INGEST, false, "begin log ingest without any processing only"); // preprocessing web log, assuming web log has already been imported Option sessionReconOpt = new Option("s", SESSION_RECON, false, "begin session reconstruction"); // calculate vocab similarity from session reconstrution results Option vocabSimFromOpt = new Option("v", VOCAB_SIM_FROM_LOG, false, "begin similarity calulation from web log Mudrod workflow"); // add metadata and ontology preprocessing and processing results into web // log vocab similarity Option addMetaOntoOpt = new Option("a", ADD_META_ONTO, false, "begin adding metadata and ontology results"); // argument options Option logDirOpt = Option.builder(LOG_DIR).required(true).numberOfArgs(1).hasArg(true) .desc("the log directory to be processed by Mudrod").argName(LOG_DIR).build(); // create the options Options options = new Options(); options.addOption(helpOpt); options.addOption(logIngestOpt); options.addOption(fullIngestOpt); options.addOption(processingOpt); options.addOption(sessionReconOpt); options.addOption(vocabSimFromOpt); options.addOption(addMetaOntoOpt); options.addOption(logDirOpt); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); String processingType = null; if (line.hasOption(LOG_INGEST)) { processingType = LOG_INGEST; } else if (line.hasOption(FULL_INGEST)) { processingType = FULL_INGEST; } else if (line.hasOption(PROCESSING)) { processingType = PROCESSING; } else if (line.hasOption(SESSION_RECON)) { processingType = SESSION_RECON; } else if (line.hasOption(VOCAB_SIM_FROM_LOG)) { processingType = VOCAB_SIM_FROM_LOG; } else if (line.hasOption(ADD_META_ONTO)) { processingType = ADD_META_ONTO; } String dataDir = line.getOptionValue(LOG_DIR).replace("\\", "/"); if (!dataDir.endsWith("/")) { dataDir += "/"; } MudrodEngine me = new MudrodEngine(); me.loadConfig(); me.props.put(LOG_DIR, dataDir); me.es = new ESDriver(me.getConfig()); me.spark = new SparkDriver(); loadFullConfig(me, dataDir); if (processingType != null) { switch (processingType) { case LOG_INGEST: me.logIngest(); break; case PROCESSING: me.startProcessing(); break; case SESSION_RECON: me.sessionRestruction(); break; case VOCAB_SIM_FROM_LOG: me.vocabSimFromLog(); break; case ADD_META_ONTO: me.addMetaAndOntologySim(); break; case FULL_INGEST: me.startFullIngest(); break; default: break; } } me.end(); } catch (Exception e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "MudrodEngine: 'logDir' argument is mandatory. " + "User must also provide an ingest method.", options, true); LOG.error("Error inputting command line!", e); return; } }
From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authpost <username> <password> <filepath> <url>"); System.exit(-1);/*from ww w.j a va 2 s . co m*/ } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; URL url = new URL(args[3]); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); conn.setRequestProperty("name", upload.getName()); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; conn.setRequestProperty("Content-type", contentType); BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload)); BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = filein.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } filein.close(); out.close(); String s = null; BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((s = in.readLine()) != null) { System.out.println(s); } }
From source file:com.manning.blogapps.chapter10.examples.AuthPost.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authpost <username> <password> <filepath> <url>"); System.exit(-1);//from w ww.j a v a2s . co m } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; String url = args[3]; HttpClient httpClient = new HttpClient(); EntityEnclosingMethod method = new PostMethod(url); method.setRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); method.setRequestHeader("Title", upload.getName()); method.setRequestBody(new FileInputStream(upload)); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; method.setRequestHeader("Content-type", contentType); httpClient.executeMethod(method); System.out.println(method.getResponseBodyAsString()); }