List of usage examples for java.lang String indexOf
public int indexOf(String str)
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. * // w ww . j a v a2s. com * 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(); }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("u", null, true, "Solr URI"); options.addOption("q", null, true, "Query"); options.addOption("n", null, true, "Max # of results"); options.addOption("o", null, true, "An optional TREC-style output file"); options.addOption("w", null, false, "Do a warm-up query call, before each query"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter trecOutFile = null; try {/*w w w .j av a 2s. co m*/ CommandLine cmd = parser.parse(options, args); String queryFile = null, solrURI = null; if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } SolrServerWrapper solr = new SolrServerWrapper(solrURI); if (cmd.hasOption("q")) { queryFile = cmd.getOptionValue("q"); } else { Usage("Specify Query file"); } int numRet = 100; if (cmd.hasOption("n")) { numRet = Integer.parseInt(cmd.getOptionValue("n")); } if (cmd.hasOption("o")) { trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o")))); } List<String> fieldList = new ArrayList<String>(); fieldList.add(UtilConst.ID_FIELD); fieldList.add(UtilConst.SCORE_FIELD); double totalTime = 0; double retQty = 0; ArrayList<Double> queryTimes = new ArrayList<Double>(); boolean bDoWarmUp = cmd.hasOption("w"); if (bDoWarmUp) { System.out.println("Using a warmup step!"); } int queryQty = 0; for (String t : FileUtils.readLines(new File(queryFile))) { t = t.trim(); if (t.isEmpty()) continue; int ind = t.indexOf('|'); if (ind < 0) throw new Exception("Wrong format, line: '" + t + "'"); String qID = t.substring(0, ind); String q = t.substring(ind + 1); SolrDocumentList res = null; if (bDoWarmUp) { res = solr.runQuery(q, fieldList, numRet); } Long tm1 = System.currentTimeMillis(); res = solr.runQuery(q, fieldList, numRet); Long tm2 = System.currentTimeMillis(); retQty += res.getNumFound(); System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms"); double delta = (tm2 - tm1); totalTime += delta; queryTimes.add(delta); ++queryQty; if (trecOutFile != null) { ArrayList<SolrRes> resArr = new ArrayList<SolrRes>(); for (SolrDocument doc : res) { String id = (String) doc.getFieldValue(UtilConst.ID_FIELD); float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD); resArr.add(new SolrRes(id, "", score)); } SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]); Arrays.sort(results); SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length); } } double devTime = 0, meanTime = totalTime / queryQty; for (int i = 0; i < queryQty; ++i) { double d = queryTimes.get(i) - meanTime; devTime += d * d; } devTime = Math.sqrt(devTime / (queryQty - 1)); System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime)); System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty)); solr.close(); trecOutFile.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:client.MultiplexingClient.java
public static void main(String[] args) throws Exception { // Prepare to parse the command line Options options = new Options(); Option sslOpt = new Option("s", "ssl", false, "Use SSL"); Option debugOpt = new Option("d", true, "Debug level (NONE, FINER, FINE, CONFIG, INFO, WARNING, SEVERE. Default INFO."); Option numConnectionsOpt = new Option("n", true, "Number of connections to establish. [Default: 1]"); Option numPcktOpt = new Option("p", true, "Number of packets to send in each connection. [Default: 20]"); Option pcktMaxSizeOpt = new Option("m", true, "Maximum size of packets. [Default: 4096]"); Option help = new Option("h", "print this message"); options.addOption(help);/* ww w .j a va 2 s . c o m*/ options.addOption(debugOpt); options.addOption(numConnectionsOpt); options.addOption(numPcktOpt); options.addOption(pcktMaxSizeOpt); options.addOption(sslOpt); CommandLineParser parser = new PosixParser(); // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt()) || line.getArgs().length < 1) { showUsage(options); return; } if (line.hasOption(sslOpt.getOpt())) { channelFactory = new SSLChannelFactory(true, TRUSTSTORE, TRUSTSTORE_PASSWORD); } else { channelFactory = new PlainChannelFactory(); } if (line.hasOption(numConnectionsOpt.getOpt())) { connectionCount = Integer.parseInt(line.getOptionValue(numConnectionsOpt.getOpt())); } else { connectionCount = 1; } if (line.hasOption(numPcktOpt.getOpt())) { packetsToSend = Integer.parseInt(line.getOptionValue(numPcktOpt.getOpt())); } else { packetsToSend = 20; } if (line.hasOption(pcktMaxSizeOpt.getOpt())) { maxPcktSize = Integer.parseInt(line.getOptionValue(pcktMaxSizeOpt.getOpt())); } else { maxPcktSize = 4096; } InetSocketAddress remotePoint; try { String host = line.getArgs()[0]; int colonIndex = host.indexOf(':'); remotePoint = new InetSocketAddress(host.substring(0, colonIndex), Integer.parseInt(host.substring(colonIndex + 1))); } catch (Exception e) { showUsage(options); return; } // Setups the logging context for Log4j // NDC.push(Thread.currentThread().getName()); st = new SelectorThread(); for (int i = 0; i < connectionCount; i++) { new MultiplexingClient(remotePoint); // Must sleep for a while between opening connections in order // to give the remote host enough time to handle them. Otherwise, // the remote host backlog will get full and the connection // attemps will start to be refused. Thread.sleep(100); } }
From source file:de.mpg.escidoc.services.edoc.BatchUpdate.java
/** * @param args/*from w w w . ja va2 s . co m*/ */ public static void main(String[] args) throws Exception { CORESERVICES_URL = PropertyReader.getProperty("escidoc.framework_access.framework.url"); String userHandle = AdminHelper.loginUser("import_user", ""); logger.info("Querying core-services..."); HttpClient httpClient = new HttpClient(); String filter = "<param><filter name=\"http://escidoc.de/core/01/structural-relations/context\">" + IMPORT_CONTEXT + "</filter><order-by>http://escidoc.de/core/01/properties/creation-date</order-by><limit>0</limit></param>"; logger.info("Filter: " + filter); PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/items/filter"); postMethod.setRequestBody(filter); ProxyHelper.executeMethod(httpClient, postMethod); // GetMethod getMethod = new GetMethod(CORESERVICES_URL + "/ir/item/escidoc:100220"); // getMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle)ProxyHelper.executeMethod(httpClient, getMethod)hod(httpClient, getMethod); String response = postMethod.getResponseBodyAsString(); logger.info("...done!"); System.out.println(response); while (response.contains("<escidocItem:item")) { int startPos = response.indexOf("<escidocItem:item"); int endPos = response.indexOf("</escidocItem:item>"); String item = response.substring(startPos, endPos + 19); response = response.substring(endPos + 19); startPos = item.indexOf("xlink:href=\""); endPos = item.indexOf("\"", startPos + 12); String objId = item.substring(startPos + 12, endPos); System.out.print(objId); if (item.contains("escidoc:22019")) { item = item.replaceAll("escidoc:22019", "escidoc:55222"); PutMethod putMethod = new PutMethod(CORESERVICES_URL + objId); putMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle); putMethod.setRequestEntity(new StringRequestEntity(item)); ProxyHelper.executeMethod(httpClient, putMethod); String result = putMethod.getResponseBodyAsString(); //System.out.println(item); startPos = result.indexOf("last-modification-date=\""); endPos = result.indexOf("\"", startPos + 24); String modDate = result.substring(startPos + 24, endPos); //System.out.println("modDate: " + modDate); String param = "<param last-modification-date=\"" + modDate + "\"><url>http://pubman.mpdl.mpg.de/pubman/item/" + objId.substring(4) + "</url></param>"; postMethod = new PostMethod(CORESERVICES_URL + objId + "/assign-version-pid"); postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle); postMethod.setRequestEntity(new StringRequestEntity(param)); ProxyHelper.executeMethod(httpClient, postMethod); result = postMethod.getResponseBodyAsString(); //System.out.println("Result: " + result); startPos = result.indexOf("last-modification-date=\""); endPos = result.indexOf("\"", startPos + 24); modDate = result.substring(startPos + 24, endPos); //System.out.println("modDate: " + modDate); param = "<param last-modification-date=\"" + modDate + "\"><comment>Batch repair of organizational unit identifier</comment></param>"; postMethod = new PostMethod(CORESERVICES_URL + objId + "/submit"); postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle); postMethod.setRequestEntity(new StringRequestEntity(param)); ProxyHelper.executeMethod(httpClient, postMethod); result = postMethod.getResponseBodyAsString(); //System.out.println("Result: " + result); startPos = result.indexOf("last-modification-date=\""); endPos = result.indexOf("\"", startPos + 24); modDate = result.substring(startPos + 24, endPos); //System.out.println("modDate: " + modDate); param = "<param last-modification-date=\"" + modDate + "\"><comment>Batch repair of organizational unit identifier</comment></param>"; postMethod = new PostMethod(CORESERVICES_URL + objId + "/release"); postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle); postMethod.setRequestEntity(new StringRequestEntity(param)); ProxyHelper.executeMethod(httpClient, postMethod); result = postMethod.getResponseBodyAsString(); //System.out.println("Result: " + result); System.out.println("...changed"); } else { System.out.println("...not affected"); } } }
From source file:com.joliciel.lefff.Lefff.java
/** * @param args//w w w.j a va 2 s .com */ public static void main(String[] args) throws Exception { long startTime = (new Date()).getTime(); String command = args[0]; String memoryBaseFilePath = ""; String lefffFilePath = ""; String posTagSetPath = ""; String posTagMapPath = ""; String word = null; List<String> categories = null; int startLine = -1; int stopLine = -1; boolean firstArg = true; for (String arg : args) { if (firstArg) { firstArg = false; continue; } int equalsPos = arg.indexOf('='); String argName = arg.substring(0, equalsPos); String argValue = arg.substring(equalsPos + 1); if (argName.equals("memoryBase")) memoryBaseFilePath = argValue; else if (argName.equals("lefffFile")) lefffFilePath = argValue; else if (argName.equals("startLine")) startLine = Integer.parseInt(argValue); else if (argName.equals("stopLine")) stopLine = Integer.parseInt(argValue); else if (argName.equals("posTagSet")) posTagSetPath = argValue; else if (argName.equals("posTagMap")) posTagMapPath = argValue; else if (argName.equals("word")) word = argValue; else if (argName.equals("categories")) { String[] parts = argValue.split(","); categories = new ArrayList<String>(); for (String part : parts) { categories.add(part); } } else throw new RuntimeException("Unknown argument: " + argName); } final LefffServiceLocator locator = new LefffServiceLocator(); locator.setDataSourcePropertiesFile("jdbc-live.properties"); TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance(); final LefffService lefffService = locator.getLefffService(); if (command.equals("load")) { if (lefffFilePath.length() == 0) throw new RuntimeException("Required argument: lefffFile"); final LefffLoader loader = lefffService.getLefffLoader(); File file = new File(lefffFilePath); if (startLine > 0) loader.setStartLine(startLine); if (stopLine > 0) loader.setStopLine(stopLine); loader.LoadFile(file); } else if (command.equals("serialiseBase")) { if (memoryBaseFilePath.length() == 0) throw new RuntimeException("Required argument: memoryBase"); if (posTagSetPath.length() == 0) throw new RuntimeException("Required argument: posTagSet"); if (posTagMapPath.length() == 0) throw new RuntimeException("Required argument: posTagMap"); PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator(); PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService(); File posTagSetFile = new File(posTagSetPath); PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile); File posTagMapFile = new File(posTagMapPath); LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet); Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>(); posTagMappers.put(posTagSet, posTagMapper); LefffMemoryLoader loader = new LefffMemoryLoader(); LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories); File memoryBaseFile = new File(memoryBaseFilePath); memoryBaseFile.delete(); loader.serializeMemoryBase(memoryBase, memoryBaseFile); } else if (command.equals("deserialiseBase")) { if (memoryBaseFilePath.length() == 0) throw new RuntimeException("Required argument: memoryBase"); LefffMemoryLoader loader = new LefffMemoryLoader(); File memoryBaseFile = new File(memoryBaseFilePath); LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile); String[] testWords = new String[] { "avoir" }; if (word != null) { testWords = word.split(","); } for (String testWord : testWords) { Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord); LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size()); int i = 1; for (PosTag posTag : possiblePosTags) { LOG.debug("### PosTag " + (i++) + ":" + posTag); } List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord); LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size()); i = 1; for (LexicalEntry entry : entriesForWord) { LOG.debug("### Entry " + (i++) + ":" + entry.getWord()); LOG.debug("Category " + entry.getCategory()); LOG.debug("Predicate " + entry.getPredicate()); LOG.debug("Lemma " + entry.getLemma()); LOG.debug("Morphology " + entry.getMorphology()); } List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, ""); LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size()); for (LexicalEntry entry : entriesForLemma) { LOG.debug("### Entry " + entry.getWord()); LOG.debug("Category " + entry.getCategory()); LOG.debug("Predicate " + entry.getPredicate()); LOG.debug("Lemma " + entry.getLemma()); LOG.debug("Morphology " + entry.getMorphology()); for (PredicateArgument argument : entry.getPredicateArguments()) { LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional()); for (String realisation : argument.getRealisations()) { LOG.debug("Realisation: " + realisation); } } } } } else { System.out.println("Usage : Lefff load filepath"); } long endTime = (new Date()).getTime() - startTime; LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds"); }
From source file:hk.hku.cecid.corvus.http.AS2EnvelopQuerySender.java
/** * The main method is for CLI mode./*from www. j a v a 2 s .co m*/ */ public static void main(String[] args) { try { java.io.PrintStream out = System.out; if (args.length < 2) { out.println("Usage: as2-envelop [config-xml] [log-path]"); out.println(); out.println("Example: as2-envelop ./config/as2-envelop/as2-request.xml ./logs/as2-envelop.log"); System.exit(1); } out.println("------------------------------------------------------"); out.println(" AS2 Envelop Queryer "); out.println("------------------------------------------------------"); // Initialize the logger. out.println("Initialize logger .. "); // The logger path is specified at the last argument. FileLogger logger = new FileLogger(new File(args[args.length - 1])); // Initialize the query parameter. out.println("Importing AS2 administrative sending parameters ... "); AS2AdminData acd = DataFactory.getInstance() .createAS2AdminDataFromXML(new PropertyTree(new File(args[0]).toURI().toURL())); boolean historyQueryNeeded = false; AS2MessageHistoryRequestData queryData = new AS2MessageHistoryRequestData(); if (acd.getMessageIdCriteria() == null || acd.getMessageIdCriteria().trim().equals("")) { historyQueryNeeded = true; // print command prompt out.println("No messageID was specified!"); out.println("Start querying message repositry ..."); String endpoint = acd.getEnvelopQueryEndpoint(); String host = endpoint.substring(0, endpoint.indexOf("/corvus")); host += "/corvus/httpd/as2/msg_history"; queryData.setEndPoint(host); } /* If the user has entered message id but no messagebox, using the messageid as serach criteria and as user to chose his target message */ else if (acd.getMessageBoxCriteria() == null || acd.getMessageBoxCriteria().trim().equals("")) { historyQueryNeeded = true; // print command prompt out.println("Message Box value haven't specified."); out.println("Start query message whcih matched with messageID: " + acd.getMessageIdCriteria()); String endpoint = acd.getEnvelopQueryEndpoint(); String host = endpoint.substring(0, endpoint.indexOf("/corvus")); host += "/corvus/httpd/as2/msg_history"; queryData.setEndPoint(host); queryData.setMessageId(acd.getMessageIdCriteria()); } //Debug Message System.out.println("history Endpoint: " + queryData.getEndPoint()); System.out.println("Repositry Endpoint: " + acd.getEnvelopQueryEndpoint()); if (historyQueryNeeded) { List msgList = listAvailableMessage(queryData, logger); if (msgList == null || msgList.size() == 0) { out.println(); out.println(); out.println("No stream data found in repositry..."); out.println("Please view log for details .. "); return; } int selection = promptForSelection(msgList); if (selection == -1) { return; } String messageID = (String) ((List) msgList.get(selection)).get(0); String messageBox = (String) ((List) msgList.get(selection)).get(1); acd.setMessageIdCriteria(messageID); acd.setMessageBoxCriteria(messageBox.toUpperCase()); out.println(); out.println(); out.println("Start download targeted message envelop ..."); } // Initialize the sender. out.println("Initialize AS2 HTTP data service client... "); AS2EnvelopQuerySender sender = new AS2EnvelopQuerySender(logger, acd); out.println("Sending AS2 HTTP Envelop Query request ... "); sender.run(); out.println(); out.println(" Sending Done: "); out.println("----------------------------------------------------"); out.println("The Message Envelope : "); InputStream eins = sender.getEnvelopStream(); if (eins.available() == 0) { out.println("No stream data found."); out.println("The message envelop does not exist for message id " + sender.getMessageIdToDownload() + " and message box " + sender.getMessageBoxToDownload()); } else IOHandler.pipe(sender.getEnvelopStream(), out); out.println("Please view log for details .. "); } catch (Exception e) { e.printStackTrace(System.err); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { ParserGetter kit = new ParserGetter(); HTMLEditorKit.Parser parser = kit.getParser(); URL u = new URL("http://www.java2s.com"); InputStream in = u.openStream(); InputStreamReader r = new InputStreamReader(in); String remoteFileName = u.getFile(); if (remoteFileName.endsWith("/")) { remoteFileName += "index.html"; }//from w w w . ja v a 2s. c o m if (remoteFileName.startsWith("/")) { remoteFileName = remoteFileName.substring(1); } File localDirectory = new File(u.getHost()); while (remoteFileName.indexOf('/') > -1) { String part = remoteFileName.substring(0, remoteFileName.indexOf('/')); remoteFileName = remoteFileName.substring(remoteFileName.indexOf('/') + 1); localDirectory = new File(localDirectory, part); } if (localDirectory.mkdirs()) { File output = new File(localDirectory, remoteFileName); FileWriter out = new FileWriter(output); HTMLEditorKit.ParserCallback callback = new PageSaver(out, u); parser.parse(r, callback, false); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { Document document = new Document(PageSize.A6); PdfWriter.getInstance(document, new FileOutputStream("2.pdf")); document.open();//from w ww .j av a 2 s . co m document.add(new Paragraph("Hello World")); document.add(new Paragraph("Hello People")); document.close(); PdfReader reader = new PdfReader("2.pdf"); PdfDictionary page = reader.getPageN(1); PRIndirectReference objectReference = (PRIndirectReference) page.get(PdfName.CONTENTS); PRStream stream = (PRStream) PdfReader.getPdfObject(objectReference); byte[] streamBytes = PdfReader.getStreamBytes(stream); String contentStream = new String(streamBytes); System.out.println(contentStream); PRTokeniser tokenizer = new PRTokeniser(streamBytes); while (tokenizer.nextToken()) { if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) { System.out.println(tokenizer.getStringValue()); } } StringBuffer buf = new StringBuffer(); int pos = contentStream.indexOf("Hello World") + 11; buf.append(contentStream.substring(0, pos)); buf.append("Hello"); buf.append(contentStream.substring(pos)); String hackedContentStream = buf.toString(); document = new Document(PageSize.A6); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorldStreamHacked.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.setLiteral(hackedContentStream); document.close(); }
From source file:edu.msu.cme.rdp.classifier.train.validation.distance.TaxaSimilarityMain.java
/** * This calculates the average similarity (Sab score or pairwise alignment) between taxa at given ranks and plot the box and whisker plot and accumulation curve. * The distances associate to a given rank contains the distances between different child taxa. It does not include the distances within the same child taxa. * For example, if a query and it's closest match are from the same genus, the distance value is added to that genus. * If there are from different genera but the same family, the distance value is added to that family, etc. * @param args/*ww w .j ava2 s. c om*/ * @throws IOException */ public static void main(String[] args) throws IOException, OverlapCheckFailedException { String usage = "Usage: taxonfile trainset.fasta query.fasta outdir kmersize rankFile sab|pw \n" + " This program calculates the average similarity (Sab score, or pairwise alignment) within taxa\n" + " and plot the box and whisker plot and accumulation curve plot. \n" + " rankFile: a file contains a list of ranks to be calculated and plotted. One rank per line, no particular order required. \n" + " Note pw is extremely slower, recommended only for lower ranks such as species, genus and family. "; if (args.length != 7) { System.err.println(usage); System.exit(1); } List<String> ranks = readRanks(args[5]); File outdir = new File(args[3]); if (!outdir.isDirectory()) { System.err.println("outdir must be a directory"); System.exit(1); } int kmer = Integer.parseInt(args[4]); GoodWordIterator.setWordSize(kmer); TaxaSimilarityMain theObj = new TaxaSimilarityMain(ranks); String plotTitle = new File(args[2]).getName(); int index = plotTitle.indexOf("."); if (index != -1) { plotTitle = plotTitle.substring(0, index); } if (args[6].equalsIgnoreCase("sab")) { theObj.calSabSimilarity(args[0], args[1], args[2]); } else { theObj.calPairwiseSimilaritye(args[0], args[1], args[2]); } theObj.createPlot(plotTitle, outdir); }
From source file:cht.Parser.java
public static void main(String[] args) throws IOException { // TODO get from google drive boolean isUnicode = false; boolean isRemoveInputFileOnComplete = false; int rowNum;/*from w w w . j ava 2 s.c om*/ int colNum; Gson gson = new GsonBuilder().setPrettyPrinting().create(); Properties prop = new Properties(); try { prop.load(new FileInputStream("config.txt")); } catch (IOException ex) { ex.printStackTrace(); } String inputFilePath = prop.getProperty("inputFile"); String outputDirectory = prop.getProperty("outputDirectory"); System.out.println(outputDirectory); // optional String unicode = prop.getProperty("unicode"); String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete"); inputFilePath = inputFilePath.trim(); outputDirectory = outputDirectory.trim(); if (unicode != null) { isUnicode = Boolean.parseBoolean(unicode.trim()); } if (removeInputFileOnComplete != null) { isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim()); } Writer out = null; FileInputStream in = null; final String newLine = System.getProperty("line.separator").toString(); final String separator = File.separator; try { in = new FileInputStream(inputFilePath); Workbook workbook = new XSSFWorkbook(in); Sheet sheet = workbook.getSheetAt(0); rowNum = sheet.getLastRowNum() + 1; colNum = sheet.getRow(0).getPhysicalNumberOfCells(); for (int j = 1; j < colNum; ++j) { String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue(); // guess directory int slash = outputFilename.indexOf('/'); if (slash != -1) { // has directory outputFilename = outputFilename.substring(0, slash) + separator + outputFilename.substring(slash + 1); } String outputPath = FilenameUtils.concat(outputDirectory, outputFilename); System.out.println("--Writing " + outputPath); out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8"); TreeMap<String, Object> map = new TreeMap<String, Object>(); for (int i = 1; i < rowNum; i++) { try { String key = sheet.getRow(i).getCell(0).getStringCellValue(); //String value = ""; Cell tmp = sheet.getRow(i).getCell(j); if (tmp != null) { // not empty string! value = sheet.getRow(i).getCell(j).getStringCellValue(); } if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) { value = isUnicode ? StringEscapeUtils.escapeJava(value) : value; int firstdot = key.indexOf("."); String keyName, keyAttribute; if (firstdot > 0) {// a.b.c.d keyName = key.substring(0, firstdot); // a keyAttribute = key.substring(firstdot + 1); // b.c.d TreeMap oldhash = null; Object old = null; if (map.get(keyName) != null) { old = map.get(keyName); if (old instanceof TreeMap == false) { System.out.println("different type of key:" + key); continue; } oldhash = (TreeMap) old; } else { oldhash = new TreeMap(); } int firstdot2 = keyAttribute.indexOf("."); String rootName, childName; if (firstdot2 > 0) {// c, d.f --> d, f rootName = keyAttribute.substring(0, firstdot2); childName = keyAttribute.substring(firstdot2 + 1); } else {// c, d -> d, null rootName = keyAttribute; childName = null; } TreeMap<String, Object> object = myPut(oldhash, rootName, childName); map.put(keyName, object); } else {// c, d -> d, null keyName = key; keyAttribute = null; // simple string mode map.put(key, value); } } } catch (Exception e) { // just ingore empty rows } } String json = gson.toJson(map); // output json out.write(json + newLine); out.close(); } in.close(); System.out.println("\n---Complete!---"); System.out.println("Read input file from " + inputFilePath); System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory); System.out.println(rowNum + " records are generated for each output file."); System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no")); if (isRemoveInputFileOnComplete) { File input = new File(inputFilePath); input.deleteOnExit(); System.out.println("Deleted " + inputFilePath); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { in.close(); } } }