List of usage examples for java.lang String length
public int length()
From source file:com.tc.simple.apn.quicktests.Test.java
/** * @param args//from w ww . j a v a 2 s. c o m */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:org.ala.hbase.RepoDataLoader.java
/** * This takes a list of infosource ids... * <p/>/*from w ww. j a v a 2 s.co m*/ * Usage: -stats or -reindex or -gList and list of infosourceId * * @param args */ public static void main(String[] args) throws Exception { //RepoDataLoader loader = new RepoDataLoader(); ApplicationContext context = SpringUtils.getContext(); RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class); long start = System.currentTimeMillis(); loader.loadInfoSources(); String filePath = repositoryDir; if (args.length > 0) { if (args[0].equalsIgnoreCase("-stats")) { loader.statsOnly = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); } if (args[0].equalsIgnoreCase("-reindex")) { loader.reindex = true; loader.indexer = context.getBean(PartialIndex.class); args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -reindex: " + loader.reindex); logger.debug("reindex url: " + loader.reindexUrl); } if (args[0].equalsIgnoreCase("-gList")) { loader.gList = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -gList: " + loader.gList); } if (args[0].equalsIgnoreCase("-biocache")) { Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); RestfulClient restfulClient = new RestfulClient(0); String fq = "&fq="; if (args.length > 1) { java.util.Date date = new java.util.Date(); if (args[1].equals("-lastWeek")) { date = DateUtils.addWeeks(date, -1); } else if (args[1].equals("-lastMonth")) { date = DateUtils.addMonths(date, -1); } else if (args[1].equals("-lastYear")) { date = DateUtils.addYears(date, -1); } else date = null; if (date != null) { SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D"; } } Object[] resp = restfulClient .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0", hashTable); logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0"); if ((Integer) resp[0] == HttpStatus.SC_OK) { String content = resp[1].toString(); logger.debug(resp[1]); if (content != null && content.length() > "[]".length()) { Map map = mapper.readValue(content, Map.class); try { List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map .get("facetResults")).get(0)).get("fieldResult")); Set<String> arg = new LinkedHashSet<String>(); for (int i = 0; i < list.size(); i++) { java.util.LinkedHashMap<String, String> value = list.get(i); String dataResource = getDataResource(value.get("fq")); Object provider = (loader.getUidInfoSourceMap().get(dataResource)); if (provider != null) { arg.add(provider.toString()); } } logger.info("Set of biocache infosource ids to load: " + arg); args = new String[] {}; args = arg.toArray(args); //handle the situation where biocache-service reports no data resources if (args.length < 1) { logger.error("No biocache data resources found. Unable to load."); System.exit(0); } } catch (Exception e) { logger.error("ERROR: exit process....." + e); e.printStackTrace(); System.exit(0); } } } else { logger.warn("Unable to process url: "); } } } int filesRead = loader.load(filePath, args); //FIX ME - move to config long finish = System.currentTimeMillis(); logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes " + ((finish - start) / 1000) + " seconds."); System.exit(1); }
From source file:de.morbz.osmpoispbf.Scanner.java
public static void main(String[] args) { System.out.println("OsmPoisPbf " + VERSION + " started"); // Get input file if (args.length < 1) { System.out.println("Error: Please provide an input file"); System.exit(-1);// ww w. j a v a2 s . c om } String inputFile = args[args.length - 1]; // Get output file String outputFile; int index = inputFile.indexOf('.'); if (index != -1) { outputFile = inputFile.substring(0, index); } else { outputFile = inputFile; } outputFile += ".csv"; // Setup CLI parameters options = new Options(); options.addOption("ff", "filterFile", true, "The file that is used to filter categories"); options.addOption("of", "outputFile", true, "The output CSV file to be written"); options.addOption("rt", "requiredTags", true, "Comma separated list of tags that are required [name]"); options.addOption("ut", "undesiredTags", true, "Comma separated list of tags=value combinations that should be filtered [key=value]"); options.addOption("ot", "outputTags", true, "Comma separated list of tags that are exported [name]"); options.addOption("ph", "printHeader", false, "If flag is set, the `outputTags` are printed as first line in the output file."); options.addOption("r", "relations", false, "Parse relations"); options.addOption("nw", "noWays", false, "Don't parse ways"); options.addOption("nn", "noNodes", false, "Don't parse nodes"); options.addOption("u", "allowUnclosedWays", false, "Allow ways that aren't closed"); options.addOption("d", "decimals", true, "Number of decimal places of coordinates [7]"); options.addOption("s", "separator", true, "Separator character for CSV [|]"); options.addOption("v", "verbose", false, "Print all found POIs"); options.addOption("h", "help", false, "Print this help"); // Parse parameters CommandLine line = null; try { line = (new DefaultParser()).parse(options, args); } catch (ParseException exp) { System.err.println(exp.getMessage()); printHelp(); System.exit(-1); } // Help if (line.hasOption("help")) { printHelp(); System.exit(0); } // Get filter file String filterFile = null; if (line.hasOption("filterFile")) { filterFile = line.getOptionValue("filterFile"); } // Get output file if (line.hasOption("outputFile")) { outputFile = line.getOptionValue("outputFile"); } // Check files if (inputFile.equals(outputFile)) { System.out.println("Error: Input and output files are the same"); System.exit(-1); } File file = new File(inputFile); if (!file.exists()) { System.out.println("Error: Input file doesn't exist"); System.exit(-1); } // Check OSM entity types boolean parseNodes = true; boolean parseWays = true; boolean parseRelations = false; if (line.hasOption("noNodes")) { parseNodes = false; } if (line.hasOption("noWays")) { parseWays = false; } if (line.hasOption("relations")) { parseRelations = true; } // Unclosed ways allowed? if (line.hasOption("allowUnclosedWays")) { onlyClosedWays = false; } // Get CSV separator char separator = '|'; if (line.hasOption("separator")) { String arg = line.getOptionValue("separator"); if (arg.length() != 1) { System.out.println("Error: The CSV separator has to be exactly 1 character"); System.exit(-1); } separator = arg.charAt(0); } Poi.setSeparator(separator); // Set decimals int decimals = 7; // OSM default if (line.hasOption("decimals")) { String arg = line.getOptionValue("decimals"); try { int dec = Integer.valueOf(arg); if (dec < 0) { System.out.println("Error: Decimals must not be less than 0"); System.exit(-1); } else { decimals = dec; } } catch (NumberFormatException ex) { System.out.println("Error: Decimals have to be a number"); System.exit(-1); } } Poi.setDecimals(decimals); // Verbose mode? if (line.hasOption("verbose")) { printPois = true; } // Required tags if (line.hasOption("requiredTags")) { String arg = line.getOptionValue("requiredTags"); requiredTags = arg.split(","); } // Undesired tags if (line.hasOption("undesiredTags")) { String arg = line.getOptionValue("undesiredTags"); undesiredTags = new HashMap<>(); for (String undesired : arg.split(",")) { String[] keyVal = undesired.split("="); if (keyVal.length != 2) { System.out.println("Error: Undesired Tags have to formated like tag=value"); System.exit(-1); } if (!undesiredTags.containsKey(keyVal[0])) { undesiredTags.put(keyVal[0], new HashSet<>(1)); } undesiredTags.get(keyVal[0]).add(keyVal[1]); } } // Output tags if (line.hasOption("outputTags")) { String arg = line.getOptionValue("outputTags"); outputTags = arg.split(","); } // Get filter rules FilterFileParser parser = new FilterFileParser(filterFile); filters = parser.parse(); if (filters == null) { System.exit(-1); } // Setup CSV output try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8")); } catch (IOException e) { System.out.println("Error: Output file error"); System.exit(-1); } // Print Header if (line.hasOption("printHeader")) { String header = "category" + separator + "osm_id" + separator + "lat" + separator + "lon"; for (int i = 0; i < outputTags.length; i++) { header += separator + outputTags[i]; } try { writer.write(header + "\n"); } catch (IOException e) { System.out.println("Error: Output file write error"); System.exit(-1); } } // Setup OSMonaut EntityFilter filter = new EntityFilter(parseNodes, parseWays, parseRelations); Osmonaut naut = new Osmonaut(inputFile, filter, false); // Start watch StopWatch stopWatch = new StopWatch(); stopWatch.start(); // Start OSMonaut String finalSeparator = String.valueOf(separator); naut.scan(new IOsmonautReceiver() { boolean entityNeeded; @Override public boolean needsEntity(EntityType type, Tags tags) { // Are there any tags? if (tags.size() == 0) { return false; } // Check required tags for (String tag : requiredTags) { if (!tags.hasKey(tag)) { return false; } } entityNeeded = getCategory(tags, filters) != null; if (undesiredTags != null && entityNeeded) { for (String key : undesiredTags.keySet()) { if (tags.hasKey(key)) { for (String val : undesiredTags.get(key)) { if (tags.hasKeyValue(key, val)) { return false; } } } } } return entityNeeded; } @Override public void foundEntity(Entity entity) { // Check if way is closed if (onlyClosedWays && entity.getEntityType() == EntityType.WAY) { if (!((Way) entity).isClosed()) { return; } } // Get category Tags tags = entity.getTags(); String cat = getCategory(tags, filters); if (cat == null) { return; } // Get center LatLon center = entity.getCenter(); if (center == null) { return; } // Make OSM-ID String type = ""; switch (entity.getEntityType()) { case NODE: type = "node"; break; case WAY: type = "way"; break; case RELATION: type = "relation"; break; } String id = String.valueOf(entity.getId()); // Make output tags String[] values = new String[outputTags.length]; for (int i = 0; i < outputTags.length; i++) { String key = outputTags[i]; if (tags.hasKey(key)) { values[i] = tags.get(key).replaceAll(finalSeparator, "").replaceAll("\"", ""); } } // Make POI poisFound++; Poi poi = new Poi(values, cat, center, type, id); // Output if (printPois && System.currentTimeMillis() > lastMillis + 40) { printPoisFound(); lastMillis = System.currentTimeMillis(); } // Write to file try { writer.write(poi.toCsv() + "\n"); } catch (IOException e) { System.out.println("Error: Output file write error"); System.exit(-1); } } }); // Close writer try { writer.close(); } catch (IOException e) { System.out.println("Error: Output file close error"); System.exit(-1); } // Output results stopWatch.stop(); printPoisFound(); System.out.println(); System.out.println("Elapsed time in milliseconds: " + stopWatch.getElapsedTime()); // Quit System.exit(0); }
From source file:net.java.sen.tools.MkSenDic.java
/** * Build sen dictionary./*ww w.j a va 2s .com*/ * * @param args * custom dictionary files. see dic/build.xml. */ public static void main(String args[]) { ResourceBundle rb = ResourceBundle.getBundle("dictionary"); DictionaryMaker dm1 = new DictionaryMaker(); DictionaryMaker dm2 = new DictionaryMaker(); DictionaryMaker dm3 = new DictionaryMaker(); // 1st field information of connect file. Vector rule1 = new Vector(); // 2nd field information of connect file. Vector rule2 = new Vector(); // 3rd field information of connect file. Vector rule3 = new Vector(); // 4th field information of connect file. // this field shows cost of morpheme connection // [size3*(x3*size2+x2)+x1] // [size3*(Attr1*size2+Attr2)+Attl] short score[] = new short[20131]; long start = System.currentTimeMillis(); // ///////////////////////////////////////// // // Step1. Loading connetion file. // log.info("(1/7): reading connection matrix ... "); try { log.info("connection file = " + rb.getString("text_connection_file")); log.info("charset = " + rb.getString("dic.charset")); CSVParser csvparser = new CSVParser(new FileInputStream(rb.getString("text_connection_file")), rb.getString("dic.charset")); String t[]; int line = 0; while ((t = csvparser.nextTokens()) != null) { if (t.length < 4) { log.warn("invalid line in " + rb.getString("text_connection_file") + ":" + line); log.warn(rb.getString("text_connection_file") + "may be broken."); break; } dm1.add(t[0]); rule1.add(t[0]); dm2.add(t[1]); rule2.add(t[1]); dm3.add(t[2]); rule3.add(t[2]); if (line == score.length) { score = resize(score); } score[line++] = (short) Integer.parseInt(t[3]); } // ///////////////////////////////////////// // // Step2. Building internal dictionary // log.info("(2/7): building type dictionary ... "); dm1.build(); dm2.build(); dm3.build(); // if you want check specified morpheme, you uncomment and modify // following line: /* * System.out.print("22="); dm3.getById(22); * System.out.print("368="); dm3.getById(368); * * System.out.println(dm3.getDicId("?????*,*,*,*,?")); * DictionaryMaker.debug = true; * System.out.println(dm3.getDicId("?????*,*,*,*,?")); * System.out.println(dm3.getDicIdNoCache("?????*,*,*,*,?")); */ } catch (IOException e) { e.printStackTrace(); System.exit(0); } // ------------------------------------------------- int size1 = dm1.size(); int size2 = dm2.size(); int size3 = dm3.size(); int ruleSize = rule1.size(); short matrix[] = new short[size1 * size2 * size3]; short default_cost = (short) Integer.parseInt(rb.getString("default_connection_cost")); // ///////////////////////////////////////// // // Step3. Writing Connection Matrix // log.info("(3/7): writing conection matrix (" + size1 + " x " + size2 + " x " + size3 + " = " + size1 * size2 * size3 + ") ..."); for (int i = 0; i < (int) (size1 * size2 * size3); i++) matrix[i] = default_cost; for (int i = 0; i < ruleSize; i++) { Vector r1 = dm1.getRuleIdList((String) rule1.get(i)); Vector r2 = dm2.getRuleIdList((String) rule2.get(i)); Vector r3 = dm3.getRuleIdList((String) rule3.get(i)); for (Iterator i1 = r1.iterator(); i1.hasNext();) { int ii1 = ((Integer) i1.next()).intValue(); for (Iterator i2 = r2.iterator(); i2.hasNext();) { int ii2 = ((Integer) i2.next()).intValue(); for (Iterator i3 = r3.iterator(); i3.hasNext();) { int ii3 = ((Integer) i3.next()).intValue(); int pos = size3 * (size2 * ii1 + ii2) + ii3; matrix[pos] = score[i]; } } } } try { DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(rb.getString("matrix_file")))); out.writeShort(size1); out.writeShort(size2); out.writeShort(size3); for (int i1 = 0; i1 < size1; i1++) for (int i2 = 0; i2 < size2; i2++) for (int i3 = 0; i3 < size3; i3++) { out.writeShort(matrix[size3 * (size2 * i1 + i2) + i3]); // if (matrix[size3 * (size2 * i1 + i2) + i3] != // default_cost) { // } } out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(0); } matrix = null; score = null; // ------------------------------------------------- int pos_start = Integer.parseInt(rb.getString("pos_start")); int pos_size = Integer.parseInt(rb.getString("pos_size")); int di = 0; int offset = 0; ArrayList dicList = new ArrayList(); // ///////////////////////////////////////// // // Step4. Reading Morpheme Information // log.info("(4/7): reading morpheme information ... "); String t = null; String[] csv = null; try { // writer for feature file. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(rb.getString("pos_file")), rb.getString("sen.charset"))); log.info("load dic: " + rb.getString("text_dic_file")); BufferedReader dicStream = null; int custom_dic = -1; if (args.length == 0) { dicStream = new BufferedReader(new InputStreamReader( new FileInputStream(rb.getString("text_dic_file")), rb.getString("dic.charset"))); } else { custom_dic = 0; dicStream = new BufferedReader( new InputStreamReader(new FileInputStream(args[custom_dic]), rb.getString("dic.charset"))); } int line = 0; CSVData key_b = new CSVData(); CSVData pos_b = new CSVData(); while (true) { t = dicStream.readLine(); if (t == null) { dicStream.close(); custom_dic++; if (args.length == custom_dic) { break; } else { // read custum dictionary log.info("load dic: " + "args[custum_dic]"); dicStream = new BufferedReader(new InputStreamReader(new FileInputStream(args[custom_dic]), rb.getString("dic.charset"))); } continue; } CSVParser parser = new CSVParser(t); csv = parser.nextTokens(); if (csv.length < (pos_size + pos_start)) { throw new RuntimeException("format error:" + t); } key_b.clear(); pos_b.clear(); for (int i = pos_start; i < (pos_start + pos_size - 1); i++) { key_b.append(csv[i]); pos_b.append(csv[i]); } key_b.append(csv[pos_start + pos_size - 1]); pos_b.append(csv[pos_start + pos_size - 1]); for (int i = pos_start + pos_size; i < (csv.length - 1); i++) { pos_b.append(csv[i]); } pos_b.append(csv[csv.length - 1]); CToken token = new CToken(); token.rcAttr2 = (short) dm1.getDicId(key_b.toString()); token.rcAttr1 = (short) dm2.getDicId(key_b.toString()); token.lcAttr = (short) dm3.getDicId(key_b.toString()); token.posid = 0; token.posID = offset; token.length = (short) csv[0].length(); token.cost = (short) Integer.parseInt(csv[1]); dicList.add(new PairObject(csv[0], token)); byte b[] = pos_b.toString().getBytes(rb.getString("sen.charset")); offset += (b.length + 1); String pos_b_str = pos_b.toString(); bw.write(pos_b_str, 0, pos_b_str.length()); // bw.write(b, 0, b.length); bw.write(0); if (++di % 50000 == 0) log.info("" + di + "... "); } bw.close(); // ----end of writing feature.cha ---- } catch (Exception e) { log.error("Error: " + t); e.printStackTrace(); System.exit(1); } rule1 = null; rule2 = null; rule3 = null; // ///////////////////////////////////////// // // Step5. Sort lexs and write to file // log.info("(5/7): sorting lex... "); int value[] = new int[dicList.size()]; char key[][] = new char[dicList.size()][]; int spos = 0; int dsize = 0; int bsize = 0; String prev = ""; Collections.sort(dicList); // ///////////////////////////////////////// // // Step6. Writing Token Information // log.info("(6/7): writing token... "); try { // writer for token file. DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(rb.getString("token_file")))); // writing 'bos' and 'eos' and 'unknown' token. CToken token = new CToken(); token.rcAttr2 = (short) dm1.getDicId(rb.getString("bos_pos")); token.rcAttr1 = (short) dm2.getDicId(rb.getString("bos_pos")); token.lcAttr = (short) dm3.getDicId(rb.getString("bos_pos")); token.write(out); token.rcAttr2 = (short) dm1.getDicId(rb.getString("eos_pos")); token.rcAttr1 = (short) dm2.getDicId(rb.getString("eos_pos")); token.lcAttr = (short) dm3.getDicId(rb.getString("eos_pos")); token.write(out); token.rcAttr2 = (short) dm1.getDicId(rb.getString("unknown_pos")); token.rcAttr1 = (short) dm2.getDicId(rb.getString("unknown_pos")); token.lcAttr = (short) dm3.getDicId(rb.getString("unknown_pos")); token.posID = -1; token.write(out); log.info("key size = " + key.length); for (int i = 0; i < key.length; i++) { String k = (String) ((PairObject) dicList.get(i)).key; if (!prev.equals(k) && i != 0) { key[dsize] = ((String) ((PairObject) dicList.get(spos)).key).toCharArray(); value[dsize] = bsize + (spos << 8); dsize++; bsize = 1; spos = i; } else { bsize++; } prev = (String) ((PairObject) dicList.get(i)).key; ((CToken) (((PairObject) dicList.get(i)).value)).write(out); } out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } key[dsize] = ((String) ((PairObject) dicList.get(spos)).key).toCharArray(); value[dsize] = bsize + (spos << 8); dsize++; dm1 = null; dm2 = null; dm3 = null; dicList = null; // ///////////////////////////////////////// // // Step7. Build Double Array // log.info("(7/7): building Double-Array (size = " + dsize + ") ..."); DoubleArrayTrie da = new DoubleArrayTrie(); da.build(key, null, value, dsize); try { da.save(rb.getString("double_array_file")); } catch (Exception e) { e.printStackTrace(); } log.info("total time = " + (System.currentTimeMillis() - start) / 1000 + "[ms]"); }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
public static void main(String[] args) { String name = "T.class"; System.out.println(name.substring(0, name.length() - 6)); }
From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java
public static void main(String[] args) { // create the parser CommandLineParser parser = new PosixParser(); CommandLine line = null;//from ww w. j av a 2 s.c om Options options = getOptions(); try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("RmiIndexerStub -h <hostName> -p <basePort> [options] ", options); System.exit(1); } boolean doOptimize = line.hasOption("optimize"); boolean doCheckpoint = line.hasOption("checkpoint"); boolean doStop = line.hasOption("stop"); Integer port = ((Long) line.getOptionObject("port")).intValue(); String host = line.getOptionValue("host"); try { RmiIndexerStub stub = new RmiIndexerStub(port, host); if (line.hasOption("deleteUrl")) { String url = line.getOptionValue("deleteUrl"); Document dom = generateDeleteDocument(url); indexOrFail(stub, dom, "Could not delete " + url); System.out.println("delete " + url + " command accepted by indexer"); } if (line.hasOption("deleteFile")) { BufferedReader reader = new BufferedReader(new FileReader(line.getOptionValue("deleteFile"))); while (reader.ready()) { String url = reader.readLine(); if (url.length() > 0 && url.charAt(0) != '#') { // ignore empty lines and comments Document dom = generateDeleteDocument(url); indexOrFail(stub, dom, "Could not delete " + url); System.out.println("delete " + url + " command accepted by indexer"); } } reader.close(); } if (doOptimize) { Document dom = generateCommandDocument("optimize"); indexOrFail(stub, dom, "Could not send optimize command."); System.out.println("optimize command accepted by indexer"); } if (doCheckpoint) { Document dom = generateCommandDocument("checkpoint"); indexOrFail(stub, dom, "Could not send checkpoint command."); System.out.println("checkpoint command accepted by indexer"); } if (doStop) { Document dom = generateCommandDocument("close"); indexOrFail(stub, dom, "Could not send stop command."); System.out.println("stop command accepted by indexer"); } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } }
From source file:net.itransformers.idiscover.discoverylisteners.TopologyDeviceLogger.java
public static void main(String[] args) throws FileNotFoundException, JAXBException { String path = "tmp1"; File dir = new File(path); String[] files = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.startsWith("device") && name.endsWith(".xml")); }/*from w w w . j a v a 2 s . co m*/ }); TopologyDeviceLogger logger = new TopologyDeviceLogger(path); String host = "10.33.0.5"; String snmpROComm = "public"; Map<String, String> resourceParams = new HashMap<String, String>(); resourceParams.put("community", snmpROComm); resourceParams.put("version", "1"); Resource resource = new Resource(host, null, resourceParams); for (String fileName : files) { FileInputStream is = new FileInputStream(path + File.separator + fileName); DiscoveredDeviceData discoveredDeviceData = null; try { discoveredDeviceData = JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } String deviceName = fileName.substring("device-".length(), fileName.length() - ".xml".length()); logger.handleDevice(deviceName, null, discoveredDeviceData, resource); } }
From source file:ExecSQL.java
public static void main(String args[]) { try {/*from www.j a v a 2 s. c om*/ Scanner in; if (args.length == 0) in = new Scanner(System.in); else in = new Scanner(new File(args[0])); Connection conn = getConnection(); try { Statement stat = conn.createStatement(); while (true) { if (args.length == 0) System.out.println("Enter command or EXIT to exit:"); if (!in.hasNextLine()) return; String line = in.nextLine(); if (line.equalsIgnoreCase("EXIT")) return; if (line.trim().endsWith(";")) // remove trailing semicolon { line = line.trim(); line = line.substring(0, line.length() - 1); } try { boolean hasResultSet = stat.execute(line); if (hasResultSet) showResultSet(stat); } catch (SQLException ex) { for (Throwable e : ex) e.printStackTrace(); } } } finally { conn.close(); } } catch (SQLException e) { for (Throwable t : e) t.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:edu.msu.cme.rdp.readseq.utils.QualityTrimmer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("f", "fastq-out", false, "Write fastq instead of fasta file"); options.addOption("l", "less-than", false, "Trim at <= instead of strictly ="); options.addOption("i", "illumina", false, "Illumina trimming mode"); FastqWriter fastqOut = null;//from w w w. j a v a 2 s. c om FastaWriter fastaOut = null; byte qualTrim = -1; boolean writeFasta = true; boolean trimle = false; boolean illumina = false; List<SeqReader> readers = new ArrayList(); List<File> seqFiles = new ArrayList(); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("fastq-out")) { writeFasta = false; } if (line.hasOption("less-than")) { trimle = true; } if (line.hasOption("illumina")) { illumina = true; } args = line.getArgs(); if (args.length < 2) { throw new Exception("Unexpected number of arguments"); } if (args[0].length() != 1) { throw new Exception("Expected single character quality score"); } qualTrim = FastqCore.Phred33QualFunction.translate(args[0].charAt(0)); for (int index = 1; index < args.length; index++) { File seqFile = new File(args[index]); SeqReader reader; if (SeqUtils.guessFileFormat(seqFile) == SequenceFormat.FASTA) { if (index + 1 == args.length) { throw new Exception("Fasta files must be immediately followed by their quality file"); } File qualFile = new File(args[index + 1]); if (SeqUtils.guessFileFormat(qualFile) != SequenceFormat.FASTA) { throw new Exception(seqFile + " was not followed by a fasta quality file"); } reader = new QSeqReader(seqFile, qualFile); index++; } else { if (seqFile.getName().endsWith(".gz")) { reader = new SequenceReader(new GZIPInputStream(new FileInputStream(seqFile))); } else { reader = new SequenceReader(seqFile); } } readers.add(reader); seqFiles.add(seqFile); } } catch (Exception e) { new HelpFormatter().printHelp("USAGE: QualityTrimmer [options] <ascii_score> <seq_file> [qual_file]", options, true); System.err.println("Error: " + e.getMessage()); System.exit(1); } for (int readerIndex = 0; readerIndex < readers.size(); readerIndex++) { File seqFile = seqFiles.get(readerIndex); String outStem = "trimmed_" + seqFile.getName().substring(0, seqFile.getName().lastIndexOf(".")); if (writeFasta) { fastaOut = new FastaWriter(outStem + ".fasta"); } else { fastqOut = new FastqWriter(outStem + ".fastq", FastqCore.Phred33QualFunction); } int[] lengthHisto = new int[200]; SeqReader reader = readers.get(readerIndex); QSequence qseq; long totalLength = 0; int totalSeqs = 0; long trimmedLength = 0; int trimmedSeqs = 0; int zeroLengthAfterTrimming = 0; long startTime = System.currentTimeMillis(); while ((qseq = (QSequence) reader.readNextSequence()) != null) { char[] bases = qseq.getSeqString().toCharArray(); byte[] qual = qseq.getQuality(); if (bases.length != qual.length) { System.err.println(qseq.getSeqName() + ": Quality length doesn't match seq length for seq"); continue; } totalSeqs++; totalLength += bases.length; int trimIndex = -1; if (illumina && qual[bases.length - 1] == qualTrim) { trimIndex = bases.length - 1; while (trimIndex >= 0 && qual[trimIndex] == qualTrim) { trimIndex--; } trimIndex++; //Technically we're positioned over the first good base, move back to the last bad base } else if (!illumina) { for (int index = 0; index < bases.length; index++) { if (qual[index] == qualTrim || (trimle && qual[index] < qualTrim)) { trimIndex = index; break; } } } String outSeq; byte[] outQual; if (trimIndex == -1) { outSeq = qseq.getSeqString(); outQual = qseq.getQuality(); } else { outSeq = new String(bases, 0, trimIndex); outQual = Arrays.copyOfRange(qual, 0, trimIndex); trimmedSeqs++; } int len = outSeq.length(); trimmedLength += len; if (len >= lengthHisto.length) { lengthHisto = Arrays.copyOf(lengthHisto, len + 1); } lengthHisto[len]++; if (outSeq.length() == 0) { //System.err.println(qseq.getSeqName() + ": length 0 after trimming"); zeroLengthAfterTrimming++; continue; } if (writeFasta) { fastaOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq); } else { fastqOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq, outQual); } } reader.close(); if (writeFasta) { fastaOut.close(); } else { fastqOut.close(); } System.out.println( "Processed " + seqFile + " in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s"); System.out.println("Before trimming:"); System.out.println("Total Sequences: " + totalSeqs); System.out.println("Total Sequence Data: " + totalLength); System.out.println("Average sequence length: " + ((float) totalLength / totalSeqs)); System.out.println(); System.out.println("After trimming:"); System.out.println("Total Sequences: " + (totalSeqs - zeroLengthAfterTrimming)); System.out.println("Sequences Trimmed: " + trimmedSeqs); System.out.println("Total Sequence Data: " + trimmedLength); System.out.println("Average sequence length: " + ((float) trimmedLength / (totalSeqs - zeroLengthAfterTrimming))); System.out.println(); System.out.println("Length\tCount"); for (int index = 0; index < lengthHisto.length; index++) { if (lengthHisto[index] == 0) { continue; } System.out.println(index + "\t" + lengthHisto[index]); } System.out.println(); System.out.println(); System.out.println(); } }
From source file:org.apache.http.examples.client.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); // DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); try {/*from w w w . j a v a2s.co m*/ // HttpGet httpget = new HttpGet("http://localhost/"); HttpGet httpget = new HttpGet( "http://api.map.baidu.com/geocoder/v2/?address=&output=json&ak=E4805d16520de693a3fe707cdc962045&callback=showLocation"); // httpget.setHeader("Accept", "180.97.33.90:80"); httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch"); httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8"); httpget.setHeader("Cache-Control", "no-cache"); httpget.setHeader("Connection", "keep-alive"); httpget.setHeader("Referer", "http://developer.baidu.com/map/index.php?title=webapi/guide/changeposition"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"); System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, "utf-8") : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); //showLocation&&showLocation({"status":0,"result":{"location":{"lng":112.25009284837,"lat":32.229168591538},"precise":0,"confidence":14,"level":"\u533a\u53bf"}}) System.out.println("----------------------------------------"); ObjectMapper mapper = new ObjectMapper(); // mapper.readValue(responseBody, AddressCoord.class); JsonNode root = mapper.readTree( responseBody.substring("showLocation&&showLocation(".length(), responseBody.length() - 1)); // String name = root.get("name").asText(); // int age = root.get("age").asInt(); String status = root.get("status").asText(); String lng = root.with("result").with("location").get("lng").asText(); String lat = root.with("result").with("location").get("lat").asText(); String level = root.with("result").get("level").asText(); System.out.println(String.format("'%1$s': [%2$s, %3$s], status: %4$s", level, lng, lat, status)); } finally { httpclient.close(); } }