List of usage examples for java.util Properties getProperty
public String getProperty(String key)
From source file:main.java.com.google.api.services.samples.youtube.cmdline.YouTubeSample.java
public static void main(String[] args) throws IOException { Properties properties = new Properties(); try {/*from ww w. j a v a 2s. co m*/ InputStream in = YouTubeSample.class.getResourceAsStream("" + PROPERTIES_FILENAME); properties.load(in); } catch (IOException e) { System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : " + e.getMessage()); System.exit(1); } youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { @Override public void initialize(HttpRequest arg0) throws IOException { // TODO Auto-generated method stub } }).setApplicationName("youtubeTest").build(); YouTube.Videos.List videos = youtube.videos().list("snippet"); String apiKey = properties.getProperty("youtube.apikey"); videos.setKey(apiKey); videos.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); videos.setChart("mostPopular"); VideoListResponse response = videos.execute(); java.util.List<Video> videoList = response.getItems(); if (videoList != null) { prettyPrint(videoList.iterator()); } else { System.out.println("There were no results!"); } }
From source file:com.bah.applefox.main.Ingest.java
public static void main(String[] args) throws Exception { if (args.length == 1 && args[0].equals("--help")) { System.out.println("Not enough arguments"); System.out.println("Arguments should be in the format <properties file> <command>"); System.out.println("Valid commands:"); System.out.println("\tpr: Calculates Page Rank"); System.out.println("\timageload: Loads Images from URLs"); System.out.println("\tload: Loads Full Text Data"); System.out.println("\tingest: Ingests URLs from given seed"); System.out.println("\tftsample: Creates a Full Text Index Sample HashMap"); System.out.println("\timagesample: Creates an Image Hash and Image Tag Sample HashMap"); }//from w w w . ja v a 2 s . co m if (args.length > 2) { System.out.println("2 Arguments expected, " + args.length + " given."); } if (args.length < 2) { System.out.println("Not enough arguments"); System.out.println("Arguments should be in the format <properties file> <command>"); System.out.println("Valid commands:"); System.out.println("\tpr: Calculates Page Rank"); System.out.println("\timageload: Loads Images from URLs"); System.out.println("\tload: Loads Full Text Data"); System.out.println("\tingest: Ingests URLs from given seed"); System.out.println("\tftsample: Creates a Full Text Index Sample HashMap"); System.out.println("\timagesample: Creates an Image Hash and Image Tag Sample HashMap"); } injector = Guice.createInjector(new IngesterModule()); // The properties object to read from the configuration file Properties properties = new Properties(); try { // Load configuration file from the command line properties.load(new FileInputStream(args[0])); } catch (Exception e) { log.error("ABORT: File not found or could not read from file ->" + e.getMessage()); log.error("Enter the location of the configuration file"); System.exit(1); } // Initialize variables from configuration file // Accumulo Variables INSTANCE_NAME = properties.getProperty("INSTANCE_NAME"); ZK_SERVERS = properties.getProperty("ZK_SERVERS"); USERNAME = properties.getProperty("USERNAME"); PASSWORD = properties.getProperty("PASSWORD"); SPLIT_SIZE = properties.getProperty("SPLIT_SIZE"); NUM_ITERATIONS = Integer.parseInt(properties.getProperty("NUM_ITERATIONS")); NUM_NODES = Integer.parseInt(properties.getProperty("NUM_NODES")); // General Search Variables MAX_NGRAMS = Integer.parseInt(properties.getProperty("MAX_NGRAMS")); GENERAL_STOP = properties.getProperty("GENERAL_STOP"); // Full Text Variables FT_DATA_TABLE = properties.getProperty("FT_DATA_TABLE"); FT_SAMPLE = properties.getProperty("FT_SAMPLE"); FT_CHECKED_TABLE = properties.getProperty("FT_CHECKED_TABLE"); FT_DIVS_FILE = properties.getProperty("FT_DIVS_FILE"); FT_SPLIT_SIZE = properties.getProperty("FT_SPLIT_SIZE"); // Web Crawler Variables URL_TABLE = properties.getProperty("URL_TABLE"); SEED = properties.getProperty("SEED"); USER_AGENT = properties.getProperty("USER_AGENT"); URL_SPLIT_SIZE = properties.getProperty("URL_SPLIT_SIZE"); // Page Rank Variables PR_TABLE_PREFIX = properties.getProperty("PR_TABLE_PREFIX"); PR_URL_MAP_TABLE_PREFIX = properties.getProperty("PR_URL_MAP_TABLE_PREFIX"); PR_OUT_LINKS_COUNT_TABLE = properties.getProperty("PR_OUT_LINKS_COUNT_TABLE"); PR_FILE = properties.getProperty("PR_FILE"); PR_DAMPENING_FACTOR = Double.parseDouble(properties.getProperty("PR_DAMPENING_FACTOR")); PR_ITERATIONS = Integer.parseInt(properties.getProperty("PR_ITERATIONS")); PR_SPLIT_SIZE = properties.getProperty("PR_SPLIT_SIZE"); // Image Variables IMG_HASH_TABLE = properties.getProperty("IMG_HASH_TABLE"); IMG_CHECKED_TABLE = properties.getProperty("IMG_CHECKED_TABLE"); IMG_TAG_TABLE = properties.getProperty("IMG_TAG_TABLE"); IMG_HASH_SAMPLE_TABLE = properties.getProperty("IMG_HASH_SAMPLE_TABLE"); IMG_TAG_SAMPLE_TABLE = properties.getProperty("IMG_TAG_SAMPLE_TABLE"); IMG_SPLIT_SIZE = properties.getProperty("IMG_SPLIT_SIZE"); // Future Use: // Work Directory in HDFS WORK_DIR = properties.getProperty("WORK_DIR"); // Initialize variable from command line RUN = args[1].toLowerCase(); // Set the instance information for AccumuloUtils AccumuloUtils.setInstanceName(INSTANCE_NAME); AccumuloUtils.setInstancePassword(PASSWORD); AccumuloUtils.setUser(USERNAME); AccumuloUtils.setZooserver(ZK_SERVERS); AccumuloUtils.setSplitSize(SPLIT_SIZE); String[] temp = new String[25]; // Accumulo Variables temp[0] = INSTANCE_NAME; temp[1] = ZK_SERVERS; temp[2] = USERNAME; temp[3] = PASSWORD; // Number of Map Tasks temp[4] = Integer.toString((int) Math.ceil(1.75 * NUM_NODES * 2)); // Web Crawler Variables temp[5] = URL_TABLE; temp[6] = USER_AGENT; // Future Use temp[7] = WORK_DIR; // General Search temp[8] = GENERAL_STOP; temp[9] = Integer.toString(MAX_NGRAMS); // Full Text Variables temp[10] = FT_DATA_TABLE; temp[11] = FT_CHECKED_TABLE; // Page Rank Variables temp[12] = PR_URL_MAP_TABLE_PREFIX; temp[13] = PR_TABLE_PREFIX; temp[14] = Double.toString(PR_DAMPENING_FACTOR); temp[15] = PR_OUT_LINKS_COUNT_TABLE; temp[16] = PR_FILE; // Image Variables temp[17] = IMG_HASH_TABLE; temp[18] = IMG_CHECKED_TABLE; temp[19] = IMG_TAG_TABLE; temp[20] = FT_DIVS_FILE; // Table Split Sizes temp[21] = FT_SPLIT_SIZE; temp[22] = IMG_SPLIT_SIZE; temp[23] = URL_SPLIT_SIZE; temp[24] = PR_SPLIT_SIZE; if (RUN.equals("pr")) { // Run PR_ITERATIONS number of iterations for page ranking PageRank.createPageRank(temp, PR_ITERATIONS, URL_SPLIT_SIZE); } else if (RUN.equals("imageload")) { // Load image index AccumuloUtils.setSplitSize(URL_SPLIT_SIZE); ToolRunner.run(new ImageLoader(), temp); } else if (RUN.equals("ingest")) { // Ingest System.out.println("Ingesting"); // Set table split size AccumuloUtils.setSplitSize(URL_SPLIT_SIZE); // Write the seed value to the table BatchWriter w; Value v = new Value(); v.set("0".getBytes()); Mutation m = new Mutation(SEED); m.put("0", "0", v); w = AccumuloUtils.connectBatchWrite(URL_TABLE); w.addMutation(m); for (int i = 0; i < NUM_ITERATIONS; i++) { // Run the ToolRunner for NUM_ITERATIONS iterations ToolRunner.run(CachedConfiguration.getInstance(), injector.getInstance(Ingester.class), temp); } } else if (RUN.equals("load")) { // Parse the URLs and add to the data table AccumuloUtils.setSplitSize(URL_SPLIT_SIZE); BatchWriter w = AccumuloUtils.connectBatchWrite(FT_CHECKED_TABLE); w.close(); AccumuloUtils.setSplitSize(FT_SPLIT_SIZE); w = AccumuloUtils.connectBatchWrite(FT_DATA_TABLE); w.close(); ToolRunner.run(CachedConfiguration.getInstance(), injector.getInstance(Loader.class), temp); } else if (RUN.equals("ftsample")) { // Create a sample table for full text index FTAccumuloSampler ftSampler = new FTAccumuloSampler(FT_SAMPLE, FT_DATA_TABLE, FT_CHECKED_TABLE); ftSampler.createSample(); } else if (RUN.equals("imagesample")) { // Create a sample table for images ImageAccumuloSampler imgHashSampler = new ImageAccumuloSampler(IMG_HASH_SAMPLE_TABLE, IMG_HASH_TABLE, IMG_CHECKED_TABLE); imgHashSampler.createSample(); ImageAccumuloSampler imgTagSampler = new ImageAccumuloSampler(IMG_TAG_SAMPLE_TABLE, IMG_TAG_TABLE, IMG_CHECKED_TABLE); imgTagSampler.createSample(); } else { System.out.println("Invalid argument " + RUN + "."); System.out.println("Valid Arguments:"); System.out.println("\tpr: Calculates Page Rank"); System.out.println("\timageload: Loads Images from URLs"); System.out.println("\tload: Loads Full Text Data"); System.out.println("\tingest: Ingests URLs from given seed"); System.out.println("\tftsample: Creates a Full Text Index Sample HashMap"); System.out.println("\timagesample: Creates an Image Hash and Image Tag Sample HashMap"); } }
From source file:net.recommenders.plista.client.Client.java
/** * This method starts the server/* w w w. ja va 2 s. c o m*/ * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { final Properties properties = new Properties(); String fileName = ""; String recommenderClass = null; String handlerClass = null; if (args.length < 3) { fileName = System.getProperty("propertyFile"); } else { fileName = args[0]; recommenderClass = args[1]; handlerClass = args[2]; } // load the team properties try { properties.load(new FileInputStream(fileName)); } catch (IOException e) { logger.error(e.getMessage()); } catch (Exception e) { logger.error(e.getMessage()); } Recommender recommender = null; recommenderClass = (recommenderClass != null ? recommenderClass : properties.getProperty("plista.recommender")); System.out.println(recommenderClass); lognum = Integer.parseInt(properties.getProperty("plista.lognum")); try { final Class<?> transformClass = Class.forName(recommenderClass); recommender = (Recommender) transformClass.newInstance(); } catch (Exception e) { logger.error(e.getMessage()); throw new IllegalArgumentException("No recommender specified or recommender not available."); } // configure log4j /*if (args.length >= 4 && args[3] != null) { PropertyConfigurator.configure(args[0]); } else { PropertyConfigurator.configure("log4j.properties"); }*/ // set up and start server AbstractHandler handler = null; handlerClass = (handlerClass != null ? handlerClass : properties.getProperty("plista.handler")); System.out.println(handlerClass); try { final Class<?> transformClass = Class.forName(handlerClass); handler = (AbstractHandler) transformClass.getConstructor(Properties.class, Recommender.class) .newInstance(properties, recommender); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); throw new IllegalArgumentException("No handler specified or handler not available."); } final Server server = new Server(Integer.parseInt(properties.getProperty("plista.port", "8080"))); server.setHandler(handler); logger.debug("Serverport " + server.getConnectors()[0].getPort()); server.start(); server.join(); }
From source file:io.personium.recovery.Recovery.java
/** * main.//from w w w . j a v a 2s.c o m * @param args */ public static void main(String[] args) { loadProperties(); Option optIndex = new Option("i", "index", true, "?"); Option optProp = new Option("p", "prop", true, ""); // t?????????????????????? Option optType = new Option("t", "type", true, "??type"); Option optClear = new Option("c", "clear", false, "???elasticsearch?"); Option optReplicas = new Option("r", "replicas", true, "??"); Option optVersion = new Option("v", "version", false, "??"); // // optIndex.setRequired(true); // optProp.setRequired(true); Options options = new Options(); options.addOption(optIndex); options.addOption(optProp); options.addOption(optType); options.addOption(optClear); options.addOption(optReplicas); options.addOption(optVersion); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args, true); } catch (ParseException e) { (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options); log.warn("Recovery failure"); System.exit(1); } if (commandLine.hasOption("v")) { log.info("Version:" + versionNumber); System.exit(0); } if (!commandLine.hasOption("p")) { (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options); log.warn("Recovery failure"); System.exit(1); } if (commandLine.hasOption("t")) { log.info("Command line option \"t\" or \"type\" is deprecated. Option ignored."); } if (!commandLine.hasOption("r")) { (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options); log.warn("Command line option \"r\" is required."); System.exit(1); } RecoveryManager recoveryManager = new RecoveryManager(); // ??index recoveryManager.setIndexNames(commandLine.getOptionValue("i")); // elasticsearch recoveryManager.setClear(commandLine.hasOption("c")); // ?? // 0 ?ES??????????int??????? try { int replicas = Integer.parseInt(commandLine.getOptionValue("r")); if (replicas < 0) { log.warn("Command line option \"r\"'s value is not integer."); System.exit(1); } recoveryManager.setReplicas(replicas); } catch (NumberFormatException e) { log.warn("Command line option \"r\"'s value is not integer."); System.exit(1); } try { // Properties? Properties properties = new Properties(); // ? properties.load(new FileInputStream(commandLine.getOptionValue("p"))); if ((!properties.containsKey(ES_HOSTS)) || (!properties.containsKey(ES_CLUSTER_NAME)) || (!properties.containsKey(ADS_JDBC_URL)) || (!properties.containsKey(ADS_JDBC_USER)) || (!properties.containsKey(ADS_JDBC_PASSWORD)) || (!properties.containsKey(ES_ROUTING_FLAG))) { log.warn("properties file error"); log.warn("Recovery failure"); System.exit(1); } else { recoveryManager.setEsHosts(properties.getProperty(ES_HOSTS)); recoveryManager.setEsClusetrName(properties.getProperty(ES_CLUSTER_NAME)); recoveryManager.setAdsJdbcUrl(properties.getProperty(ADS_JDBC_URL)); recoveryManager.setAdsUser(properties.getProperty(ADS_JDBC_USER)); recoveryManager.setAdsPassword(properties.getProperty(ADS_JDBC_PASSWORD)); recoveryManager.setExecuteCnt(properties.getProperty(EXECUTE_COUNT)); recoveryManager.setCheckCount(properties.getProperty(CHECK_COUNT)); recoveryManager.setUnitPrefix(properties.getProperty(UNIT_PREFIX)); } } catch (FileNotFoundException e) { e.printStackTrace(); log.warn("properties file error"); log.warn("Recovery failure"); System.exit(1); } catch (IOException e) { e.printStackTrace(); log.warn("properties file error"); log.warn("Recovery failure"); System.exit(1); } String[] indexList = recoveryManager.getIndexNames(); boolean isClear = recoveryManager.isClear(); if (isClear && (indexList != null && null != indexList[0])) { String ad = recoveryManager.getUnitPrefix() + "_" + EsIndex.CATEGORY_AD; if (Arrays.asList(indexList).contains(ad)) { log.warn("Cannot specify both -c and -i " + recoveryManager.getUnitPrefix() + "_ad option."); log.warn("Recovery failure"); System.exit(1); } } // ?????? try { LockUtility.lock(); } catch (AlreadyStartedException e) { log.info("Recovery has already started"); log.info("Recovery failure"); return; } catch (Exception e) { log.error("Failed to get lock for the double start control"); e.printStackTrace(); LockUtility.release(); log.error("Recovery failure"); System.exit(1); } // ?? try { recoveryManager.recovery(); } catch (Exception e) { LockUtility.release(); log.error("Recovery failure"); System.exit(1); } LockUtility.release(); log.info("Recovery Success"); return; }
From source file:ab.demo.MainEntry.java
public static void main(String args[]) { LoggingHandler.initConsoleLog();//from w ww.ja v a2 s . co m //args = new String[]{"-su"}; Options options = new Options(); options.addOption("s", "standalone", false, "runs the reinforcement learning agent in standalone mode"); options.addOption("p", "proxyPort", true, "the port which is to be used by the proxy"); options.addOption("h", "help", false, "displays this help"); options.addOption("n", "naiveAgent", false, "runs the naive agent in standalone mode"); options.addOption("c", "competition", false, "runs the naive agent in the server/client competition mode"); options.addOption("u", "updateDatabaseTables", false, "executes CREATE TABLE IF NOT EXIST commands"); options.addOption("l", "level", true, "if set the agent is playing only in this one level"); options.addOption("m", "manual", false, "runs the empirical threshold determination agent in standalone mode"); options.addOption("r", "real", false, "shows the recognized shapes in a new frame"); CommandLineParser parser = new DefaultParser(); CommandLine cmd; StandaloneAgent agent; Properties properties = new Properties(); InputStream configInputStream = null; try { Class.forName("org.sqlite.JDBC"); //parse configuration file configInputStream = new FileInputStream("config.properties"); properties.load(configInputStream); } catch (IOException exception) { exception.printStackTrace(); } catch (ClassNotFoundException exception) { exception.printStackTrace(); } finally { if (configInputStream != null) { try { configInputStream.close(); } catch (IOException exception) { exception.printStackTrace(); } } } String dbPath = properties.getProperty("db_path"); String dbUser = properties.getProperty("db_user"); String dbPass = properties.getProperty("db_pass"); DBI dbi = new DBI(dbPath, dbUser, dbPass); QValuesDAO qValuesDAO = dbi.open(QValuesDAO.class); GamesDAO gamesDAO = dbi.open(GamesDAO.class); MovesDAO movesDAO = dbi.open(MovesDAO.class); ProblemStatesDAO problemStatesDAO = dbi.open(ProblemStatesDAO.class); try { cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } int proxyPort = 9000; if (cmd.hasOption("proxyPort")) { proxyPort = Integer.parseInt(cmd.getOptionValue("proxyPort")); logger.info("Set proxy port to " + proxyPort); } Proxy.setPort(proxyPort); LoggingHandler.initFileLog(); if (cmd.hasOption("standalone")) { agent = new ReinforcementLearningAgent(gamesDAO, movesDAO, problemStatesDAO, qValuesDAO); } else if (cmd.hasOption("naiveAgent")) { agent = new NaiveStandaloneAgent(); } else if (cmd.hasOption("manual")) { agent = new ManualGamePlayAgent(gamesDAO, movesDAO, problemStatesDAO); } else if (cmd.hasOption("competition")) { System.out.println("We haven't implemented a competition ready agent yet."); return; } else { System.out.println("Please specify which solving strategy we should be using."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } if (cmd.hasOption("updateDatabaseTables")) { qValuesDAO.createTable(); gamesDAO.createTable(); movesDAO.createTable(); problemStatesDAO.createTable(); problemStatesDAO.createObjectsTable(); } if (cmd.hasOption("level")) { agent.setFixedLevel(Integer.parseInt(cmd.getOptionValue("level"))); } if (cmd.hasOption("real")) { ShowSeg.useRealshape = true; Thread thread = new Thread(new ShowSeg()); thread.start(); } } catch (UnrecognizedOptionException e) { System.out.println("Unrecognized commandline option: " + e.getOption()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } catch (ParseException e) { System.out.println( "There was an error while parsing your command line input. Did you rechecked your syntax before running?"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } agent.run(); }
From source file:com.openx.oauthdemo.Demo.java
/** * Main class. OX3 with OAuth demo//from w ww. j av a2 s.co m * @param args */ public static void main(String[] args) { String apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl, accessTokenUrl, realm, authorizeUrl; String propertiesFile = "default.properties"; // load params from the properties file Properties defaultProps = new Properties(); InputStream in = null; try { ClassLoader cl = ClassLoader.getSystemClassLoader(); in = cl.getResourceAsStream(propertiesFile); if (in != null) { defaultProps.load(in); } } catch (IOException ex) { System.out.println("The properties file was not found!"); return; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { System.out.println("IO Error closing the properties file"); return; } } } if (defaultProps.isEmpty()) { System.out.println("The properties file was not loaded!"); return; } apiKey = defaultProps.getProperty("apiKey"); apiSecret = defaultProps.getProperty("apiSecret"); loginUrl = defaultProps.getProperty("loginUrl"); username = defaultProps.getProperty("username"); password = defaultProps.getProperty("password"); domain = defaultProps.getProperty("domain"); path = defaultProps.getProperty("path"); requestTokenUrl = defaultProps.getProperty("requestTokenUrl"); accessTokenUrl = defaultProps.getProperty("accessTokenUrl"); realm = defaultProps.getProperty("realm"); authorizeUrl = defaultProps.getProperty("authorizeUrl"); // log in to the server Client cl = new Client(apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl, accessTokenUrl, realm, authorizeUrl); try { // connect to the server cl.OX3OAuth(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "UTF-8 support needed for OAuth", ex); } catch (IOException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "IO file reading error", ex); } catch (Exception ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "API issue", ex); } // now lets make a call to the api to check String json; try { json = cl.getHelper().callOX3Api(domain, path, "account"); } catch (IOException ex) { System.out.println("There was an error calling the API"); return; } System.out.println("JSON response: " + json); Gson gson = new Gson(); int[] accounts = gson.fromJson(json, int[].class); if (accounts.length > 0) { // let's get a single account try { json = cl.getHelper().callOX3Api(domain, path, "account", accounts[0]); } catch (IOException ex) { System.out.println("There was an error calling the API"); return; } System.out.println("JSON response: " + json); OX3Account account = gson.fromJson(json, OX3Account.class); System.out.println("Account id: " + account.getId() + " name: " + account.getName()); } }
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method.//ww w. ja va 2 s . co m */ 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:com.msc.dao.facturierswing.Main.java
/** * @param args the command line arguments *//*from www .j a va 2s .co m*/ public static void main(String args[]) throws FileNotFoundException, IOException { Properties prop = new Properties(); Reader r = new FileReader("./config.properties"); prop.load(r); r.close(); WebService.prop = prop; WebService.setDebugMode(Boolean.parseBoolean(prop.getProperty("debugMode"))); Request request = new Request("login", "login"); try { Response s = request.sendRequest(); s.consumeToken(); request.setEndpoint("moi"); request.setUrlSuite("existe"); s = request.sendRequest(); java.lang.reflect.Type fooType = new TypeToken<Helper<Boolean>>() { }.getType(); Helper<Boolean> b = (Helper<Boolean>) s.getObject(null, fooType); firstTime = !b.getMyObject(); } catch (MalformedURLException | IllegalArgumentException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Main().setVisible(true); } }); }
From source file:hu.bme.mit.sette.run.Run.java
public static void main(String[] args) { LOG.debug("main() called"); // parse properties Properties prop = new Properties(); InputStream is = null;/*from w w w . ja v a 2s. c o m*/ try { is = new FileInputStream(SETTE_PROPERTIES); prop.load(is); } catch (IOException e) { System.err.println("Parsing " + SETTE_PROPERTIES + " has failed"); e.printStackTrace(); System.exit(1); } finally { IOUtils.closeQuietly(is); } String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|'); String snippetDir = prop.getProperty("snippet-dir"); String snippetProject = prop.getProperty("snippet-project"); String catgPath = prop.getProperty("catg"); String catgVersionFile = prop.getProperty("catg-version-file"); String jPETPath = prop.getProperty("jpet"); String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml"); String jPETVersionFile = prop.getProperty("jpet-version-file"); String spfPath = prop.getProperty("spf"); String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml"); String spfVersionFile = prop.getProperty("spf-version-file"); String outputDir = prop.getProperty("output-dir"); Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES); Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES); Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES); Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES); Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES); Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES); Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES); String basedir = null; for (String bd : basedirs) { bd = StringUtils.trimToEmpty(bd); if (bd.startsWith("~")) { // Linux home bd = System.getProperty("user.home") + bd.substring(1); } FileValidator v = new FileValidator(new File(bd)); v.type(FileType.DIRECTORY); if (v.isValid()) { basedir = bd; break; } } if (basedir == null) { System.err.println("basedir = " + Arrays.toString(basedirs)); System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES); System.exit(2); } BASEDIR = new File(basedir); SNIPPET_DIR = new File(basedir, snippetDir); SNIPPET_PROJECT = snippetProject; OUTPUT_DIR = new File(basedir, outputDir); try { String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile)); if (catgVersion != null) { new CatgTool(new File(BASEDIR, catgPath), catgVersion); } String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile)); if (jPetVersion != null) { new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion); } String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile)); if (spfVersion != null) { new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion); } // TODO stuff stuff(args); } catch (Exception e) { System.err.println(ExceptionUtils.getStackTrace(e)); ValidatorException vex = (ValidatorException) e; for (ValidationException v : vex.getValidator().getAllExceptions()) { v.printStackTrace(); } // System.exit(0); e.printStackTrace(); System.err.println("=========="); e.printStackTrace(); if (e instanceof ValidatorException) { System.err.println("Details:"); System.err.println(((ValidatorException) e).getFullMessage()); } else if (e.getCause() instanceof ValidatorException) { System.err.println("Details:"); System.err.println(((ValidatorException) e.getCause()).getFullMessage()); } } }
From source file:edu.hku.sdb.driver.SdbDriver.java
/** * @param args/* w ww .j a va 2 s . co m*/ */ public static void main(String[] args) { CommandLine line = parseAndValidateInput(args); String confDir = line.getOptionValue(CONF); Properties properties = line.getOptionProperties("D"); File sdbConnectionConfigFile = new File(confDir + "/" + ConnectionConf.CONF_FILE); File sdbServerConfigFile = new File(confDir + "/" + ServerConf.CONF_FILE); File sdbMetadbConfigFile = new File(confDir + "/" + MetadbConf.CONF_FILE); XMLPropParser propParser = new XMLPropParser(); // Parse all the sdb connection config Map<String, String> prop = propParser.importXML(sdbConnectionConfigFile); // Parse all the server config prop.putAll(propParser.importXML(sdbServerConfigFile)); // Parse all the metadb config prop.putAll(propParser.importXML(sdbMetadbConfigFile)); // Override the config if any Set<Object> states = properties.keySet(); // get set-view of keys for (Object object : states) { String key = (String) object; String value = properties.getProperty(key); prop.put(key, value); } // Cet log4j config PropertyConfigurator.configure(confDir + "/" + "log4j.properties"); ServerConf serverConf = ServerConfFactory.getServerConf(prop); MetadbConf metadbConf = MetadbConfFactory.getMetadbConf(prop); ConnectionConf connectionConf = new ConnectionConf(prop); SdbConf sdbConf = new SdbConf(connectionConf, serverConf, metadbConf); // Start the SDB proxy startConnectionPool(sdbConf); }