List of usage examples for java.lang Integer Integer
@Deprecated(since = "9") public Integer(String s) throws NumberFormatException
From source file:Messenger.TorLib.java
public static void main(String[] args) { String req = "-r"; String targetHostname = "tor.eff.org"; String targetDir = "index.html"; int targetPort = 80; if (args.length > 0 && args[0].equals("-h")) { System.out.println("Tinfoil/TorLib - interface for using Tor from Java\n" + "By Joe Foley<foley@mit.edu>\n" + "Usage: java Tinfoil.TorLib <cmd> <args>\n" + "<cmd> can be: -h for help\n" + " -r for resolve\n" + " -w for wget\n" + "For -r, the arg is:\n" + " <hostname> Hostname to DNS resolve\n" + "For -w, the args are:\n" + " <host> <path> <optional port>\n" + " for example, http://tor.eff.org:80/index.html would be\n" + " tor.eff.org index.html 80\n" + " Since this is a demo, the default is the tor website.\n"); System.exit(2);/*from www .j a va 2 s . com*/ } if (args.length >= 4) targetPort = new Integer(args[2]).intValue(); if (args.length >= 3) targetDir = args[2]; if (args.length >= 2) targetHostname = args[1]; if (args.length >= 1) req = args[0]; if (req.equals("-r")) { System.out.println(TorResolve(targetHostname)); } else if (req.equals("-w")) { try { Socket s = TorSocket(targetHostname, targetPort); DataInputStream is = new DataInputStream(s.getInputStream()); PrintStream out = new java.io.PrintStream(s.getOutputStream()); //Construct an HTTP request out.print("GET /" + targetDir + " HTTP/1.0\r\n"); out.print("Host: " + targetHostname + ":" + targetPort + "\r\n"); out.print("Accept: */*\r\n"); out.print("Connection: Keep-Aliv\r\n"); out.print("Pragma: no-cache\r\n"); out.print("\r\n"); out.flush(); // this is from Java Examples In a Nutshell final InputStreamReader from_server = new InputStreamReader(is); char[] buffer = new char[1024]; int chars_read; // read until stream closes while ((chars_read = from_server.read(buffer)) != -1) { // loop through array of chars // change \n to local platform terminator // this is a nieve implementation for (int j = 0; j < chars_read; j++) { if (buffer[j] == '\n') System.out.println(); else System.out.print(buffer[j]); } System.out.flush(); } s.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:it.cnr.icar.eric.common.security.KeystoreMover.java
public static void main(String args[]) throws Throwable { KeystoreMover ksm = new KeystoreMover(); String sourceKeystoreType = "PKCS12"; String sourceKeystorePath = null; String sourceKeystorePassword = null; String sourceAlias = null;//from ww w . jav a2s.co m String sourceKeyPassword = null; String destinationKeystoreType = "JKS"; String destinationKeystorePath = null; String destinationKeystorePassword = null; String destinationAlias = null; String destinationKeyPassword = null; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-help")) { printUsage(); } else if (args[i].equalsIgnoreCase("-sourceKeystoreType")) { sourceKeystoreType = args[++i]; } else if (args[i].startsWith("-sourceKeystorePath")) { sourceKeystorePath = args[++i]; } else if (args[i].startsWith("-sourceKeystorePassword")) { sourceKeystorePassword = args[++i]; } else if (args[i].startsWith("-sourceAlias")) { sourceAlias = args[++i]; } else if (args[i].startsWith("-sourceKeyPassword")) { sourceKeyPassword = args[++i]; } else if (args[i].startsWith("-destinationKeystoreType")) { destinationKeystoreType = args[++i]; } else if (args[i].startsWith("-destinationKeystorePath")) { destinationKeystorePath = args[++i]; } else if (args[i].startsWith("-destinationKeystorePassword")) { destinationKeystorePassword = args[++i]; } else if (args[i].startsWith("-destinationAlias")) { destinationAlias = args[++i]; } else if (args[i].startsWith("-destinationKeyPassword")) { destinationKeyPassword = args[++i]; } else { log.error(CommonResourceBundle.getInstance().getString("message.UnknownParameterAtPosition", new Object[] { args[i], new Integer(i) })); if (i > 0) { log.error(CommonResourceBundle.getInstance().getString("message.LastValidParameterWas", new Object[] { args[i - 1] })); } printUsage(); } } if (sourceKeystorePath == null) { log.error(CommonResourceBundle.getInstance().getString("message.ErrorMissingSourceKeystorePath")); printUsage(); } if (sourceKeystorePassword == null) { log.error(CommonResourceBundle.getInstance().getString("message.ErrorMissingSourceKeystorePassword")); printUsage(); } if (destinationKeystorePath == null) { log.error(CommonResourceBundle.getInstance().getString("message.ErrorMissingDestinationKeystorePath")); printUsage(); } if (destinationKeystorePassword == null) { log.error(CommonResourceBundle.getInstance() .getString("message.ErrorMissingDestinationKeystorePassword")); printUsage(); } try { ksm.move(sourceKeystoreType, sourceKeystorePath, sourceKeystorePassword, sourceAlias, sourceKeyPassword, destinationKeystoreType, destinationKeystorePath, destinationKeystorePassword, destinationAlias, destinationKeyPassword); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); }
From source file:de.prozesskraft.pkraft.Waitinstance.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file//from w ww . j av a 2 s . c o m ----------------------------*/ java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/" + "../etc/pkraft-waitinstance.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'") // .isRequired() .create("instance"); Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.") // .isRequired() .create("scandir"); Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription( "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.") // .isRequired() .create("maxrun"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oscandir); options.addOption(omaxrun); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("waitinstance", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ Integer maxrun = new Integer(4320); String pathInstance = null; String pathScandir = null; // instance & scandir if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) { System.err.println("one of the options -instance/-scandir is mandatory"); exiter(); } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) { System.err.println("both options -instance/-scandir are not allowed"); exiter(); } else if (commandline.hasOption("instance")) { pathInstance = commandline.getOptionValue("instance"); } else if (commandline.hasOption("scandir")) { pathScandir = commandline.getOptionValue("scandir"); } // maxrun if (commandline.hasOption("maxrun")) { maxrun = new Integer(commandline.getOptionValue("maxrun")); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // scannen nach dem ersten process.pmb if ((pathScandir != null) && (pathInstance == null)) { String[] allBinariesOfScanDir = getProcessBinaries(pathScandir); if (allBinariesOfScanDir.length == 0) { System.err.println("no instance (process.pmb) found in directory tree " + pathScandir); exiter(); } else { pathInstance = allBinariesOfScanDir[0]; System.err.println("found instance: " + pathInstance); } } // ueberpruefen ob instance file existiert java.io.File fileInstance = new java.io.File(pathInstance); if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } if (!fileInstance.isFile()) { System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath()); exiter(); } // zeitpunkt wenn spaetestens beendet werden soll long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000); // logging System.err.println("waiting for instance: " + fileInstance.getAbsolutePath()); System.err.println("checking its status every 5 minutes"); System.err.println("now is: " + new Timestamp(startInMillis).toString()); System.err.println("maxrun till: " + new Timestamp(runTill).toString()); // instanz einlesen Process p1 = new Process(); p1.setInfilebinary(fileInstance.getAbsolutePath()); Process p2 = p1.readBinary(); // schleife, die prozess einliest und ueberprueft ob er noch laeuft while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) { // logging System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus()); // 5 minuten schlafen: 300000 millis try { Thread.sleep(300000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage) if (System.currentTimeMillis() > runTill) { System.err .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis())); System.exit(2); } // den prozess frisch einlesen p2 = p1.readBinary(); } System.err.println("exiting because instance status is: " + p2.getStatus()); System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString()); System.exit(0); }
From source file:com.github.chrbayer84.keybits.KeyBits.java
/** * @param args//from w w w .j a v a 2s . c om */ public static void main(String[] args) throws Exception { int number_of_addresses = 1; int depth = 1; String usage = "java -jar KeyBits.jar [options]"; // create parameters which can be chosen Option help = new Option("h", "print this message"); Option verbose = new Option("v", "verbose"); Option exprt = new Option("e", "export public key to blockchain"); Option imprt = OptionBuilder.withArgName("string").hasArg() .withDescription("import public key from blockchain").create("i"); Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address") .create("a"); Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet") .create("c"); Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet") .create("u"); Option balance_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("return balance of wallet").create("b"); Option show_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("show content of wallet").create("w"); Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis") .create("s"); Option monitor_pending = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor pending transactions of wallet").create("p"); Option monitor_depth = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor transaction depths of wallet").create("d"); Option number = OptionBuilder.withArgName("integer").hasArg() .withDescription("in combination with -c, -d, -r or -s").create("n"); Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r"); Options options = new Options(); options.addOption(help); options.addOption(verbose); options.addOption(imprt); options.addOption(exprt); options.addOption(blockchain_address); options.addOption(create_wallet); options.addOption(update_wallet); options.addOption(balance_wallet); options.addOption(show_wallet); options.addOption(send_coins); options.addOption(monitor_pending); options.addOption(monitor_depth); options.addOption(number); options.addOption(reset); BasicParser parser = new BasicParser(); CommandLine cmd = null; String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator"); // show help if wrong usage try { cmd = parser.parse(options, args); } catch (Exception e) { printHelp(usage, options, header); } if (cmd.getOptions().length == 0) printHelp(usage, options, header); if (cmd.hasOption("h")) printHelp(usage, options, header); if (cmd.hasOption("v")) System.out.println(header); if (cmd.hasOption("c") && cmd.hasOption("n")) number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue(); if (cmd.hasOption("d") && cmd.hasOption("n")) depth = new Integer(cmd.getOptionValue("n")).intValue(); String checkpoints_file_name = "checkpoints"; if (!new File(checkpoints_file_name).exists()) checkpoints_file_name = null; // --------------------------------------------------------------------- if (cmd.hasOption("c")) { String wallet_file_name = cmd.getOptionValue("c"); String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); if (!new File(wallet_file_name).exists()) { String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name); if (!passphrase.equals(passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase); System.exit(0); } if (cmd.hasOption("u")) { String wallet_file_name = cmd.getOptionValue("u"); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("b")) { String wallet_file_name = cmd.getOptionValue("b"); System.out.println( MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue()); System.exit(0); } if (cmd.hasOption("w")) { String wallet_file_name = cmd.getOptionValue("w"); System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain")); System.exit(0); } if (cmd.hasOption("p")) { System.out.println("monitoring of pending transactions ... "); String wallet_file_name = cmd.getOptionValue("p"); MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("d")) { System.out.println("monitoring of transaction depth ... "); String wallet_file_name = cmd.getOptionValue("d"); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, depth); System.exit(0); } if (cmd.hasOption("r") && cmd.hasOption("n")) { long epoch = new Long(cmd.getOptionValue("n")); System.out.println("resetting wallet ... "); String wallet_file_name = cmd.getOptionValue("r"); File chain_file = (new File(wallet_file_name + ".chain")); if (chain_file.exists()) chain_file.delete(); MyWallet.setCreationTime(wallet_file_name, epoch); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) { String wallet_file_name = cmd.getOptionValue("s"); String address = cmd.getOptionValue("a"); Integer amount = new Integer(cmd.getOptionValue("n")); String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address, new BigInteger(amount + ""), wallet_passphrase); System.out.println("waiting ..."); Thread.sleep(10000); System.out.println("monitoring of transaction depth ... "); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, 1); System.out.println("transaction fixed in blockchain with depth " + depth); System.exit(0); } // ---------------------------------------------------------------------------------------- // creates public key // ---------------------------------------------------------------------------------------- GnuPGP gpg = new GnuPGP(); if (cmd.hasOption("e")) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = input.readLine()) != null) sb.append(line + "\n"); PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString()); //System.out.println(gpg.showPublicKeys(public_key_ring)); byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring); String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded); // System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses)))); // file names for message String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet"; String public_key_wallet_file_name = public_key_file_name; String public_key_chain_file_name = public_key_wallet_file_name + ".chain"; // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage String public_key_wallet_passphrase = HelpfulStuff .insertPassphrase("enter password for " + public_key_wallet_file_name); if (!new File(public_key_wallet_file_name).exists()) { String public_key_wallet_passphrase_ = HelpfulStuff .reInsertPassphrase("enter password for " + public_key_wallet_file_name); if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1, public_key_wallet_passphrase); MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name); String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name, 0); System.out.println("address of public key: " + public_key_address); // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name, addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase); } if (cmd.hasOption("i")) { String location = cmd.getOptionValue("i"); String[] addresses = null; if (location.indexOf(",") > -1) { String[] locations = location.split(","); addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain", checkpoints_file_name, locations[0], locations[1]); } else { addresses = BlockchainDotInfo.getKeys(location); } byte[] encoded = (new Encoding()).decodePublicKey(addresses); PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded); System.out.println(gpg.getArmored(public_key_ring)); System.exit(0); } }
From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java
/** * Main application to be run when this CygnusApplication is invoked. The only differences with the original one * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in * the command line.// w w w . ja v a 2s .c om * @param args */ public static void main(String[] args) { try { Options options = new Options(); Option option = new Option("n", "name", true, "the name of this agent"); option.setRequired(true); options.addOption(option); option = new Option("f", "conf-file", true, "specify a conf file"); option.setRequired(true); options.addOption(option); option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed"); options.addOption(option); option = new Option("h", "help", false, "display help text"); options.addOption(option); option = new Option("p", "mgmt-if-port", true, "the management interface port"); option.setRequired(false); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); File configurationFile = new File(commandLine.getOptionValue('f')); String agentName = commandLine.getOptionValue('n'); boolean reload = !commandLine.hasOption("no-reload-conf"); if (commandLine.hasOption('h')) { new HelpFormatter().printHelp("flume-ng agent", options, true); return; } // if int mgmtIfPort = 8081; // default value if (commandLine.hasOption('p')) { mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue(); } // if // the following is to ensure that by default the agent will fail on startup if the file does not exist if (!configurationFile.exists()) { // if command line invocation, then need to fail fast if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) { String path = configurationFile.getPath(); try { path = configurationFile.getCanonicalPath(); } catch (IOException ex) { logger.error("Failed to read canonical path for file: " + path, ex); } // try catch throw new ParseException("The specified configuration file does not exist: " + path); } // if } // if List<LifecycleAware> components = Lists.newArrayList(); CygnusApplication application; if (reload) { EventBus eventBus = new EventBus(agentName + "-event-bus"); PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider( agentName, configurationFile, eventBus, 30); components.add(configurationProvider); application = new CygnusApplication(components, mgmtIfPort); eventBus.register(application); } else { PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider( agentName, configurationFile); application = new CygnusApplication(mgmtIfPort); application.handleConfigurationEvent(configurationProvider.getConfiguration()); } // if else application.start(); final CygnusApplication appReference = application; Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") { @Override public void run() { appReference.stop(); } // run }); } catch (Exception e) { logger.error("A fatal error occurred while running. Exception follows.", e); } // try catch }
From source file:com.wordnik.swagger.testframework.APITestRunner.java
/** * Follow the following argument pattern * * Arg[0] --> api server URL/* w w w .ja va 2s .c o m*/ * Arg[1] --> api key * Arg[2] --> test script file path * Arg[3] --> test data file path * Arg[4] --> test data class name (class to which test data file will be deserialized) * Arg[5] --> package where API classes are available * Arg[6] --> Language to execute test cases * Arg[7] --> Library location * Arg[8] --> Optional test cases id. provide this if you need to execute only one test case * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String apiServer = args[0]; if (!apiServer.endsWith("/")) { apiServer = apiServer + "/"; } String apiKey = args[1]; String testScriptLocation = args[2]; String testDataLocation = args[3]; String testDataClass = args[4].trim(); System.out.println("class" + testDataClass + "test"); String apiPackageName = args[5]; String libraryLocation = args[6]; String language = args[7]; String suiteId = "0"; if (args.length > 8) { suiteId = args[8]; } ApiKeyAuthTokenBasedSecurityHandler securityHandler = new ApiKeyAuthTokenBasedSecurityHandler(apiKey, ""); APIInvoker aAPIInvoker = APIInvoker.initialize(securityHandler, apiServer, true); APITestRunner runner = new APITestRunner(); runner.initialize(testScriptLocation, testDataLocation, testDataClass); runner.runTests(apiServer, apiPackageName, runner.getTestPackage(), language, new Integer(suiteId), apiPackageName, securityHandler, libraryLocation); }
From source file:ebay.Ebay.java
/** * @param args the command line arguments *//* w w w . ja v a2 s .c om*/ public static void main(String[] args) { HttpClient client = null; HttpResponse response = null; BufferedReader rd = null; Document doc = null; String xml = ""; EbayDAO<Producto> db = new EbayDAO<>(Producto.class); String busqueda; while (true) { busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda"); if (busqueda != null) { busqueda = busqueda.replaceAll(" ", "%20"); try { client = new DefaultHttpClient(); /* peticion GET */ HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems" + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords=" + busqueda + "&siteid=0" + "&responseencoding=XML"); /* se ejecuta la peticion GET */ response = client.execute(request); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); /* comienza la lectura de la respuesta a la peticion GET */ String line; while ((line = rd.readLine()) != null) { xml += line + "\n"; } } catch (IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } /* creamos nuestro documentBulder(documento constructor) y obtenemos nuestro objeto documento apartir de documentBuilder */ try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } Element raiz = doc.getDocumentElement(); if (raiz == null) { System.exit(0); } if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) { NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes(); for (int i = 0; i < array.getLength(); ++i) { Node n = array.item(i); if (n.getNodeType() != Node.TEXT_NODE) { Producto p = new Producto(); if (((Element) n).getElementsByTagName("ItemID").item(0) != null) p.setId(new Long( ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("EndTime").item(0) != null) p.setEndtime( ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null) p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("ListingType").item(0) != null) p.setListingtype( ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent()); if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null) p.setGalleryurl( ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent()); if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null) p.setPrimarycategoryid(new Integer(((Element) n) .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null) p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("BidCount").item(0) != null) p.setBidcount(new Integer( ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null) p.setConvertedcurrentprice(new Double(((Element) n) .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null) p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null) p.setTimeleft( ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent()); if (((Element) n).getElementsByTagName("Title").item(0) != null) p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null) p.setShippingservicecost(new Double(((Element) n) .getElementsByTagName("ShippingServiceCost").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ShippingType").item(0) != null) p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("WatchCount").item(0) != null) p.setWatchcount(new Integer( ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null) p.setListedshippingservicecost( new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost") .item(0).getTextContent())); try { db.insert(p); } catch (Exception e) { db.update(p); } } } } Ventana.crear(xml); } else System.exit(0); } }
From source file:edu.msu.cme.rdp.classifier.train.validation.crossvalidate.CrossValidateMain.java
/** * This is the main method for cross validation test. * @param args//from w ww. j av a 2 s.c om * @throws IOException */ public static void main(String[] args) throws IOException { String tax_file = null; String source_file = null; String out_file = null; Integer partialLength = null; // default is full length float fraction = 0.1f; String rdmSelectedRank = null; int min_bootstrap_words = NBClassifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(TRAIN_TAXONFILE_SHORT_OPT)) { tax_file = line.getOptionValue(TRAIN_TAXONFILE_SHORT_OPT); } else { throw new ParseException("Taxonomy file must be specified"); } if (line.hasOption(TRAIN_SEQFILE_SHORT_OPT)) { source_file = line.getOptionValue(TRAIN_SEQFILE_SHORT_OPT); } else { throw new ParseException("Source training fasta file must be specified"); } if (line.hasOption(OUTFILE_SHORT_OPT)) { out_file = line.getOptionValue(OUTFILE_SHORT_OPT); } else { throw new ParseException("Output file must be specified"); } if (line.hasOption(LENGTH_SHORT_OPT)) { ; partialLength = new Integer(line.getOptionValue(LENGTH_SHORT_OPT)); } if (line.hasOption("fraction")) { fraction = Float.parseFloat(line.getOptionValue("fraction")); } if (line.hasOption("rdmRank")) { rdmSelectedRank = line.getOptionValue("rdmRank"); } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < NBClassifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException( min_bootstrap_words + " must be at least " + NBClassifier.MIN_BOOTSTRSP_WORDS); } } } catch (ParseException ex) { new HelpFormatter().printHelp(120, "CrossValidateMain", "", options, "", true); return; } boolean useSeed = true; // use seed for random number generator CrossValidate theObj = new CrossValidate(); theObj.runTest(new File(tax_file), new File(source_file), new File(out_file), rdmSelectedRank, fraction, partialLength, useSeed, min_bootstrap_words); }
From source file:ClassFileUtilities.java
/** * Program that computes the dependencies between the Batik jars. * <p>/*from ww w.j a v a 2 s . c o m*/ * Run this from the main Batik distribution directory, after building * the jars. For every jar file in the batik-xxx/ build directory, * it will determine which other jar files it directly depends on. * The output is lines of the form: * </p> * <pre> <i>number</i>,<i>from</i>,<i>to</i></pre> * <p> * where mean that the <i>from</i> jar has <i>number</i> class files * that depend on class files in the <i>to</i> jar. * </p> */ public static void main(String[] args) { boolean showFiles = false; if (args.length == 1 && args[0].equals("-f")) { showFiles = true; } else if (args.length != 0) { System.err.println("usage: ClassFileUtilities [-f]"); System.err.println(); System.err.println(" -f list files that cause each jar file dependency"); System.exit(1); } File cwd = new File("."); File buildDir = null; String[] cwdFiles = cwd.list(); for (int i = 0; i < cwdFiles.length; i++) { if (cwdFiles[i].startsWith("batik-")) { buildDir = new File(cwdFiles[i]); if (!buildDir.isDirectory()) { buildDir = null; } else { break; } } } if (buildDir == null || !buildDir.isDirectory()) { System.out.println("Directory 'batik-xxx' not found in current directory!"); return; } try { Map cs = new HashMap(); Map js = new HashMap(); collectJars(buildDir, js, cs); Set classpath = new HashSet(); Iterator i = js.values().iterator(); while (i.hasNext()) { classpath.add(((Jar) i.next()).jarFile); } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); // System.out.println(fromFile.name); Set result = getClassDependencies(fromFile.getInputStream(), classpath, false); Iterator j = result.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) cs.get(j.next()); if (fromFile != toFile && toFile != null) { fromFile.deps.add(toFile); } } } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); Iterator j = fromFile.deps.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) j.next(); Jar fromJar = fromFile.jar; Jar toJar = toFile.jar; if (fromFile.name.equals(toFile.name) || toJar == fromJar || fromJar.files.contains(toFile.name)) { continue; } Integer n = (Integer) fromJar.deps.get(toJar); if (n == null) { fromJar.deps.put(toJar, new Integer(1)); } else { fromJar.deps.put(toJar, new Integer(n.intValue() + 1)); } } } List triples = new ArrayList(10); i = js.values().iterator(); while (i.hasNext()) { Jar fromJar = (Jar) i.next(); Iterator j = fromJar.deps.keySet().iterator(); while (j.hasNext()) { Jar toJar = (Jar) j.next(); Triple t = new Triple(); t.from = fromJar; t.to = toJar; t.count = ((Integer) fromJar.deps.get(toJar)).intValue(); triples.add(t); } } Collections.sort(triples); i = triples.iterator(); while (i.hasNext()) { Triple t = (Triple) i.next(); System.out.println(t.count + "," + t.from.name + "," + t.to.name); if (showFiles) { Iterator j = t.from.files.iterator(); while (j.hasNext()) { ClassFile fromFile = (ClassFile) j.next(); Iterator k = fromFile.deps.iterator(); while (k.hasNext()) { ClassFile toFile = (ClassFile) k.next(); if (toFile.jar == t.to && !t.from.files.contains(toFile.name)) { System.out.println("\t" + fromFile.name + " --> " + toFile.name); } } } } } } catch (IOException e) { e.printStackTrace(); } }
From source file:QueueRoundTrip.java
public static void main(String argv[]) { // Values to be read from parameters String broker = DEFAULT_BROKER_NAME; String username = DEFAULT_USER_NAME; String password = DEFAULT_PASSWORD; int numTests = DEFAULT_NUM_TESTS; // Check parameters if (argv.length > 0) { for (int i = 0; i < argv.length; i++) { String arg = argv[i]; // Options if (!arg.startsWith("-")) { System.err.println("error: unexpected argument - " + arg); printUsage();//from ww w . j a v a 2 s . co m System.exit(1); } else { if (arg.equals("-b")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing broker name:port"); System.exit(1); } broker = argv[++i]; continue; } if (arg.equals("-u")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing user name"); System.exit(1); } username = argv[++i]; continue; } if (arg.equals("-p")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing password"); System.exit(1); } password = argv[++i]; continue; } if (arg.equals("-n")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing number of test to run."); System.exit(1); } numTests = (new Integer(argv[++i])).intValue(); continue; } if (arg.equals("-h")) { printUsage(); System.exit(1); } } } } // create the payload byte charToWrite = (0x30); for (int i = 0; i < msgSize; i++) { msgBody[i] = charToWrite; charToWrite = (byte) ((int) charToWrite + (int) 0x01); if (charToWrite == (0x39)) { charToWrite = (0x30); } } // Start the JMS client for the test. QueueRoundTrip queueRoundTripper = new QueueRoundTrip(); queueRoundTripper.QueueRoundTripper(broker, username, password, numTests); }