List of usage examples for java.util Properties Properties
public Properties()
From source file:com.google.oacurl.Login.java
public static void main(String[] args) throws Exception { LoginOptions options = new LoginOptions(); try {//from w w w . j a va 2 s . c o m options.parse(args); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(-1); } if (options.isHelp()) { new HelpFormatter().printHelp(" ", options.getOptions()); System.exit(0); } if (options.isInsecure()) { SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); } LoggingConfig.init(options.isVerbose()); if (options.isWirelogVerbose()) { LoggingConfig.enableWireLog(); } ServiceProviderDao serviceProviderDao = new ServiceProviderDao(); ConsumerDao consumerDao = new ConsumerDao(options); AccessorDao accessorDao = new AccessorDao(); String serviceProviderFileName = options.getServiceProviderFileName(); if (serviceProviderFileName == null) { if (options.isBuzz()) { // Buzz has its own provider because it has a custom authorization URL serviceProviderFileName = "BUZZ"; } else if (options.getVersion() == OAuthVersion.V2) { serviceProviderFileName = "GOOGLE_V2"; } else { serviceProviderFileName = "GOOGLE"; } } // We have a wee library of service provider properties files bundled into // the resources, so we set up the PropertiesProvider to search for them // if the file cannot be found. OAuthServiceProvider serviceProvider = serviceProviderDao.loadServiceProvider( new PropertiesProvider(serviceProviderFileName, ServiceProviderDao.class, "services/").get()); OAuthConsumer consumer = consumerDao .loadConsumer(new PropertiesProvider(options.getConsumerFileName()).get(), serviceProvider); OAuthAccessor accessor = accessorDao.newAccessor(consumer); OAuthClient client = new OAuthClient(new HttpClient4()); LoginCallbackServer callbackServer = null; boolean launchedBrowser = false; try { if (!options.isNoServer()) { callbackServer = new LoginCallbackServer(options); callbackServer.start(); } String callbackUrl; if (options.getCallback() != null) { callbackUrl = options.getCallback(); } else if (callbackServer != null) { callbackUrl = callbackServer.getCallbackUrl(); } else { callbackUrl = null; } OAuthEngine engine; switch (options.getVersion()) { case V1: engine = new V1OAuthEngine(); break; case V2: engine = new V2OAuthEngine(); break; case WRAP: engine = new WrapOAuthEngine(); break; default: throw new IllegalArgumentException("Unknown version: " + options.getVersion()); } do { String authorizationUrl = engine.getAuthorizationUrl(client, accessor, options, callbackUrl); if (!options.isNoServer()) { callbackServer.setAuthorizationUrl(authorizationUrl); } if (!launchedBrowser) { String url = options.isDemo() ? callbackServer.getDemoUrl() : authorizationUrl; if (options.isNoBrowser()) { System.out.println(url); System.out.flush(); } else { launchBrowser(options, url); } launchedBrowser = true; } accessor.accessToken = null; logger.log(Level.INFO, "Waiting for verification token..."); String verifier; if (options.isNoServer()) { System.out.print("Verification token: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); verifier = ""; while (verifier.isEmpty()) { String line = reader.readLine(); if (line == null) { System.exit(-1); } verifier = line.trim(); } } else { verifier = callbackServer.waitForVerifier(accessor, -1); if (verifier == null) { System.err.println("Wait for verifier interrupted"); System.exit(-1); } } logger.log(Level.INFO, "Verification token received: " + verifier); boolean success = engine.getAccessToken(accessor, client, callbackUrl, verifier); if (success) { if (callbackServer != null) { callbackServer.setTokenStatus(TokenStatus.VALID); } Properties loginProperties = new Properties(); accessorDao.saveAccessor(accessor, loginProperties); consumerDao.saveConsumer(consumer, loginProperties); loginProperties.put("oauthVersion", options.getVersion().toString()); new PropertiesProvider(options.getLoginFileName()).overwrite(loginProperties); } else { if (callbackServer != null) { callbackServer.setTokenStatus(TokenStatus.INVALID); } } } while (options.isDemo()); } catch (OAuthProblemException e) { OAuthUtil.printOAuthProblemException(e); } finally { if (callbackServer != null) { callbackServer.stop(); } } }
From source file:gobblin.runtime.util.JobStateToJsonConverter.java
@SuppressWarnings("all") public static void main(String[] args) throws Exception { Option sysConfigOption = Option.builder("sc").argName("system configuration file") .desc("Gobblin system configuration file").longOpt("sysconfig").hasArgs().build(); Option storeUrlOption = Option.builder("u").argName("gobblin state store URL") .desc("Gobblin state store root path URL").longOpt("storeurl").hasArgs().required().build(); Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name") .longOpt("name").hasArgs().required().build(); Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id") .hasArgs().build();//from ww w.ja v a2 s .com Option convertAllOption = Option.builder("a") .desc("Whether to convert all past job states of the given job").longOpt("all").build(); Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties") .longOpt("keepConfig").build(); Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name") .longOpt("toFile").hasArgs().build(); Options options = new Options(); options.addOption(sysConfigOption); options.addOption(storeUrlOption); options.addOption(jobNameOption); options.addOption(jobIdOption); options.addOption(convertAllOption); options.addOption(keepConfigOption); options.addOption(outputToFile); CommandLine cmd = null; try { CommandLineParser parser = new DefaultParser(); cmd = parser.parse(options, args); } catch (ParseException pe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateToJsonConverter", options); System.exit(1); } Properties sysConfig = new Properties(); if (cmd.hasOption(sysConfigOption.getLongOpt())) { sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt())); } JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'), cmd.hasOption("kc")); StringWriter stringWriter = new StringWriter(); if (cmd.hasOption('i')) { converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter); } else { if (cmd.hasOption('a')) { converter.convertAll(cmd.getOptionValue('n'), stringWriter); } else { converter.convert(cmd.getOptionValue('n'), stringWriter); } } if (cmd.hasOption('t')) { Closer closer = Closer.create(); try { FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t'))); OutputStreamWriter outputStreamWriter = closer.register( new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING)); BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter)); bufferedWriter.write(stringWriter.toString()); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } else { System.out.println(stringWriter.toString()); } }
From source file:io.anserini.index.UserPostFrequencyDistribution.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(OptionBuilder.withArgName("collection").hasArg() .withDescription("source collection directory").create(COLLECTION_OPTION)); options.addOption(OptionBuilder.withArgName("property").hasArg() .withDescription("source collection directory").create("property")); options.addOption(OptionBuilder.withArgName("collection_pattern").hasArg() .withDescription("source collection directory").create("collection_pattern")); CommandLine cmdline = null;/*from ww w .ja v a 2 s. co m*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(UserPostFrequencyDistribution.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); final FieldType textOptions = new FieldType(); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); textOptions.setStoreTermVectors(true); LOG.info("collection: " + collectionPath); LOG.info("collection_pattern " + cmdline.getOptionValue("collection_pattern")); LOG.info("property " + cmdline.getOptionValue("property")); LongOpenHashSet deletes = null; long startTime = System.currentTimeMillis(); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } final JsonStatusCorpusReader stream = new JsonStatusCorpusReader(file, cmdline.getOptionValue("collection_pattern")); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { stream.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ; System.out.println("# of users indexed this round: " + userIndexedCount); System.out.println("Shutting down"); } }); Status status; boolean readerNotInitialized = true; try { Properties prop = new Properties(); while ((status = stream.next()) != null) { // try{ // status = DataObjectFactory.createStatus(s); // if (status==null||status.getText() == null) { // continue; // }}catch(Exception e){ // // } // boolean pittsburghRelated = false; try { if (Math.abs(status.getLongitude() - pittsburghLongitude) < 0.05d && Math.abs(status.getlatitude() - pittsburghLatitude) < 0.05d) pittsburghRelated = true; } catch (Exception e) { } try { if (status.getPlace().contains("Pittsburgh, PA")) pittsburghRelated = true; } catch (Exception e) { } try { if (status.getUserLocation().contains("Pittsburgh, PA")) pittsburghRelated = true; } catch (Exception e) { } try { if (status.getText().contains("Pittsburgh")) pittsburghRelated = true; } catch (Exception e) { } if (pittsburghRelated) { int previousPostCount = 0; if (prop.containsKey(String.valueOf(status.getUserid()))) { previousPostCount = Integer .valueOf(prop.getProperty(String.valueOf(status.getUserid())).split(" ")[1]); } prop.setProperty(String.valueOf(status.getUserid()), String.valueOf(status.getStatusesCount()) + " " + (1 + previousPostCount)); if (prop.size() > 0 && prop.size() % 1000 == 0) { Runtime runtime = Runtime.getRuntime(); runtime.gc(); System.out.println("Property size " + prop.size() + "Memory used: " + ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB\n"); } OutputStream output = new FileOutputStream(cmdline.getOptionValue("property"), false); prop.store(output, null); output.close(); } } // prop.store(output, null); LOG.info(String.format("Total of %s statuses added", userIndexedCount)); LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { stream.close(); } }
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method.//from w w w .jav a 2 s . com */ public static void main(String args[]) { LogUtils.setupUncaughtExceptionHandler(); /* Set timeout for RMI connections - TODO: move to external file */ System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000"); updateRmiHostName(); /* * Set up menu bar for Mac */ System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager"); /* * Set look and feel to 'system' style */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.info("Failed to set system look and feel"); } /* * Set workingDir to a writable folder for storing competitions, settings etc. */ String applicationData = System.getenv("APPDATA"); if (applicationData != null) { workingDir = new File(applicationData, "EventManager"); if (workingDir.exists() || workingDir.mkdirs()) { // redirect logging to writable folder LogUtils.reconfigureFileAppenders("log4j.properties", workingDir); } else { workingDir = new File("."); } } // log version for debugging log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")"); /* * Copy license if necessary */ File license1 = new File("license.lic"); File license2 = new File(workingDir, "license.lic"); if (license1.exists() && !license2.exists()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } if (license1.exists() && license2.exists()) { if (license1.lastModified() > license2.lastModified()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } } /* * Check if run lock exists, if so ask user if it is ok to continue */ if (!obtainRunLock(false)) { int response = JOptionPane.showConfirmDialog(null, "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?", "Run-lock detected", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) obtainRunLock(true); else System.exit(0); } try { LoadWindow loadWindow = new LoadWindow(); loadWindow.setVisible(true); loadWindow.addMessage("Reading settings.."); /* * Read properties from file */ final Properties props = new Properties(); try { Properties defaultProps = PropertiesLoaderUtils .loadProperties(new ClassPathResource("eventmanager.properties")); props.putAll(defaultProps); } catch (IOException ex) { log.error(ex); } props.putAll(System.getProperties()); File databaseStore = new File(workingDir, "comps"); int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port")); loadWindow.addMessage("Loading Peer Manager.."); log.info("Loading Peer Manager"); ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService(); JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat")); peerManager.addDiscoveryService(manualDiscoveryService); monitorNetworkInterfaceChanges(peerManager); loadWindow.addMessage("Loading Database Manager.."); log.info("Loading Database Manager"); DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager); LicenseManager licenseManager = new LicenseManager(workingDir); loadWindow.addMessage("Loading Load Competition Dialog.."); log.info("Loading Load Competition Dialog"); LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager, peerManager); loadCompetitionWindow.setTitle(WINDOW_TITLE); loadWindow.dispose(); log.info("Starting Load Competition Dialog"); while (true) { // reset permission checker to use our license licenseManager.updatePermissionChecker(); GUIUtils.runModalJFrame(loadCompetitionWindow); if (loadCompetitionWindow.getSuccess()) { DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo(); if (!databaseManager.checkLock(info.id)) { String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n" + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n" + "3) Delete the competition from this computer\n" + "4) If possible, reload this competition from another computer on the network\n" + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked."; String title = "WARNING: Potential Data Corruption Detected"; int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)"); if (status == 0) continue; // return to load competition window } SynchronizingWindow syncWindow = new SynchronizingWindow(); syncWindow.setVisible(true); long t = System.nanoTime(); DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash); long dt = System.nanoTime() - t; log.debug(String.format("Initial sync in %dms", TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS))); syncWindow.dispose(); if (loadCompetitionWindow.isNewDatabase()) { GregorianCalendar calendar = new GregorianCalendar(); Date today = calendar.getTime(); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 31); Date endOfYear = new java.sql.Date(calendar.getTimeInMillis()); CompetitionInfo ci = new CompetitionInfo(); ci.setName(info.name); ci.setStartDate(today); ci.setEndDate(today); ci.setAgeThresholdDate(endOfYear); //ci.setPasswordHash(info.passwordHash); License license = licenseManager.getLicense(); if (license != null) { ci.setLicenseName(license.getName()); ci.setLicenseType(license.getType().toString()); ci.setLicenseContact(license.getContactPhoneNumber()); } database.add(ci); } // Set PermissionChecker to use database's license type String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType(); PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType)); TransactionNotifier notifier = new TransactionNotifier(); database.setListener(notifier); MainWindow mainWindow = new MainWindow(); mainWindow.setDatabase(database); mainWindow.setNotifier(notifier); mainWindow.setPeerManager(peerManager); mainWindow.setLicenseManager(licenseManager); mainWindow.setManualDiscoveryService(manualDiscoveryService); mainWindow.setTitle(WINDOW_TITLE); mainWindow.afterPropertiesSet(); TestUtil.setActivatedDatabase(database); // show main window (modally) GUIUtils.runModalJFrame(mainWindow); // shutdown procedures // System.exit(); database.shutdown(); databaseManager.deactivateDatabase(1500); if (mainWindow.getDeleteOnExit()) { for (File file : info.localDirectory.listFiles()) if (!file.isDirectory()) file.delete(); info.localDirectory.deleteOnExit(); } } else { // This can cause an RuntimeException - Peer is disconnected peerManager.stop(); System.exit(0); } } } catch (Throwable e) { log.error("Error in main function", e); String message = e.getMessage(); if (message == null) message = ""; if (message.length() > 100) message = message.substring(0, 97) + "..."; GUIUtils.displayError(null, "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message); System.exit(0); } }
From source file:esg.node.components.registry.PeerNetworkFilter.java
public static void main(String[] args) { Properties p = new Properties(); p.setProperty("node.peer.group", "/o=org/ou=esgf, gov.llnl"); PeerNetworkFilter pnf = new PeerNetworkFilter(p); if (pnf.isInNetwork(args[0])) System.out.println("YES"); else/*from w w w. j a v a2 s .c o m*/ System.out.println("NO"); }
From source file:net.aepik.alasca.plugin.schemaconverter.SCTool.java
/** * Launch this tool.// ww w .ja v a 2s .c o m */ public static void main(String[] args) { String inFile = null; String inSyntax = null; String outFile = null; String outSyntax = null; boolean clear = false; boolean list = false; // // Parsing options. // CommandLineParser parser = new GnuParser(); try { CommandLine cmdOptions = parser.parse(options, args); inFile = cmdOptions.getOptionValue("i"); inSyntax = cmdOptions.getOptionValue("I"); outFile = cmdOptions.getOptionValue("o"); outSyntax = cmdOptions.getOptionValue("O"); if (cmdOptions.hasOption("c")) { clear = true; } if (cmdOptions.hasOption("l")) { list = true; } if (cmdOptions.getOptions().length == 0) { displayHelp(); System.exit(2); } } catch (MissingArgumentException e) { System.out.println("Missing arguments\n"); displayHelp(); System.exit(2); } catch (ParseException e) { System.out.println("Wrong arguments\n"); displayHelp(); System.exit(2); } // // Print query options. // if (list) { displayAvailableSyntaxes(); System.exit(0); } // // Launch schema. // String dictionnary = findDictionnary(inSyntax, outSyntax); if (dictionnary == null) { System.out.println("Can't find valid translation dictionnary"); System.exit(1); } SchemaSyntax inSchemaSyntax = createSchemaSyntax(inSyntax); if (inSchemaSyntax == null) { System.out.println("Unknow input syntax (" + inSyntax + ")"); System.exit(1); } SchemaSyntax outSchemaSyntax = createSchemaSyntax(outSyntax); if (outSchemaSyntax == null) { System.out.println("Unknow output syntax (" + outSyntax + ")"); System.exit(1); } Schema inSchema = createSchema(inSchemaSyntax, inFile); if (inSchema == null) { System.out.println("Failed to read input schema file (" + inFile + ")"); System.exit(1); } // // Convert schema. // Schema outSchema = convertSchema(inSchema, dictionnary, outSyntax); if (outSchema == null) { System.out.println("Failed to convert input schema"); System.exit(1); } if (clear) { outSchema.setProperties(new Properties()); } // // Write schema. // SchemaFileWriter schemaWriter = outSchemaSyntax.createSchemaWriter(); SchemaFile schemaFile = new SchemaFile(outFile, null, schemaWriter); schemaFile.setSchema(outSchema); if (!schemaFile.write()) { System.out.println("Failed to write output schema file"); System.exit(1); } System.exit(0); }
From source file:com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient.java
public static void main(String[] args) { CouchDBNativeClient cli = new CouchDBNativeClient(); Properties props = new Properties(); props.setProperty("hosts", "localhost"); props.setProperty("port", "5984"); cli.setProperties(props);/* w ww . j a v a 2 s. c o m*/ try { cli.init(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>(); vals.put("age", new StringByteIterator("57")); vals.put("middlename", new StringByteIterator("bradley")); vals.put("favoritecolor", new StringByteIterator("blue")); int res = cli.insert("usertable", "BrianFrankCooper", vals); System.out.println("Result of insert: " + res); HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>(); HashSet<String> fields = new HashSet<String>(); fields.add("middlename"); fields.add("age"); fields.add("favoritecolor"); res = cli.read("usertable", "BrianFrankCooper", null, result); System.out.println("Result of read: " + res); for (String s : result.keySet()) { System.out.println("[" + s + "]=[" + result.get(s) + "]"); } res = cli.delete("usertable", "BrianFrankCooper"); System.out.println("Result of delete: " + res); }
From source file:net.ontopia.topicmaps.db2tm.CSVImport.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();/* ww w . j a v a 2 s . c om*/ // Initialize command line option parser and listeners CmdlineOptions options = new CmdlineOptions("CSVImport", argv); OptionsListener ohandler = new OptionsListener(); // Register local options options.addLong(ohandler, "separator", 's', true); options.addLong(ohandler, "stripquotes", 'q'); options.addLong(ohandler, "ignorelines", 'i', true); // Register logging options CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length < 2) { System.err.println("Error: wrong number of arguments."); usage(); System.exit(1); } String dbprops = args[0]; String csvfile = args[1]; String table = (args.length >= 3 ? args[2] : null); if (table == null) { if (csvfile.endsWith(".csv")) table = csvfile.substring(0, csvfile.length() - 4); else table = csvfile; } String[] columns = (args.length >= 4 ? StringUtils.split(args[3], ",") : null); // Load property file Properties props = new Properties(); props.load(new FileInputStream(dbprops)); // Create database connection DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false); Connection conn = cfactory.requestConnection(); CSVImport ci = new CSVImport(conn); ci.setTable(table); ci.setColumns(columns); ci.setSeparator(ohandler.separator); ci.setClearTable(true); ci.setStripQuotes(ohandler.stripquotes); ci.setIgnoreColumns(true); ci.setIgnoreLines(ohandler.ignorelines); ci.importCSV(new FileInputStream(csvfile)); }
From source file:ar.edu.taco.TacoMain.java
/** * @param args//from w w w .j a v a 2 s.com */ @SuppressWarnings({ "static-access" }) public static void main(String[] args) { @SuppressWarnings("unused") int loopUnrolling = 3; String tacoVersion = getManifestAttribute(Attributes.Name.IMPLEMENTATION_VERSION); String tacoCreatedBy = getManifestAttribute(new Name("Created-By")); System.out.println("TACO: Taco static analysis tool."); System.out.println("Created By: " + tacoCreatedBy); System.out.println("Version: " + tacoVersion); System.out.println(""); System.out.println(""); Option helpOption = new Option("h", "help", false, "print this message"); Option versionOption = new Option("v", "version", false, "shows version"); Option configFileOption = OptionBuilder.withArgName("path").withLongOpt("configFile").hasArg() .withDescription("set the configuration file").create("cf"); Option classToCheckOption = OptionBuilder.withArgName("classname").withLongOpt("classToCheck").hasArg() .withDescription("set the class to be checked").create('c'); Option methodToCheckOption = OptionBuilder.withArgName("methodname").withLongOpt("methodToCheck").hasArg() .withDescription("set the method to be checked").create('m'); Option dependenciesOption = OptionBuilder.withArgName("classname").withLongOpt("dependencies").hasArgs() .withDescription("additional sources to be parsed").create('d'); Option relevantClassesOption = OptionBuilder.withArgName("classname").withLongOpt("relevantClasses") .hasArgs().withDescription("Set the relevant classes to be used").create("rd"); Option loopsOptions = OptionBuilder.withArgName("integer").withLongOpt("unroll").hasArg() .withDescription("set number of loop unrollings").create('u'); Option bitOptions = OptionBuilder.withArgName("integer").withLongOpt("width").hasArg() .withDescription("set bit width").create('w'); Option instOptions = OptionBuilder.withArgName("integer").withLongOpt("bound").hasArg() .withDescription("set class bound").create('b'); Option skolemizeOption = OptionBuilder.withLongOpt("skolemize") .withDescription("set whether or not skolemize").create("sk"); Option simulateOption = OptionBuilder.withLongOpt("simulate") .withDescription("run method instead of checking").create("r"); Option modularReasoningOption = OptionBuilder.withLongOpt("modularReasoning") .withDescription("check method using modular reasoning").create("mr"); Option relevancyAnalysisOption = OptionBuilder.withLongOpt("relevancyAnalysis") .withDescription("calculate the needed relevantClasses").create("ra"); Option scopeRestrictionOption = OptionBuilder.withLongOpt("scopeRestriction") .withDescription("restrict signature scope to value set in -b option").create("sr"); /* * Option noVerifyOption = OptionBuilder.withLongOpt( * "noVerify").withDescription( * "builds output but does not invoke verification engine").create( * "nv"); */ Options options = new Options(); options.addOption(helpOption); options.addOption(versionOption); options.addOption(configFileOption); options.addOption(classToCheckOption); options.addOption(methodToCheckOption); options.addOption(dependenciesOption); options.addOption(relevantClassesOption); options.addOption(loopsOptions); options.addOption(bitOptions); options.addOption(instOptions); options.addOption(skolemizeOption); options.addOption(simulateOption); options.addOption(modularReasoningOption); options.addOption(relevancyAnalysisOption); options.addOption(scopeRestrictionOption); // options.addOption(noVerifyOption) String configFileArgument = null; Properties overridingProperties = new Properties(); TacoCustomScope tacoScope = new TacoCustomScope(); // create the parser CommandLineParser parser = new PosixParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // help if (line.hasOption(helpOption.getOpt())) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, CMD, HEADER, options, FOOTER, true); return; } // version if (line.hasOption(versionOption.getOpt())) { System.out.println(FOOTER); System.out.println(""); return; } // Configuration file if (line.hasOption(configFileOption.getOpt())) { configFileArgument = line.getOptionValue(configFileOption.getOpt()); } // class to check if (line.hasOption(classToCheckOption.getOpt())) { overridingProperties.put(TacoConfigurator.CLASS_TO_CHECK_FIELD, line.getOptionValue(classToCheckOption.getOpt())); } // method to check if (line.hasOption(methodToCheckOption.getOpt())) { String methodtoCheck = line.getOptionValue(methodToCheckOption.getOpt()); if (!methodtoCheck.matches("^[A-Za-z0-9_-]+_[0-9]")) { methodtoCheck = methodtoCheck + "_0"; } overridingProperties.put(TacoConfigurator.METHOD_TO_CHECK_FIELD, methodtoCheck); } // Dependencies classes if (line.hasOption(dependenciesOption.getOpt())) { String dependenciesClasses = ""; for (String aDependencyClass : line.getOptionValues(dependenciesOption.getOpt())) { dependenciesClasses += aDependencyClass; } overridingProperties.put(TacoConfigurator.CLASSES_FIELD, dependenciesClasses); } // Relevant classes if (line.hasOption(relevantClassesOption.getOpt())) { String relevantClasses = ""; for (String aRelevantClass : line.getOptionValues(relevantClassesOption.getOpt())) { relevantClasses += aRelevantClass; } overridingProperties.put(TacoConfigurator.RELEVANT_CLASSES, relevantClasses); } // Loop unrolling if (line.hasOption(loopsOptions.getOpt())) { loopUnrolling = Integer.parseInt(line.getOptionValue(loopsOptions.getOpt())); } // Int bitwidth if (line.hasOption(bitOptions.getOpt())) { String alloy_bitwidth_str = line.getOptionValue(bitOptions.getOpt()); overridingProperties.put(TacoConfigurator.BITWIDTH, alloy_bitwidth_str); int alloy_bitwidth = new Integer(alloy_bitwidth_str); tacoScope.setAlloyBitwidth(alloy_bitwidth); } // instances scope if (line.hasOption(instOptions.getOpt())) { String assertionsArguments = "for " + line.getOptionValue(instOptions.getOpt()); overridingProperties.put(TacoConfigurator.ASSERTION_ARGUMENTS, assertionsArguments); } // Skolemize if (line.hasOption(skolemizeOption.getOpt())) { overridingProperties.put(TacoConfigurator.SKOLEMIZE_INSTANCE_INVARIANT, false); overridingProperties.put(TacoConfigurator.SKOLEMIZE_INSTANCE_ABSTRACTION, false); } // Simulation if (line.hasOption(simulateOption.getOpt())) { overridingProperties.put(TacoConfigurator.INCLUDE_SIMULATION_PROGRAM_DECLARATION, true); overridingProperties.put(TacoConfigurator.GENERATE_CHECK, false); overridingProperties.put(TacoConfigurator.GENERATE_RUN, false); } // Modular Reasoning if (line.hasOption(modularReasoningOption.getOpt())) { overridingProperties.put(TacoConfigurator.MODULAR_REASONING, true); } // Relevancy Analysis if (line.hasOption(relevancyAnalysisOption.getOpt())) { overridingProperties.put(TacoConfigurator.RELEVANCY_ANALYSIS, true); } } catch (ParseException e) { System.err.println("Command line parsing failed: " + e.getMessage()); } try { System.out.println("****** Starting Taco (version. " + tacoVersion + ") ****** "); System.out.println(""); File file = new File("config/log4j.xml"); if (file.exists()) { DOMConfigurator.configure("config/log4j.xml"); } else { System.err.println("log4j:WARN File config/log4j.xml not found"); } TacoMain main = new TacoMain(); // BUILD TacoScope // main.run(configFileArgument, overridingProperties); } catch (IllegalArgumentException e) { System.err.println("Error found:"); System.err.println(e.getMessage()); } catch (MethodToCheckNotFoundException e) { System.err.println("Error found:"); System.err.println("Method to check was not found. Please verify config file, or add -m option"); } catch (TacoException e) { System.err.println("Error found:"); System.err.println(e.getMessage()); } }
From source file:Main.java
public static Properties getProperties(String string) { Properties properties = new Properties(); try {//from ww w . jav a2 s .com properties.load(new StringReader(string)); } catch (IOException e) { e.printStackTrace(); } return properties; }