List of usage examples for java.util List get
E get(int index);
From source file:eu.fbk.utils.lsa.util.Anvur.java
public static void main(String[] args) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "log-config.txt"; }/* w w w . j a va 2 s.co m*/ PropertyConfigurator.configure(logConfig); /* if (args.length != 2) { log.println("Usage: java -mx512M eu.fbk.utils.lsa.util.Anvur in-file out-dir"); System.exit(1); } File l = new File(args[1]); if (!l.exists()) { l.mkdir(); } List<String[]> list = readText(new File(args[0])); String oldCategory = ""; for (int i=0;i<list.size();i++) { String[] s = list.get(i); if (!oldCategory.equals(s[0])) { File f = new File(args[1] + File.separator + s[0]); boolean b = f.mkdir(); logger.debug(f + " created " + b); } File g = new File(args[1] + File.separator + s[0] + File.separator + s[1] + ".txt"); logger.debug("writing " + g + "..."); PrintWriter pw = new PrintWriter(new FileWriter(g)); //pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2])); if (s.length == 5) { pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2] + " " + s[4].replace('_', ' '))); } else { pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2])); } pw.flush(); pw.close(); } // end for i */ if (args.length != 7) { System.out.println(args.length); System.out.println( "Usage: java -mx2G eu.fbk.utils.lsa.util.Anvur input threshold size dim idf in-file-csv fields\n\n"); System.exit(1); } // DecimalFormat dec = new DecimalFormat("#.00"); File Ut = new File(args[0] + "-Ut"); File Sk = new File(args[0] + "-S"); File r = new File(args[0] + "-row"); File c = new File(args[0] + "-col"); File df = new File(args[0] + "-df"); double threshold = Double.parseDouble(args[1]); int size = Integer.parseInt(args[2]); int dim = Integer.parseInt(args[3]); boolean rescaleIdf = Boolean.parseBoolean(args[4]); //"author_check"0, "authors"1, "title"2, "year"3, "pubtype"4, "publisher"5, "journal"6, "volume"7, "number"8, "pages"9, "abstract"10, "nauthors", "citedby" String[] labels = { "author_check", "authors", "title", "year", "pubtype", "publisher", "journal", "volume", "number", "pages", "abstract", "nauthors", "citedby" //author_id authors title year pubtype publisher journal volume number pages abstract nauthors citedby }; String name = buildName(labels, args[6]); File bwf = new File(args[5] + name + "-bow.txt"); PrintWriter bw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bwf), "UTF-8"))); File bdf = new File(args[5] + name + "-bow.csv"); PrintWriter bd = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bdf), "UTF-8"))); File lwf = new File(args[5] + name + "-ls.txt"); PrintWriter lw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lwf), "UTF-8"))); File ldf = new File(args[5] + name + "-ls.csv"); PrintWriter ld = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ldf), "UTF-8"))); File blwf = new File(args[5] + name + "-bow+ls.txt"); PrintWriter blw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(blwf), "UTF-8"))); File bldf = new File(args[5] + name + "-bow+ls.csv"); PrintWriter bld = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bldf), "UTF-8"))); File logf = new File(args[5] + name + ".log"); PrintWriter log = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logf), "UTF-8"))); //System.exit(0); LSM lsm = new LSM(Ut, Sk, r, c, df, dim, rescaleIdf); LSSimilarity lss = new LSSimilarity(lsm, size); List<String[]> list = readText(new File(args[5])); // author_check authors title year pubtype publisher journal volume number pages abstract nauthors citedby //header for (int i = 0; i < list.size(); i++) { String[] s1 = list.get(i); String t1 = s1[0].toLowerCase(); bw.print("\t"); lw.print("\t"); blw.print("\t"); bw.print(i + "(" + s1[0] + ")"); lw.print(i + "(" + s1[0] + ")"); blw.print(i + "(" + s1[0] + ")"); } // end for i bw.print("\n"); lw.print("\n"); blw.print("\n"); for (int i = 0; i < list.size(); i++) { logger.info(i + "\t"); String[] s1 = list.get(i); String t1 = buildText(s1, args[6]); BOW bow1 = new BOW(t1); logger.info(bow1); Vector d1 = lsm.mapDocument(bow1); d1.normalize(); log.println("d1:" + d1); Vector pd1 = lsm.mapPseudoDocument(d1); pd1.normalize(); log.println("pd1:" + pd1); Vector m1 = merge(pd1, d1); log.println("m1:" + m1); // write the orginal line for (int j = 0; j < s1.length; j++) { bd.print(s1[j]); bd.print("\t"); ld.print(s1[j]); ld.print("\t"); bld.print(s1[j]); bld.print("\t"); } // write the bow, ls, and bow+ls vectors bd.println(d1); ld.println(pd1); bld.println(m1); bw.print(i + "(" + s1[0] + ")"); lw.print(i + "(" + s1[0] + ")"); blw.print(i + "(" + s1[0] + ")"); for (int j = 0; j < i + 1; j++) { bw.print("\t"); lw.print("\t"); blw.print("\t"); } // end for j for (int j = i + 1; j < list.size(); j++) { logger.info(i + "\t" + j); String[] s2 = list.get(j); String t2 = buildText(s2, args[6]); BOW bow2 = new BOW(t2); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t1:" + t1); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t2:" + t2); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow1:" + bow1); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow2:" + bow2); Vector d2 = lsm.mapDocument(bow2); d2.normalize(); log.println("d2:" + d2); Vector pd2 = lsm.mapPseudoDocument(d2); pd2.normalize(); log.println("pd2:" + pd2); Vector m2 = merge(pd2, d2); log.println("m2:" + m2); float cosVSM = d1.dotProduct(d2) / (float) Math.sqrt(d1.dotProduct(d1) * d2.dotProduct(d2)); float cosLSM = pd1.dotProduct(pd2) / (float) Math.sqrt(pd1.dotProduct(pd1) * pd2.dotProduct(pd2)); float cosBOWLSM = m1.dotProduct(m2) / (float) Math.sqrt(m1.dotProduct(m1) * m2.dotProduct(m2)); bw.print("\t"); bw.print(dec.format(cosVSM)); lw.print("\t"); lw.print(dec.format(cosLSM)); blw.print("\t"); blw.print(dec.format(cosBOWLSM)); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow\t" + cosVSM); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") ls:\t" + cosLSM); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow+ls:\t" + cosBOWLSM); } bw.print("\n"); lw.print("\n"); blw.print("\n"); } // end for i logger.info("wrote " + bwf); logger.info("wrote " + bwf); logger.info("wrote " + bdf); logger.info("wrote " + lwf); logger.info("wrote " + ldf); logger.info("wrote " + blwf); logger.info("wrote " + bldf); logger.info("wrote " + logf); ld.close(); bd.close(); bld.close(); bw.close(); lw.close(); blw.close(); log.close(); }
From source file:simauthenticator.SimAuthenticator.java
/** * @param args the command line arguments *///from w ww .j av a 2 s .co m public static void main(String[] args) throws Exception { cliOpts = new Options(); cliOpts.addOption("U", "url", true, "Connection URL"); cliOpts.addOption("u", "user", true, "User name"); cliOpts.addOption("p", "password", true, "User password"); cliOpts.addOption("d", "domain", true, "Domain name"); cliOpts.addOption("v", "verbose", false, "Verbose output"); cliOpts.addOption("k", "keystore", true, "KeyStore path"); cliOpts.addOption("K", "keystorepass", true, "KeyStore password"); cliOpts.addOption("h", "help", false, "Print help info"); CommandLineParser clip = new GnuParser(); cmd = clip.parse(cliOpts, args); if (cmd.hasOption("help")) { help(); return; } else { boolean valid = init(args); if (!valid) { return; } } HttpClientContext clientContext = HttpClientContext.create(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] keystorePassword = passwk.toCharArray(); FileInputStream kfis = null; try { kfis = new FileInputStream(keyStorePath); ks.load(kfis, keystorePassword); } finally { if (kfis != null) { kfis.close(); } } SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext) .setSSLSocketFactory(sslsf).setUserAgent(userAgent); ; cookieStore = new BasicCookieStore(); /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details"); cookie.setVersion(0); cookie.setDomain(".astelit.ukr"); cookie.setPath("/"); cookieStore.addCookie(cookie);*/ CloseableHttpClient client = httpClientBuilder.build(); try { NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(), domain); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setCookieStore(cookieStore); HttpGet httpget = new HttpGet(eventUrl); if (verbose) { System.out.println("executing request " + httpget.getRequestLine()); } HttpResponse response = client.execute(httpget, context); HttpEntity entity = response.getEntity(); HttpPost httppost = new HttpPost(eventUrl); List<Cookie> cookies = cookieStore.getCookies(); if (verbose) { System.out.println("----------------------------------------------"); System.out.println(response.getStatusLine()); System.out.print("Initial set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("usernameInput", usern)); nvps.add(new BasicNameValuePair("passwordInput", passwu)); nvps.add(new BasicNameValuePair("domainInput", domain)); //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern)); //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu)); if (entity != null && verbose) { System.out.println("Responce content length: " + entity.getContentLength()); } //System.out.println(EntityUtils.toString(entity)); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse afterPostResponse = client.execute(httppost, context); HttpEntity afterPostEntity = afterPostResponse.getEntity(); cookies = cookieStore.getCookies(); if (entity != null && verbose) { System.out.println("----------------------------------------------"); System.out.println(afterPostResponse.getStatusLine()); System.out.println("Responce content length: " + afterPostEntity.getContentLength()); System.out.print("After POST set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } System.out.println(EntityUtils.toString(afterPostEntity)); EntityUtils.consume(entity); EntityUtils.consume(afterPostEntity); } finally { client.getConnectionManager().shutdown(); } }
From source file:DcmRcv.java
@SuppressWarnings("unchecked") public static void main(String[] args) { CommandLine cl = parse(args);/*from w w w .j a v a2 s . co m*/ DcmRcv dcmrcv = new DcmRcv(); final List argList = cl.getArgList(); String port = (String) argList.get(0); String[] aetPort = split(port, ':', 1); dcmrcv.setPort(parseInt(aetPort[1], "illegal port number", 1, 0xffff)); if (aetPort[0] != null) { String[] aetHost = split(aetPort[0], '@', 0); dcmrcv.setAEtitle(aetHost[0]); if (aetHost[1] != null) { dcmrcv.setHostname(aetHost[1]); } } if (cl.hasOption("dest")) dcmrcv.setDestination(cl.getOptionValue("dest")); if (cl.hasOption("defts")) dcmrcv.setTransferSyntax(ONLY_DEF_TS); else if (cl.hasOption("native")) dcmrcv.setTransferSyntax(cl.hasOption("bigendian") ? NATIVE_TS : NATIVE_LE_TS); else if (cl.hasOption("bigendian")) dcmrcv.setTransferSyntax(NON_RETIRED_TS); if (cl.hasOption("reaper")) dcmrcv.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"), "illegal argument of option -reaper", 1, Integer.MAX_VALUE)); if (cl.hasOption("idleTO")) dcmrcv.setIdleTimeout(parseInt(cl.getOptionValue("idleTO"), "illegal argument of option -idleTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("requestTO")) dcmrcv.setRequestTimeout(parseInt(cl.getOptionValue("requestTO"), "illegal argument of option -requestTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("releaseTO")) dcmrcv.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"), "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("soclosedelay")) dcmrcv.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"), "illegal argument of option -soclosedelay", 1, 10000)); if (cl.hasOption("rspdelay")) dcmrcv.setDimseRspDelay( parseInt(cl.getOptionValue("rspdelay"), "illegal argument of option -rspdelay", 0, 10000)); if (cl.hasOption("rcvpdulen")) dcmrcv.setMaxPDULengthReceive( parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000) * KB); if (cl.hasOption("sndpdulen")) dcmrcv.setMaxPDULengthSend( parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000) * KB); if (cl.hasOption("sosndbuf")) dcmrcv.setSendBufferSize( parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB); if (cl.hasOption("sorcvbuf")) dcmrcv.setReceiveBufferSize( parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB); if (cl.hasOption("bufsize")) dcmrcv.setFileBufferSize( parseInt(cl.getOptionValue("bufsize"), "illegal argument of option -bufsize", 1, 10000) * KB); dcmrcv.setPackPDV(!cl.hasOption("pdv1")); dcmrcv.setTcpNoDelay(!cl.hasOption("tcpdelay")); if (cl.hasOption("async")) dcmrcv.setMaxOpsPerformed( parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff)); dcmrcv.initTransferCapability(); if (cl.hasOption("tls")) { String cipher = cl.getOptionValue("tls"); if ("NULL".equalsIgnoreCase(cipher)) { dcmrcv.setTlsWithoutEncyrption(); } else if ("3DES".equalsIgnoreCase(cipher)) { dcmrcv.setTls3DES_EDE_CBC(); } else if ("AES".equalsIgnoreCase(cipher)) { dcmrcv.setTlsAES_128_CBC(); } else { exit("Invalid parameter for option -tls: " + cipher); } if (cl.hasOption("nossl2")) { dcmrcv.disableSSLv2Hello(); } dcmrcv.setTlsNeedClientAuth(!cl.hasOption("noclientauth")); if (cl.hasOption("keystore")) { dcmrcv.setKeyStoreURL(cl.getOptionValue("keystore")); } if (cl.hasOption("keystorepw")) { dcmrcv.setKeyStorePassword(cl.getOptionValue("keystorepw")); } if (cl.hasOption("keypw")) { dcmrcv.setKeyPassword(cl.getOptionValue("keypw")); } if (cl.hasOption("truststore")) { dcmrcv.setTrustStoreURL(cl.getOptionValue("truststore")); } if (cl.hasOption("truststorepw")) { dcmrcv.setTrustStorePassword(cl.getOptionValue("truststorepw")); } try { dcmrcv.initTLS(); } catch (Exception e) { System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage()); System.exit(2); } } try { dcmrcv.start(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.acapulcoapp.alloggiatiweb.FileReader.java
public static void main(String[] args) throws UnknownHostException, IOException { // TODO code application logic here SpringApplication app = new SpringApplication(AcapulcoappApp.class); SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); addDefaultProfile(app, source);/* w w w.j a va 2 s.c o m*/ ConfigurableApplicationContext context = app.run(args); initBeans(context); Map<LocalDate, List<List<String>>> map = new TreeMap<>(); List<File> files = new ArrayList<>(FileUtils.listFiles(new File("/Users/chiccomask/Downloads/ALLOGGIATI"), new String[] { "txt" }, true)); Collections.reverse(files); int count = 0; for (File file : files) { // List<String> allLines = FileUtils.readLines(file, "windows-1252"); List<String> allLines = FileUtils.readLines(file, "UTF-8"); for (int i = 0; i < allLines.size();) { count++; List<String> record = new ArrayList<>(); String line = allLines.get(i); String type = TIPO_ALLOGGIO.parse(line); switch (type) { case "16": record.add(line); i++; break; case "17": { record.add(line); boolean out = false; while (!out) { i++; if (i < allLines.size()) { String subline = allLines.get(i); String subtype = TIPO_ALLOGGIO.parse(subline); if (!subtype.equals("19")) { out = true; } else { record.add(subline); } } else { out = true; } } break; } case "18": { record.add(line); boolean out = false; while (!out) { i++; if (i < allLines.size()) { String subline = allLines.get(i); String subtype = TIPO_ALLOGGIO.parse(subline); if (!subtype.equals("20")) { out = true; } else { record.add(subline); } } else { out = true; } } break; } default: break; } LocalDate arrived = LocalDate.parse(DATA_ARRIVO.parse(line), DateTimeFormatter.ofPattern(DATE_PATTERN)); if (!map.containsKey(arrived)) { map.put(arrived, new ArrayList<>()); } map.get(arrived).add(record); } } for (LocalDate date : map.keySet()) { System.out.println(); System.out.println("process day " + date); for (List<String> record : map.get(date)) { System.out.println(); System.out.println("process record "); for (String line : record) { System.out.println(line); } CheckinRecord checkinRecord = new CheckinRecord(); //non lo setto per adesso String firstLine = record.get(0); String typeStr = TIPO_ALLOGGIO.parse(firstLine); CheckinType cht = checkinTypeRepository.find(typeStr); checkinRecord.setCheckinType(cht); int days = Integer.parseInt(PERMANENZA.parse(firstLine)); checkinRecord.setDays(days); checkinRecord.setArrived(date); boolean isMain = true; List<Person> others = new ArrayList<>(); for (String line : record) { Person p = extractPerson(line); if (p.getDistrictOfBirth() == null) { System.out.println("district of birth not found " + p); } List<Person> duplicates = personRepository.findDuplicates(p.getSurname(), p.getName(), p.getDateOfBirth()); if (duplicates.isEmpty()) { System.out.println("add new person " + p.getId() + " " + p); personRepository.saveAndFlush(p); } else if (duplicates.size() == 1) { Person found = duplicates.get(0); if (p.getIdentityDocument() != null) { //we sorted by date so we suppose //the file version is newer so we update the entity p.setId(found.getId()); System.out.println("update person " + p.getId() + " " + p); personRepository.saveAndFlush(p); } else if (found.getIdentityDocument() != null) { //on db there are more data so I use them. p = found; System.out.println("use already saved person " + p.getId() + " " + p); } else { p.setId(found.getId()); System.out.println("update person " + p.getId() + " " + p); personRepository.saveAndFlush(p); } } else { throw new RuntimeException("More duplicated for " + p.getName()); } if (isMain) { checkinRecord.setMainPerson(p); isMain = false; } else { others.add(p); } } checkinRecord.setOtherPeople(new HashSet<>(others)); if (checkinRecordRepository.alreadyExists(checkinRecord.getMainPerson(), date) != null) { System.out.println("already exists " + date + " p " + checkinRecord.getMainPerson()); } else { System.out.println("save record "); checkinRecordRepository.saveAndFlush(checkinRecord); } } } // // if (type.equals("16")) { // List<String> record = new ArrayList<>(); // record.add(line); // keepOpen = false; // } // // map.get(arrived).add(record); // map.values().forEach((list) -> { // // for (String line : list) { // // Person p = null; // // try { // // p = extractPerson(line); // // List<Person> duplicates = personRepository.findDuplicates(p.getSurname(), p.getName(), p.getDateOfBirth()); // // if (duplicates.isEmpty()) { // personRepository.saveAndFlush(p); // // } else if (duplicates.size() > 1) { // System.out.println(); // System.out.println("MULIPLE DUPLICATED"); // // for (Person dd : duplicates) { // System.out.println(dd); // } // System.out.println("* " + p); // throw new RuntimeException(); // } else { // //// if (!duplicates.get(0).getDistrictOfBirth().equals(p.getDistrictOfBirth())) { //// int index = 0; //// //// System.out.println(); //// System.out.println("DUPLICATED"); //// //// for (Person dd : duplicates) { //// System.out.println(dd); //// index++; //// } //// System.out.println("* " + p); //// System.out.println(file.getAbsolutePath() + " " + p); //// //// System.out.println(); //// System.out.println(); //// } //// duplicates.remove(0); //// personRepository.deleteInBatch(duplicates); //// System.out.println(); //// System.out.println("Seleziona scelta"); //// Scanner s = new Scanner(System.in); //// int selected; //// try { //// selected = s.nextInt(); //// } catch (InputMismatchException e) { //// selected = 0; //// } //// //// if (duplicates.size() <= selected) { //// personRepository.deleteInBatch(duplicates); //// personRepository.saveAndFlush(p); //// } else { //// duplicates.remove(selected); //// personRepository.deleteInBatch(duplicates); //// } // } // // } catch (Exception e) { // // System.out.println(); //// System.out.println("ERROR READING lineCount=" + allLines.indexOf(line) + " line=" + line); //// System.out.println(file.getAbsolutePath()); // System.out.println(p); // e.printStackTrace(); // System.out.println(); // } // } // }); context.registerShutdownHook(); System.exit(0); }
From source file:com.kactech.otj.examples.App_otj.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String command = null;//w w w . ja va 2 s . c om String hisacct = null; String hisacctName = null; String hisacctAsset = null; String asset = null; String assetName = null; List<String> argList = null; boolean newAccount = false; File dir = null; ConnectionInfo connection = null; List<ScriptFilter> filters = null; CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println("Command-line parsing error: " + e.getMessage()); help(); System.exit(-1); } if (cmd.hasOption('h')) { help(); System.exit(0); } @SuppressWarnings("unchecked") List<String> list = cmd.getArgList(); if (list.size() > 1) { System.err.println("only one command is supported, you've typed " + list); help(); System.exit(-1); } if (list.size() > 0) command = list.get(0).trim(); List<SampleAccount> accounts = ExamplesUtils.getSampleAccounts(); if (cmd.hasOption('s')) { String v = cmd.getOptionValue('s').trim(); connection = ExamplesUtils.findServer(v); if (connection == null) { System.err.println("unknown server: " + v); System.exit(-1); } } else { connection = ExamplesUtils.findServer(DEF_SERVER_NAME); if (connection == null) { System.err.println("default server not found server: " + DEF_SERVER_NAME); System.exit(-1); } } if (cmd.hasOption('t')) { String v = cmd.getOptionValue('t'); for (SampleAccount ac : accounts) if (ac.accountName.startsWith(v)) { hisacct = ac.accountID; hisacctName = ac.accountName; hisacctAsset = ac.assetID; break; } if (hisacct == null) if (mayBeValid(v)) hisacct = v; else { System.err.println("invalid hisacct: " + v); System.exit(-1); } } if (cmd.hasOption('p')) { String v = cmd.getOptionValue('p'); for (SampleAccount ac : accounts) if (ac.assetName.startsWith(v)) { asset = ac.assetID; assetName = ac.assetName; break; } if (asset == null) if (mayBeValid(v)) asset = v; else { System.err.println("invalid asset: " + v); System.exit(-1); } } if (cmd.hasOption('a')) { String v = cmd.getOptionValue('a'); argList = new ArrayList<String>(); boolean q = false; StringBuilder b = new StringBuilder(); for (int i = 0; i < v.length(); i++) { char c = v.charAt(i); if (c == '"') { if (q) { argList.add(b.toString()); b = null; q = false; continue; } if (b != null) argList.add(b.toString()); b = new StringBuilder(); q = true; continue; } if (c == ' ' || c == '\t') { if (q) { b.append(c); continue; } if (b != null) argList.add(b.toString()); b = null; continue; } if (b == null) b = new StringBuilder(); b.append(c); } if (b != null) argList.add(b.toString()); if (q) { System.err.println("unclosed quote in args: " + v); System.exit(-1); } } dir = new File(cmd.hasOption('d') ? cmd.getOptionValue('d') : DEF_CLIENT_DIR); if (cmd.hasOption('x')) del(dir); newAccount = cmd.hasOption('n'); if (cmd.hasOption('f')) { filters = new ArrayList<ScriptFilter>(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Compilable compilingEngine = (Compilable) engine; for (String fn : cmd.getOptionValue('f').split(",")) { fn = fn.trim(); if (fn.isEmpty()) continue; fn += ".js"; Reader r = null; try { r = new InputStreamReader(new FileInputStream(new File("filters", fn)), Utils.UTF8); } catch (Exception e) { try { r = new InputStreamReader( App_otj.class.getResourceAsStream("/com/kactech/otj/examples/filters/" + fn)); } catch (Exception e2) { } } if (r == null) { System.err.println("filter not found: " + fn); System.exit(-1); } else try { CompiledScript compiled = compilingEngine.compile(r); ScriptFilter sf = new ScriptFilter(compiled); filters.add(sf); } catch (Exception ex) { System.err.println("error while loading " + fn + ": " + ex); System.exit(-1); } } } System.out.println("server: " + connection.getEndpoint() + " " + connection.getID()); System.out.println("command: '" + command + "'"); System.out.println("args: " + argList); System.out.println("hisacct: " + hisacct); System.out.println("hisacctName: " + hisacctName); System.out.println("hisacctAsset: " + hisacctAsset); System.out.println("asset: " + asset); System.out.println("assetName: " + assetName); if (asset != null && hisacctAsset != null && !asset.equals(hisacctAsset)) { System.err.println("asset differs from hisacctAsset"); System.exit(-1); } EClient client = new EClient(dir, connection); client.setAssetType(asset != null ? asset : hisacctAsset); client.setCreateNewAccount(newAccount); if (filters != null) client.setFilters(filters); try { Utils.init(); Client.DEBUG_JSON = true; client.init(); if ("balance".equals(command)) System.out.println("Balance: " + client.getAccount().getBalance().getAmount()); else if ("acceptall".equals(command)) client.processInbox(); else if ("transfer".equals(command)) { if (hisacct == null) System.err.println("please specify --hisacct"); else { int idx = argList != null ? argList.indexOf("amount") : -1; if (idx < 0) System.err.println("please specify amount"); else if (idx == argList.size()) System.err.println("amount argument needs value"); else { Long amount = -1l; try { amount = new Long(argList.get(idx + 1)); } catch (Exception e) { } if (amount <= 0) System.err.println("invalid amount"); else { client.notarizeTransaction(hisacct, amount); } } } } else if ("reload".equals(command)) client.reloadState(); else if ("procnym".equals(command)) client.processNymbox(); } finally { client.saveState(); client.close(); } }
From source file:eu.amidst.core.inference.ImportanceSamplingRobust.java
public static void main(String[] args) throws IOException, ClassNotFoundException { BayesianNetworkGenerator.setNumberOfGaussianVars(0); BayesianNetworkGenerator.setNumberOfMultinomialVars(60, 2); BayesianNetworkGenerator.setNumberOfLinks(100); BayesianNetworkGenerator.setSeed(1); BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork(); System.out.println(bn);//from w w w.j a v a 2 s .co m ImportanceSamplingRobust importanceSampling = new ImportanceSamplingRobust(); importanceSampling.setModel(bn); //importanceSampling.setSamplingModel(vmp.getSamplingModel()); importanceSampling.setParallelMode(true); importanceSampling.setSampleSize(5000); importanceSampling.setSeed(57457); List<Variable> causalOrder = importanceSampling.causalOrder; Variable varPosterior = causalOrder.get(0); List<Variable> variablesPosteriori = new ArrayList<>(1); variablesPosteriori.add(varPosterior); importanceSampling.setVariablesAPosteriori(variablesPosteriori); importanceSampling.runInference(); // // //// for (Variable var: causalOrder) { //// System.out.println("Posterior (IS) of " + var.getName() + ":" + importanceSampling.getPosterior(var).toString()); //// } // System.out.println("Posterior (IS) of " + varPosterior.getName() + ":" + importanceSampling.getPosterior(varPosterior).toString()); System.out.println(bn.getConditionalDistribution(varPosterior).toString()); System.out.println("Log-Prob. of Evidence: " + importanceSampling.getLogProbabilityOfEvidence()); // Including evidence: Variable variableEvidence = causalOrder.get(1); int varEvidenceValue = 0; System.out.println("Evidence: Variable " + variableEvidence.getName() + " = " + varEvidenceValue); System.out.println(); HashMapAssignment assignment = new HashMapAssignment(1); assignment.setValue(variableEvidence, varEvidenceValue); importanceSampling.setEvidence(assignment); long time_start = System.nanoTime(); importanceSampling.runInference(); long time_end = System.nanoTime(); double execution_time = (((double) time_end) - time_start) / 1E9; System.out.println("Execution time: " + execution_time + " s"); System.out.println("Posterior of " + varPosterior.getName() + " (IS with Evidence) :" + importanceSampling.getPosterior(varPosterior).toString()); System.out.println("Log-Prob. of Evidence: " + importanceSampling.getLogProbabilityOfEvidence()); System.out.println("Prob of Evidence: " + Math.exp(importanceSampling.getLogProbabilityOfEvidence())); // Complex complex = new Complex(1,0); // Complex log_complex = complex.log(); // System.out.println(log_complex.getReal() + " + 1i * " + log_complex.getImaginary()); // // // Complex complex1 = new Complex(0.5,-0.3); // Complex complex2 = new Complex(0.2,0.1); // // Complex sum = complex1.add(complex2); // System.out.println(sum.getReal() + " + 1i * " + sum.getImaginary()); }
From source file:org.wso2.api.client.APIDownloader.java
public static void main(String[] args) throws Exception { String adminCookie;//from w ww. j ava2 s .c o m String authenticationAdminURL = APIDownloaderConstant.SERVICE_URL + APIDownloaderConstant.AUTHENTICATION_ADMIN; String tenantAdminURL = APIDownloaderConstant.SERVICE_URL + APIDownloaderConstant.TENANT_ADMIN; // setting the system properties for javax.net.ssl AuthenticationAdminServiceClient.setSystemProperties(APIDownloaderConstant.CLIENT_TRUST_STORE_PATH, APIDownloaderConstant.KEY_STORE_TYPE, APIDownloaderConstant.KEY_STORE_PASSWORD); AuthenticationAdminServiceClient.init(authenticationAdminURL); log.info("retrieving the admin cookie from the logged in session...."); adminCookie = AuthenticationAdminServiceClient.login(APIDownloaderConstant.HOST_NAME, APIDownloaderConstant.USER_NAME, APIDownloaderConstant.PASSWORD); List<String> tenantDomainList = null; if (adminCookie != null) { log.info("logged in to the back-end server successfully...."); TenantMgtAdminServiceClient.init(tenantAdminURL, adminCookie); tenantDomainList = TenantMgtAdminServiceClient.getAllTenants(); } else { throw new APIStoreInvocationException("Login Failed to Admin service"); } httpClient = HttpClientBuilder.create().build(); String storeCookie = StoreAPIInvoker.loginToStore(httpClient); if (storeCookie == null) { throw new APIStoreInvocationException("Login Failed to API Store"); } for (int i = 0; i < tenantDomainList.size(); i++) { APIMetaData apiMetaData = StoreAPIInvoker.fetchAPIMetaData(httpClient, tenantDomainList.get(i), storeCookie); StoreAPIInvoker.fetchAPIDefinition(httpClient, apiMetaData, storeCookie); } }
From source file:caarray.client.test.full.LoadTest.java
/** * @param args/*from w w w. j a v a2s. c om*/ */ public static void main(String[] args) { List<ApiFacade> apiFacades = new ArrayList<ApiFacade>(); List<List<ConfigurableTestSuite>> testSuiteCollection = new ArrayList<List<ConfigurableTestSuite>>(); int numThreads = TestProperties.getNumThreads(); if (numThreads <= 1) { System.out.println( "Thread count for load test set to 1 - setting to default count of " + DEFAULT_THREADS); numThreads = DEFAULT_THREADS; } try { for (int i = apiFacades.size(); i < numThreads; i++) { apiFacades.add(new FullApiFacade()); } for (int i = testSuiteCollection.size(); i < numThreads; i++) { List<ConfigurableTestSuite> shortTests = TestMain.getShortTestSuites(apiFacades.get(i)); List<ConfigurableTestSuite> longTests = TestMain.getLongTestSuites(apiFacades.get(i)); List<ConfigurableTestSuite> testSuites = new ArrayList<ConfigurableTestSuite>(); testSuites.addAll(shortTests); testSuites.addAll(longTests); testSuiteCollection.add(testSuites); } TestResultReport[] threadReports = new TestResultReport[numThreads]; for (int i = 0; i < numThreads; i++) { threadReports[i] = new TestResultReport(); } Thread[] loadTestThreads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { LoadTestThread thread = new LoadTestThread(apiFacades.get(i), testSuiteCollection.get(i), threadReports[i], i); loadTestThreads[i] = new Thread(thread); } System.out.println("Executing load tests for " + numThreads + " threads ..."); long start = System.currentTimeMillis(); for (int i = 0; i < numThreads; i++) { loadTestThreads[i].start(); } for (int i = 0; i < numThreads; i++) { loadTestThreads[i].join(); } long time = System.currentTimeMillis() - start; System.out.println("Load tests completed in " + (double) time / (double) 1000 + " seconds."); TestResultReport finalReport = new TestResultReport(); for (TestResultReport report : threadReports) { finalReport.merge(report); } System.out.println("Analyzing load test results ..."); finalReport.writeLoadTestReports(); } catch (Throwable t) { System.out.println("An exception occured execuitng the load tests: " + t.getClass()); System.out.println("Test suite aborted."); t.printStackTrace(); log.error("Exception encountered:", t); } }
From source file:hk.hku.cecid.corvus.http.AS2EnvelopQuerySender.java
/** * The main method is for CLI mode./*from w w w . jav a 2 s . c o 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:io.s4.util.LoadGenerator.java
public static void main(String args[]) { Options options = new Options(); boolean warmUp = false; options.addOption(/* w w w . j av a2s .c o m*/ OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r")); options.addOption(OptionBuilder.withArgName("display_rate").hasArg() .withDescription("Display Rate at specified second boundary").create("d")); options.addOption(OptionBuilder.withArgName("start_boundary").hasArg() .withDescription("Start boundary in seconds").create("b")); options.addOption(OptionBuilder.withArgName("run_for").hasArg() .withDescription("Run for a specified number of seconds").create("x")); options.addOption(OptionBuilder.withArgName("cluster_manager").hasArg().withDescription("Cluster manager") .create("z")); options.addOption(OptionBuilder.withArgName("sender_application_name").hasArg() .withDescription("Sender application name").create("a")); options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg() .withDescription("Listener application name").create("g")); options.addOption( OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o")); options.addOption(new Option("w", "Warm-up")); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } int expectedRate = 250; if (line.hasOption("r")) { try { expectedRate = Integer.parseInt(line.getOptionValue("r")); } catch (Exception e) { System.err.println("Bad expected rate specified " + line.getOptionValue("r")); System.exit(1); } } int displayRateIntervalSeconds = 20; if (line.hasOption("d")) { try { displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d")); } catch (Exception e) { System.err.println("Bad display rate value specified " + line.getOptionValue("d")); System.exit(1); } } int startBoundary = 2; if (line.hasOption("b")) { try { startBoundary = Integer.parseInt(line.getOptionValue("b")); } catch (Exception e) { System.err.println("Bad start boundary value specified " + line.getOptionValue("b")); System.exit(1); } } int updateFrequency = 0; if (line.hasOption("f")) { try { updateFrequency = Integer.parseInt(line.getOptionValue("f")); } catch (Exception e) { System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f")); System.exit(1); } System.out.printf("Update frequency is %d\n", updateFrequency); } int runForTime = 0; if (line.hasOption("x")) { try { runForTime = Integer.parseInt(line.getOptionValue("x")); } catch (Exception e) { System.err.println("Bad run for time specified " + line.getOptionValue("x")); System.exit(1); } System.out.printf("Run for time is %d\n", runForTime); } String clusterManagerAddress = null; if (line.hasOption("z")) { clusterManagerAddress = line.getOptionValue("z"); } String senderApplicationName = null; if (line.hasOption("a")) { senderApplicationName = line.getOptionValue("a"); } String listenerApplicationName = null; if (line.hasOption("a")) { listenerApplicationName = line.getOptionValue("g"); } if (listenerApplicationName == null) { listenerApplicationName = senderApplicationName; } long sleepOverheadMicros = -1; if (line.hasOption("o")) { try { sleepOverheadMicros = Long.parseLong(line.getOptionValue("o")); } catch (NumberFormatException e) { System.err.println("Bad sleep overhead specified " + line.getOptionValue("o")); System.exit(1); } System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros); } if (line.hasOption("w")) { warmUp = true; } List loArgs = line.getArgList(); if (loArgs.size() < 1) { System.err.println("No input file specified"); System.exit(1); } String inputFilename = (String) loArgs.get(0); EventEmitter emitter = null; SerializerDeserializer serDeser = new KryoSerDeser(); CommLayerEmitter clEmitter = new CommLayerEmitter(); clEmitter.setAppName(senderApplicationName); clEmitter.setListenerAppName(listenerApplicationName); clEmitter.setClusterManagerAddress(clusterManagerAddress); clEmitter.setSenderId(String.valueOf(System.currentTimeMillis() / 1000)); clEmitter.setSerDeser(serDeser); clEmitter.init(); emitter = clEmitter; long endTime = 0; if (runForTime > 0) { endTime = System.currentTimeMillis() + (runForTime * 1000); } LoadGenerator loadGenerator = new LoadGenerator(); loadGenerator.setInputFilename(inputFilename); loadGenerator.setEventEmitter(clEmitter); loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds); loadGenerator.setExpectedRate(expectedRate); loadGenerator.run(); System.exit(0); }