List of usage examples for java.lang String length
public int length()
From source file:net.ontopia.topicmaps.db2tm.CSVImport.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();//from www . j av a 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.marklogic.client.tutorial.util.Bootstrapper.java
/** * Command-line invocation.//ww w.j av a2s . c o m * @param args command-line arguments specifying the configuration and REST server */ public static void main(String[] args) throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError { Properties properties = new Properties(); for (int i = 0; i < args.length; i++) { String name = args[i]; if (name.startsWith("-") && name.length() > 1 && ++i < args.length) { name = name.substring(1); if ("properties".equals(name)) { InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name); if (propsStream == null) throw new IOException("Could not read bootstrapper properties"); Properties props = new Properties(); props.load(propsStream); props.putAll(properties); properties = props; } else { properties.put(name, args[i]); } } else { System.err.println("invalid argument: " + name); System.err.println(getUsage()); System.exit(1); } } String invalid = joinList(listInvalidKeys(properties)); if (invalid != null && invalid.length() > 0) { System.err.println("invalid arguments: " + invalid); System.err.println(getUsage()); System.exit(1); } new Bootstrapper().makeServer(properties); System.out.println("Created " + properties.getProperty("restserver") + " server on " + properties.getProperty("restport") + " port for " + properties.getProperty("restdb") + " database"); }
From source file:com.projity.pm.graphic.gantt.Main.java
public static void main(String[] args) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", Environment.getStandAlone() ? "OpenProj" : "Project-ON-Demand"); System.setProperty("apple.laf.useScreenMenuBar", "true"); Locale.setDefault(ConfigurationFile.getLocale()); HashMap opts = ApplicationStartupFactory.extractOpts(args); String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("linux")) { String javaExec = ConfigurationFile.getRunProperty("JAVA_EXE"); //check jvm String javaVersion = System.getProperty("java.version"); if (Environment.compareJavaVersion(javaVersion, "1.5") < 0) { String message = Messages.getStringWithParam("Text.badJavaVersion", javaVersion); if (javaExec != null && javaExec.length() > 0) message += "\n" + Messages.getStringWithParam("Text.javaExecutable", new Object[] { javaExec, "JAVA_EXE", "$HOME/.openproj/run.conf" }); if (!opts.containsKey("silentlyFail")) JOptionPane.showMessageDialog(null, message, Messages.getContextString("Title.ProjityError"), JOptionPane.ERROR_MESSAGE); System.exit(64);/* w ww. j av a 2 s . c o m*/ } String javaVendor = System.getProperty("java.vendor"); if (javaVendor == null || !(javaVendor.startsWith("Sun") || javaVendor.startsWith("IBM"))) { String message = Messages.getStringWithParam("Text.badJavaVendor", javaVendor); if (javaExec != null && javaExec.length() > 0) message += "\n" + Messages.getStringWithParam("Text.javaExecutable", new Object[] { javaExec, "JAVA_EXE", "$HOME/.openproj/run.conf" }); if (!opts.containsKey("silentlyFail")) JOptionPane.showMessageDialog(null, message, Messages.getContextString("Title.ProjityError"), JOptionPane.ERROR_MESSAGE); System.exit(64); } } boolean newLook = false; // HashMap opts = ApplicationStartupFactory.extractOpts(args); // allow setting menu look on command line - primarily for testing or webstart args log.info(opts); // newLook = opts.get("menu") == null; Environment.setNewLook(newLook); // if (!Environment.isNewLaf()) { // try { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } catch (Exception e) { // } // } ApplicationStartupFactory startupFactory = new ApplicationStartupFactory(opts); //put before to initialize standalone flag mainFrame = new MainFrame(Messages.getContextString("Text.ApplicationTitle"), null, null); boolean doWelcome = true; // to do see if project param exists in args startupFactory.instanceFromNewSession(mainFrame, doWelcome); }
From source file:com.marklogic.client.example.util.Bootstrapper.java
/** * Command-line invocation./*from ww w. j a v a2s . c om*/ * @param args command-line arguments specifying the configuration and REST server */ public static void main(String[] args) throws ClientProtocolException, IOException, FactoryConfigurationError { Properties properties = new Properties(); for (int i = 0; i < args.length; i++) { String name = args[i]; if (name.startsWith("-") && name.length() > 1 && ++i < args.length) { name = name.substring(1); if ("properties".equals(name)) { InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name); if (propsStream == null) throw new IOException("Could not read bootstrapper properties"); Properties props = new Properties(); props.load(propsStream); props.putAll(properties); properties = props; } else { properties.put(name, args[i]); } } else { System.err.println("invalid argument: " + name); System.err.println(getUsage()); System.exit(1); } } String invalid = joinList(listInvalidKeys(properties)); if (invalid != null && invalid.length() > 0) { System.err.println("invalid arguments: " + invalid); System.err.println(getUsage()); System.exit(1); } // TODO: catch invalid argument exceptions and provide feedback new Bootstrapper().makeServer(properties); System.out.println("Created " + properties.getProperty("restserver") + " server on " + properties.getProperty("restport") + " port for " + properties.getProperty("restdb") + " database"); }
From source file:net.morphbank.webclient.ProcessFiles.java
/** * @param args//w w w. j a va 2 s. c om * args[0] directory including terminal '/' * args[1] prefix of request files * args[2] number of digits in file index value * args[3] number of files * args[4] index of first file (default 0) * args[5] prefix of service * args[6] prefix of response files (default args[1] + "Resp") */ public static void main(String[] args) { ProcessFiles fileProcessor = new ProcessFiles(); // restTest.processRequest(URL, UPLOAD_FILE); String zeros = "0000000"; if (args.length < 4) { System.out.println("Too few parameters"); } else { try { // get parameters String reqDir = args[0]; String reqPrefix = args[1]; int numDigits = Integer.valueOf(args[2]); if (numDigits > zeros.length()) numDigits = zeros.length(); NumberFormat intFormat = new DecimalFormat(zeros.substring(0, numDigits)); int numFiles = Integer.valueOf(args[3]); int firstFile = 0; BufferedReader fileIn = new BufferedReader(new FileReader(FILE_IN_PATH)); String line = fileIn.readLine(); fileIn.close(); firstFile = Integer.valueOf(line); // firstFile = 189; // numFiles = 1; int lastFile = firstFile + numFiles - 1; String url = URL; String respPrefix = reqPrefix + "Resp"; if (args.length > 5) respPrefix = args[5]; if (args.length > 6) url = args[6]; // process files for (int i = firstFile; i <= lastFile; i++) { String xmlOutputFile = null; String requestFile = reqDir + reqPrefix + intFormat.format(i) + ".xml"; System.out.println("Processing request file " + requestFile); String responseFile = reqDir + respPrefix + intFormat.format(i) + ".xml"; System.out.println("Response file " + responseFile); // restTest.processRequest(URL, UPLOAD_FILE); fileProcessor.processRequest(url, requestFile, responseFile); Writer fileOut = new FileWriter(FILE_IN_PATH, false); fileOut.append(Integer.toString(i + 1)); fileOut.close(); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.cloud.sample.UserCloudAPIExecutor.java
public static void main(String[] args) { // Host/*from www .ja v a 2 s. c o m*/ String host = null; // Fully qualified URL with http(s)://host:port String apiUrl = null; // ApiKey and secretKey as given by your CloudStack vendor String apiKey = null; String secretKey = null; try { Properties prop = new Properties(); prop.load(new FileInputStream("usercloud.properties")); // host host = prop.getProperty("host"); if (host == null) { System.out.println( "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); } // apiUrl apiUrl = prop.getProperty("apiUrl"); if (apiUrl == null) { System.out.println( "Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); } // apiKey apiKey = prop.getProperty("apiKey"); if (apiKey == null) { System.out.println( "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); } // secretKey secretKey = prop.getProperty("secretKey"); if (secretKey == null) { System.out.println( "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); } if (apiUrl == null || apiKey == null || secretKey == null) { return; } System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); // Step 1: Make sure your APIKey is URL encoded String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); // Step 2: URL encode each parameter value, then sort the parameters and apiKey in // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using // '&' to delimit // the string List<String> sortedParams = new ArrayList<String>(); sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); StringTokenizer st = new StringTokenizer(apiUrl, "&"); String url = null; boolean first = true; while (st.hasMoreTokens()) { String paramValue = st.nextToken(); String param = paramValue.substring(0, paramValue.indexOf("=")); String value = URLEncoder .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); if (first) { url = param + "=" + value; first = false; } else { url = url + "&" + param + "=" + value; } sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); } Collections.sort(sortedParams); System.out.println("Sorted Parameters: " + sortedParams); // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key String sortedUrl = null; first = true; for (String param : sortedParams) { if (first) { sortedUrl = param; first = false; } else { sortedUrl = sortedUrl + "&" + param; } } System.out.println("sorted URL : " + sortedUrl); String encodedSignature = signRequest(sortedUrl, secretKey); // Step 4: Construct the final URL we want to send to the CloudStack Management Server // Final result should look like: // http(s)://://client/api?&apiKey=&signature= String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; System.out.println("final URL : " + finalUrl); // Step 5: Perform a HTTP GET on this URL to execute the command HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(finalUrl); int responseCode = client.executeMethod(method); if (responseCode == 200) { // SUCCESS! System.out.println("Successfully executed command"); } else { // FAILED! System.out.println("Unable to execute command with response code: " + responseCode); } } catch (Throwable t) { System.out.println(t); } }
From source file:com.yahoo.semsearch.fastlinking.EntityContextFastEntityLinker.java
/** * Context-aware command line entity linker * @param args arguments (see -help for further info) * @throws Exception//from w w w . j a va2 s . co m */ public static void main(String args[]) throws Exception { SimpleJSAP jsap = new SimpleJSAP(EntityContextFastEntityLinker.class.getName(), "Interactive mode for entity linking", new Parameter[] { new FlaggedOption("hash", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'h', "hash", "quasi succint hash"), new FlaggedOption("vectors", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'v', "vectors", "Word vectors file"), new FlaggedOption("labels", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'l', "labels", "File containing query2entity labels"), new FlaggedOption("id2type", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'i', "id2type", "File with the id2type mapping"), new Switch("centroid", 'c', "centroid", "Use centroid-based distances and not LR"), new FlaggedOption("map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'm', "map", "Entity 2 type mapping "), new FlaggedOption("threshold", JSAP.STRING_PARSER, "-20", JSAP.NOT_REQUIRED, 'd', "threshold", "Score threshold value "), new FlaggedOption("entities", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'e', "entities", "Entities word vectors file"), }); JSAPResult jsapResult = jsap.parse(args); if (jsap.messagePrinted()) return; double threshold = Double.parseDouble(jsapResult.getString("threshold")); QuasiSuccinctEntityHash hash = (QuasiSuccinctEntityHash) BinIO.loadObject(jsapResult.getString("hash")); EntityContext queryContext; if (!jsapResult.getBoolean("centroid")) { queryContext = new LREntityContext(jsapResult.getString("vectors"), jsapResult.getString("entities"), hash); } else { queryContext = new CentroidEntityContext(jsapResult.getString("vectors"), jsapResult.getString("entities"), hash); } HashMap<String, ArrayList<EntityRelevanceJudgment>> labels = null; if (jsapResult.getString("labels") != null) { labels = readTrainingData(jsapResult.getString("labels")); } String map = jsapResult.getString("map"); HashMap<String, String> entities2Type = null; if (map != null) entities2Type = readEntity2IdFile(map); EntityContextFastEntityLinker linker = new EntityContextFastEntityLinker(hash, queryContext); final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String q; for (;;) { System.out.print(">"); q = br.readLine(); if (q == null) { System.err.println(); break; // CTRL-D } if (q.length() == 0) continue; long time = -System.nanoTime(); try { List<EntityResult> results = linker.getResults(q, threshold); //List<EntityResult> results = linker.getResultsGreedy( q, 5 ); //int rank = 0; for (EntityResult er : results) { if (entities2Type != null) { String name = er.text.toString().trim(); String newType = entities2Type.get(name); if (newType == null) newType = "NF"; System.out.println(q + "\t span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id + " ( t= " + newType + ")" + " score: " + er.score + " ( " + er.s.span + " ) "); //System.out.println( newType + "\t" + q + "\t" + StringUtils.remove( q, er.s.span.toString() ) + " \t " + er.text ); break; /* } else { System.out.print( "[" + er.text + "(" + String.format("%.2f",er.score) +")] "); System.out.println( "span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id + " ( t= " + typeMapping.get( hash.getEntity( er.id ).type ) + " score: " + er.score + " ( " + er.s.span + " ) " ); } rank++; */ } else { if (labels == null) { System.out.println(q + "\t" + er.text + "\t" + er.score); } else { ArrayList<EntityRelevanceJudgment> jds = labels.get(q); String label = "NF"; if (jds != null) { EntityRelevanceJudgment relevanceOfEntity = relevanceOfEntity(er.text, jds); label = relevanceOfEntity.label; } System.out.println(q + "\t" + er.text + "\t" + label + "\t" + er.score); break; } } System.out.println(); } time += System.nanoTime(); System.out.println("Time to rank and print the candidates:" + time / 1000000. + " ms"); } catch (Exception e) { e.printStackTrace(); } } }
From source file:edu.msu.cme.rdp.kmer.KmerFilter.java
public static void main(String[] args) throws Exception { final KmerTrie kmerTrie; final SeqReader queryReader; final SequenceType querySeqType; final File queryFile; final KmerStartsWriter out; final boolean translQuery; final int wordSize; final int translTable; final boolean alignedSeqs; final List<String> refLabels = new ArrayList(); final int maxThreads; try {// www.j ava 2 s .c o m CommandLine cmdLine = new PosixParser().parse(options, args); args = cmdLine.getArgs(); if (args.length < 3) { throw new Exception("Unexpected number of arguments"); } if (cmdLine.hasOption("out")) { out = new KmerStartsWriter(cmdLine.getOptionValue("out")); } else { out = new KmerStartsWriter(System.out); } if (cmdLine.hasOption("aligned")) { alignedSeqs = true; } else { alignedSeqs = false; } if (cmdLine.hasOption("transl-table")) { translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table")); } else { translTable = 11; } if (cmdLine.hasOption("threads")) { maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads")); } else { maxThreads = Runtime.getRuntime().availableProcessors(); } queryFile = new File(args[1]); wordSize = Integer.valueOf(args[0]); SequenceType refSeqType = null; querySeqType = SeqUtils.guessSequenceType(queryFile); queryReader = new SequenceReader(queryFile); if (querySeqType == SequenceType.Protein) { throw new Exception("Expected nucl query sequences"); } refSeqType = SeqUtils .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2])); translQuery = refSeqType == SequenceType.Protein; if (translQuery && wordSize % 3 != 0) { throw new Exception("Word size must be a multiple of 3 for nucl ref seqs"); } int trieWordSize; if (translQuery) { trieWordSize = wordSize / 3; } else { trieWordSize = wordSize; } kmerTrie = new KmerTrie(trieWordSize, translQuery); for (int index = 2; index < args.length; index++) { String refName; String refFileName = args[index]; if (refFileName.contains("=")) { String[] lexemes = refFileName.split("="); refName = lexemes[0]; refFileName = lexemes[1]; } else { String tmpName = new File(refFileName).getName(); if (tmpName.contains(".")) { refName = tmpName.substring(0, tmpName.lastIndexOf(".")); } else { refName = tmpName; } } File refFile = new File(refFileName); if (refSeqType != SeqUtils.guessSequenceType(refFile)) { throw new Exception( "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile) + " sequences but expected " + refSeqType + " sequences"); } SequenceReader seqReader = new SequenceReader(refFile); Sequence seq; while ((seq = seqReader.readNextSequence()) != null) { if (seq.getSeqName().startsWith("#")) { continue; } if (alignedSeqs) { kmerTrie.addModelSequence(seq, refLabels.size()); } else { kmerTrie.addSequence(seq, refLabels.size()); } } seqReader.close(); refLabels.add(refName); } } catch (Exception e) { new HelpFormatter().printHelp("KmerSearch <word_size> <query_file> [name=]<ref_file> ...", options); System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables } long startTime = System.currentTimeMillis(); long seqCount = 0; final int maxTasks = 25000; /* * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else { */ //} System.err.println("Starting kmer mapping at " + new Date()); System.err.println("* Number of threads: " + maxThreads); System.err.println("* References: " + refLabels); System.err.println("* Reads file: " + queryFile); System.err.println("* Kmer length: " + kmerTrie.getWordSize()); final AtomicInteger processed = new AtomicInteger(); final AtomicInteger outstandingTasks = new AtomicInteger(); ExecutorService service = Executors.newFixedThreadPool(maxThreads); Sequence querySeq; while ((querySeq = queryReader.readNextSequence()) != null) { seqCount++; String seqString = querySeq.getSeqString(); if (seqString.length() < 3) { System.err.println("Sequence " + querySeq.getSeqName() + "'s length is less than 3"); continue; } final Sequence threadSeq = querySeq; Runnable r = new Runnable() { public void run() { try { processSeq(threadSeq, refLabels, kmerTrie, out, wordSize, translQuery, translTable, false); processSeq(threadSeq, refLabels, kmerTrie, out, wordSize, translQuery, translTable, true); } catch (IOException e) { throw new RuntimeException(e); } processed.incrementAndGet(); outstandingTasks.decrementAndGet(); } }; outstandingTasks.incrementAndGet(); service.submit(r); while (outstandingTasks.get() >= maxTasks) ; if ((processed.get() + 1) % 1000000 == 0) { System.err.println("Processed " + processed + " sequences in " + (System.currentTimeMillis() - startTime) + " ms"); } } service.shutdown(); service.awaitTermination(1, TimeUnit.DAYS); System.err.println("Finished Processed " + processed + " sequences in " + (System.currentTimeMillis() - startTime) + " ms"); out.close(); }
From source file:MainClass.java
public static void main(String[] args) { String phrase = new String("text\n"); String dirname = "C:/test"; // Directory name String filename = "byteData.txt"; File aFile = new File(dirname, filename); // Create the file output stream FileOutputStream file = null; try {//from w ww.jav a2 s . c o m file = new FileOutputStream(aFile, true); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } FileChannel outChannel = file.getChannel(); ByteBuffer buf = ByteBuffer.allocate(phrase.length()); byte[] bytes = phrase.getBytes(); buf.put(bytes); buf.flip(); try { outChannel.write(buf); file.close(); } catch (IOException e) { e.printStackTrace(System.err); } }
From source file:com.cyberway.issue.util.SurtPrefixSet.java
/** * Allow class to be used as a command-line tool for converting * URL lists (or naked host or host/path fragments implied * to be HTTP URLs) to implied SURT prefix form. * /*from w ww. ja v a 2 s.co m*/ * Read from stdin or first file argument. Writes to stdout. * * @param args cmd-line arguments: may include input file * @throws IOException */ public static void main(String[] args) throws IOException { InputStream in = args.length > 0 ? new BufferedInputStream(new FileInputStream(args[0])) : System.in; PrintStream out = args.length > 1 ? new PrintStream(new BufferedOutputStream(new FileOutputStream(args[1]))) : System.out; BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { if (line.indexOf("#") > 0) line = line.substring(0, line.indexOf("#")); line = line.trim(); if (line.length() == 0) continue; out.println(prefixFromPlain(line)); } br.close(); out.close(); }