List of usage examples for java.lang String split
public String[] split(String regex)
From source file:com.intuit.tank.standalone.agent.StandaloneAgentStartup.java
public static void main(String[] args) { StandaloneAgentStartup agentStartup = new StandaloneAgentStartup(); for (int iter = 0; iter < args.length; ++iter) { String argument = args[iter]; String[] values = argument.split("="); if (values[0].equalsIgnoreCase("-controller")) { if (values.length < 2) { usage();// w w w.j a v a 2 s . c o m return; } agentStartup.controllerBase = values[1]; continue; } else if (values[0].equalsIgnoreCase("-host")) { if (values.length < 2) { usage(); return; } agentStartup.hostname = values[1]; continue; } else if (values[0].equalsIgnoreCase("-capacity")) { if (values.length < 2) { usage(); return; } try { agentStartup.capacity = Integer.parseInt(values[1]); } catch (NumberFormatException e) { LOG.error("Error parsing capacity " + values[1] + " Capacity must be an integer."); System.out.println("Error parsing capacity " + values[1] + " Capacity must be an integer."); usage(); return; } continue; } } if (StringUtils.isBlank(agentStartup.controllerBase)) { usage(); System.exit(1); } agentStartup.run(); }
From source file:org.nmdp.b12s.mac.client.http.X509Config.java
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException { URL trustKeyStoreUrl = X509Config.class.getResource("/trusted.jks"); URL clientKeyStoreUri = X509Config.class.getResource("/test-client.jks"); SSLContext sslContext = SSLContexts.custom() // Configure trusted certs .loadTrustMaterial(trustKeyStoreUrl, "changeit".toCharArray()) // Configure client certificate .loadKeyMaterial(clientKeyStoreUri, "changeit".toCharArray(), "changeit".toCharArray()).build(); try (TextHttpClient httpClient = new TextHttpClient("https://macbeta.b12x.org/mac/api", sslContext)) { }//from w w w . ja v a2 s .co m // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) { HttpGet httpget = new HttpGet("https://macbeta.b12x.org/mac/api/codes/AA"); System.out.println("executing request " + httpget.getRequestLine()); try (CloseableHttpResponse response = httpclient.execute(httpget)) { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { Charset charset = StandardCharsets.UTF_8; for (Header contentType : response.getHeaders("Content-Type")) { System.out.println("Content-Type: " + contentType); for (String part : contentType.getValue().split(";")) { if (part.startsWith("charset=")) { String charsetName = part.split("=")[1]; charset = Charset.forName(charsetName); } } } System.out.println("Response content length: " + entity.getContentLength()); String content = EntityUtils.toString(entity, charset); System.out.println(content); } EntityUtils.consume(entity); } } }
From source file:gov.lanl.adore.djatoka.DjatokaExtract.java
/** * Uses apache commons cli to parse input args. Passes parsed * parameters to IExtract implementation. * @param args command line parameters to defined input,output,etc. *///from w w w. j a v a 2 s . c o m public static void main(String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("i", "input", true, "Filepath of the input file."); options.addOption("o", "output", true, "Filepath of the output file."); options.addOption("l", "level", true, "Resolution level to extract."); options.addOption("d", "reduce", true, "Resolution levels to subtract from max resolution."); options.addOption("r", "region", true, "Format: Y,X,H,W. "); options.addOption("c", "cLayer", true, "Compositing Layer Index."); options.addOption("s", "scale", true, "Format: Option 1. Define a long-side dimension (e.g. 96); Option 2. Define absolute w,h values (e.g. 1024,768); Option 3. Define a single dimension (e.g. 1024,0) with or without Level Parameter; Option 4. Use a single decimal scaling factor (e.g. 0.854)"); options.addOption("t", "rotate", true, "Number of degrees to rotate image (i.e. 90, 180, 270)."); options.addOption("f", "format", true, "Mimetype of the image format to be provided as response. Default: image/jpeg"); options.addOption("a", "AltImpl", true, "Alternate IExtract Implemenation"); try { if (args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gov.lanl.adore.djatoka.DjatokaExtract", options); System.exit(0); } // parse the command line arguments CommandLine line = parser.parse(options, args); String input = line.getOptionValue("i"); String output = line.getOptionValue("o"); DjatokaDecodeParam p = new DjatokaDecodeParam(); String level = line.getOptionValue("l"); if (level != null) p.setLevel(Integer.parseInt(level)); String reduce = line.getOptionValue("d"); if (level == null && reduce != null) p.setLevelReductionFactor(Integer.parseInt(reduce)); String region = line.getOptionValue("r"); if (region != null) p.setRegion(region); String cl = line.getOptionValue("c"); if (cl != null) { int clayer = Integer.parseInt(cl); if (clayer > 0) p.setCompositingLayer(clayer); } String scale = line.getOptionValue("s"); if (scale != null) { String[] v = scale.split(","); if (v.length == 1) { if (v[0].contains(".")) p.setScalingFactor(Double.parseDouble(v[0])); else { int[] dims = new int[] { -1, Integer.parseInt(v[0]) }; p.setScalingDimensions(dims); } } else if (v.length == 2) { int[] dims = new int[] { Integer.parseInt(v[0]), Integer.parseInt(v[1]) }; p.setScalingDimensions(dims); } } String rotate = line.getOptionValue("t"); if (rotate != null) p.setRotationDegree(Integer.parseInt(rotate)); String format = line.getOptionValue("f"); if (format == null) format = "image/jpeg"; String alt = line.getOptionValue("a"); if (output == null) output = input + ".jpg"; long x = System.currentTimeMillis(); IExtract ex = new KduExtractExe(); if (alt != null) ex = (IExtract) Class.forName(alt).newInstance(); DjatokaExtractProcessor e = new DjatokaExtractProcessor(ex); e.extractImage(input, output, p, format); logger.info("Extraction Time: " + ((double) (System.currentTimeMillis() - x) / 1000) + " seconds"); } catch (ParseException e) { logger.error("Parse exception:" + e.getMessage(), e); } catch (DjatokaException e) { logger.error("djatoka Extraction exception:" + e.getMessage(), e); } catch (InstantiationException e) { logger.error("Unable to initialize alternate implemenation:" + e.getMessage(), e); } catch (Exception e) { logger.error("Unexpected exception:" + e.getMessage(), e); } }
From source file:cz.muni.fi.crocs.EduHoc.Main.java
/** * @param args the command line arguments */// ww w. ja va 2s . c o m public static void main(String[] args) { System.out.println("JeeTool \n"); Options options = OptionsMain.createOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException ex) { System.err.println("cannot parse parameters"); OptionsMain.printHelp(options); System.err.println(ex.toString()); return; } boolean silent = cmd.hasOption("s"); boolean verbose = cmd.hasOption("v"); if (!silent) { System.out.println(ANSI_GREEN + "EduHoc home is: " + System.getenv("EDU_HOC_HOME") + "\n" + ANSI_RESET); } //help if (cmd.hasOption("h")) { OptionsMain.printHelp(options); return; } String filepath; //path to config list of nodes if (cmd.hasOption("a")) { filepath = cmd.getOptionValue("a"); } else { filepath = System.getenv("EDU_HOC_HOME") + "/config/motePaths.txt"; } //create motelist MoteList moteList = new MoteList(filepath); if (verbose) { moteList.setVerbose(); } if (silent) { moteList.setSilent(); } if (verbose) { System.out.println("reading motelist from file " + filepath); } if (cmd.hasOption("i")) { List<Integer> ids = new ArrayList<Integer>(); String arg = cmd.getOptionValue("i"); String[] IdArgs = arg.split(","); for (String s : IdArgs) { if (s.contains("-")) { int start = Integer.parseInt(s.substring(0, s.indexOf("-"))); int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length())); for (int i = start; i <= end; i++) { ids.add(i); } } else { ids.add(Integer.parseInt(s)); } } moteList.setIds(ids); } moteList.readFile(); if (cmd.hasOption("d")) { //only detect nodes return; } //if make if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) { UploadMain upload = new UploadMain(moteList, cmd); upload.runMake(); } //if execute command if (cmd.hasOption("E")) { try { ExecuteShellCommand com = new ExecuteShellCommand(); if (verbose) { System.out.println("Executing shell command " + cmd.getOptionValue("E")); } com.executeCommand(cmd.getOptionValue("E")); } catch (IOException ex) { System.err.println("Execute command " + cmd.getOptionValue("E") + " failed"); } } //if serial if (cmd.hasOption("l") || cmd.hasOption("w")) { SerialMain serial = new SerialMain(cmd, moteList); if (silent) { serial.setSilent(); } if (verbose) { serial.setVerbose(); } serial.startSerial(); } }
From source file:com.wipro.ats.bdre.dq.DQMain.java
/** * @param args//w ww. ja v a 2 s . c o m * @throws Exception */ public static void main(String[] args) throws Exception { CommandLine commandLine = new DQMain().getCommandLine(args, PARAMS_STRUCTURE); String processId = commandLine.getOptionValue("process-id"); String sPath = commandLine.getOptionValue("source-file-path"); String destDir = commandLine.getOptionValue("destination-directory"); int result = 0; if (sPath.indexOf(';') != -1 || sPath.indexOf(',') != -1) { String[] lof = sPath.split(";"); String[] entries = lof[0].split(","); String[] params = { processId, entries[2], destDir }; result = ToolRunner.run(new Configuration(), new DQDriver(), params); } else { String[] params = { processId, sPath, destDir }; result = ToolRunner.run(new Configuration(), new DQDriver(), params); } if (result != 0) throw new DQValidationException(new DQStats()); }
From source file:zz.pseas.ghost.login.taobao.MTaobaoLogin.java
public static void main(String[] args) throws UnsupportedEncodingException { String tbuserNmae = "TBname"; String tbpassWord = "TBpasssword"; GhostClient iPhone = new GhostClient("utf-8"); String ans = iPhone.get("https://login.m.taobao.com/login.htm"); Document doc = Jsoup.parse(ans); String url = doc.select("form#loginForm").first().attr("action"); String _tb_token = doc.select("input[name=_tb_token_]").first().attr("value"); String sid = doc.select("input[name=sid]").first().attr("value"); System.out.println(_tb_token); System.out.println(sid);//from w w w . j a v a 2s.c o m System.out.println(url); HashMap<String, String> map = new HashMap<String, String>(); map.put("TPL_password", tbpassWord); map.put("TPL_username", tbuserNmae); map.put("_tb_token_", _tb_token); map.put("action", "LoginAction"); map.put("event_submit_do_login", "1"); map.put("loginFrom", "WAP_TAOBAO"); map.put("sid", sid); String location = null; while (true) { CommonsPage commonsPage = iPhone.postForPage(url, map); location = commonsPage.getHeader("Location"); String postAns = new String(commonsPage.getContents(), "utf-8"); if (StringUtil.isNotEmpty(location) && StringUtil.isEmpty(postAns)) { break; } String s = Jsoup.parse(postAns).select("img.checkcode-img").first().attr("src"); String imgUrl = "https:" + s; byte[] bytes = iPhone.getBytes(imgUrl); FileUtil.writeFile(bytes, "g:/tbCaptcha.jpg"); String wepCheckId = Jsoup.parse(postAns).select("input[name=wapCheckId]").val(); String captcha = null; map.put("TPL_checkcode", captcha); map.put("wapCheckId", wepCheckId); } iPhone.get(location); String tk = iPhone.getCookieValue("_m_h5_tk"); if (StringUtil.isNotEmpty(tk)) { tk = tk.split("_")[0]; } else { tk = "undefined"; } String url2 = genUrl(tk); String ans1 = iPhone.get(url2); System.out.println(url2); System.out.println(ans1); tk = iPhone.getCookieValue("_m_h5_tk").split("_")[0]; if (StringUtil.isEmpty(tk)) { tk = "undefined"; } System.out.println(tk); url2 = genUrl(tk); iPhone.showCookies(); RequestConfig requestConfig = RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8888)).build(); HttpUriRequest get = RequestBuilder.get().setConfig(requestConfig) //.addHeader("User-Agent","Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16") .addHeader("Host", "api.m.taobao.com").setUri(url2).build(); ans1 = iPhone.execute(get); System.out.println(ans1); }
From source file:de.zib.vold.userInterface.ABI.java
public static void main(String[] args) { ABI abi = new ABI(); while (true) { try {/* w w w.jav a2 s. c om*/ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.print("#: "); String s = br.readLine(); if (null == s) break; String[] a = s.split("\\s+"); if (a.length < 1) { System.out.println("ERROR: The following commands are valid:"); System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*"); System.out.println("ERROR: lookup <scope> <type> <keyname>"); System.out.println("ERROR: exit"); continue; } else if (a[0].equals("lookup") || a[0].equals("l")) { if (a.length < 4) { System.out.println("ERROR: Syntax for lookup is:"); System.out.println("ERROR: lookup <scope> <type> <keyname>"); continue; } Map<Key, Set<String>> result; try { result = abi.frontend.lookup(new Key(a[1], a[2], a[3])); } catch (VoldException e) { System.out.println( "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage()); continue; } for (Map.Entry<Key, Set<String>> entry : result.entrySet()) { Key k = entry.getKey(); System.out.println("+Found ('" + k.get_scope() + "', '" + k.get_type() + "', '" + k.get_keyname() + "')"); for (String v : entry.getValue()) { System.out.println("-" + v); } } } else if (a[0].equals("insert") || a[0].equals("i")) { if (a.length < 5) { System.out.println("ERROR: Syntax for insert is:"); System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*"); continue; } Key k = new Key(a[2], a[3], a[4]); Set<String> values = new HashSet<String>(); for (int i = 5; i < a.length; ++i) { values.add(a[i]); } try { abi.frontend.insert(a[1], k, values, DateTime.now().getMillis()); } catch (VoldException e) { System.out.println( "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage()); continue; } } else if (a[0].equals("exit") || a[0].equals("x")) { break; } else { System.out.println("ERROR: Unknown command!"); System.out.println("ERROR: The following commands are valid:"); System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*"); System.out.println("ERROR: lookup <scope> <type> <keyname>"); System.out.println("ERROR: exit"); } } catch (IOException e) { e.printStackTrace(); } } System.exit(0); }
From source file:backtype.storm.command.gray_upgrade.java
public static void main(String[] args) throws Exception { if (args == null || args.length < 1) { System.out.println("Invalid parameter"); usage();//from www.ja v a2 s . c o m return; } String topologyName = args[0]; String[] str2 = Arrays.copyOfRange(args, 1, args.length); CommandLineParser parser = new GnuParser(); Options r = buildGeneralOptions(new Options()); CommandLine commandLine = parser.parse(r, str2, true); int workerNum = 0; String component = null; List<String> workers = null; if (commandLine.hasOption("n")) { workerNum = Integer.valueOf(commandLine.getOptionValue("n")); } if (commandLine.hasOption("p")) { component = commandLine.getOptionValue("p"); } if (commandLine.hasOption("w")) { String w = commandLine.getOptionValue("w"); if (!StringUtils.isBlank(w)) { workers = Lists.newArrayList(); String[] parts = w.split(","); for (String part : parts) { if (part.split(":").length == 2) { workers.add(part.trim()); } } } } upgradeTopology(topologyName, component, workers, workerNum); }
From source file:com.metamx.druid.utils.ExposeS3DataSource.java
public static void main(String[] args) throws ServiceException, IOException, NoSuchAlgorithmException { CLI cli = new CLI(); cli.addOption(new RequiredOption(null, "s3Bucket", true, "s3 bucket to pull data from")); cli.addOption(new RequiredOption(null, "s3Path", true, "base input path in s3 bucket. Everything until the date strings.")); cli.addOption(new RequiredOption(null, "timeInterval", true, "ISO8601 interval of dates to index")); cli.addOption(new RequiredOption(null, "granularity", true, String.format( "granularity of index, supported granularities: [%s]", Arrays.asList(Granularity.values())))); cli.addOption(new RequiredOption(null, "zkCluster", true, "Cluster string to connect to ZK with.")); cli.addOption(new RequiredOption(null, "zkBasePath", true, "The base path to register index changes to.")); CommandLine commandLine = cli.parse(args); if (commandLine == null) { return;/*from w w w .ja v a 2 s . c om*/ } String s3Bucket = commandLine.getOptionValue("s3Bucket"); String s3Path = commandLine.getOptionValue("s3Path"); String timeIntervalString = commandLine.getOptionValue("timeInterval"); String granularity = commandLine.getOptionValue("granularity"); String zkCluster = commandLine.getOptionValue("zkCluster"); String zkBasePath = commandLine.getOptionValue("zkBasePath"); Interval timeInterval = new Interval(timeIntervalString); Granularity gran = Granularity.valueOf(granularity.toUpperCase()); final RestS3Service s3Client = new RestS3Service(new AWSCredentials( System.getProperty("com.metamx.aws.accessKey"), System.getProperty("com.metamx.aws.secretKey"))); ZkClient zkClient = new ZkClient(new ZkConnection(zkCluster), Integer.MAX_VALUE, new StringZkSerializer()); zkClient.waitUntilConnected(); for (Interval interval : gran.getIterable(timeInterval)) { log.info("Processing interval[%s]", interval); String s3DatePath = JOINER.join(s3Path, gran.toPath(interval.getStart())); if (!s3DatePath.endsWith("/")) { s3DatePath += "/"; } StorageObjectsChunk chunk = s3Client.listObjectsChunked(s3Bucket, s3DatePath, "/", 2000, null, true); TreeSet<String> commonPrefixes = Sets.newTreeSet(); commonPrefixes.addAll(Arrays.asList(chunk.getCommonPrefixes())); if (commonPrefixes.isEmpty()) { log.info("Nothing at s3://%s/%s", s3Bucket, s3DatePath); continue; } String latestPrefix = commonPrefixes.last(); log.info("Latest segments at [s3://%s/%s]", s3Bucket, latestPrefix); chunk = s3Client.listObjectsChunked(s3Bucket, latestPrefix, "/", 2000, null, true); Integer partitionNumber; if (chunk.getCommonPrefixes().length == 0) { partitionNumber = null; } else { partitionNumber = -1; for (String partitionPrefix : chunk.getCommonPrefixes()) { String[] splits = partitionPrefix.split("/"); partitionNumber = Math.max(partitionNumber, Integer.parseInt(splits[splits.length - 1])); } } log.info("Highest segment partition[%,d]", partitionNumber); if (partitionNumber == null) { final S3Object s3Obj = new S3Object(new S3Bucket(s3Bucket), String.format("%sdescriptor.json", latestPrefix)); updateWithS3Object(zkBasePath, s3Client, zkClient, s3Obj); } else { for (int i = partitionNumber; i >= 0; --i) { final S3Object partitionObject = new S3Object(new S3Bucket(s3Bucket), String.format("%s%s/descriptor.json", latestPrefix, i)); updateWithS3Object(zkBasePath, s3Client, zkClient, partitionObject); } } } }
From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {//w w w . j a v a 2 s.c o m httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); HttpHost targetHost = new HttpHost("pt.3g.qq.com"); HttpHost proxy = new HttpHost("133.13.162.149", 8080); BasicClientCookie netscapeCookie = null; httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // httpclient.getCookieStore().addCookie(netscapeCookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpGet httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("via proxy: " + proxy); System.out.println("to target: " + targetHost); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = entity.getContent(); StringBuffer sb = new StringBuffer(200); byte data[] = new byte[65536]; int n = 1; do { n = is.read(data); if (n > 0) { sb.append(new String(data)); } } while (n > 0); // System.out.println(sb); EntityUtils.consume(entity); System.out.println("----------------------------------------"); Header[] headerlist = response.getAllHeaders(); for (int i = 0; i < headerlist.length; i++) { Header header = headerlist[i]; if (header.getName().equals("Set-Cookie")) { String setCookie = header.getValue(); String cookies[] = setCookie.split(";"); for (int j = 0; j < cookies.length; j++) { String cookie[] = cookies[j].split("="); CookieManager.cookie.put(cookie[0], cookie[1]); } } System.out.println(header.getName() + ":" + header.getValue()); } String sid = getSid(sb.toString(), "&"); System.out.println("sid: " + sid); httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); String url = Constant.openUrl + "&" + sid; targetHost = new HttpHost(url); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); Iterator it = CookieManager.cookie.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); netscapeCookie = new BasicClientCookie((String) (key), (String) (value)); netscapeCookie.setVersion(0); netscapeCookie.setDomain(".qq.com"); netscapeCookie.setPath("/"); // httpclient.getCookieStore().addCookie(netscapeCookie); } response = httpclient.execute(targetHost, httpget); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }