List of usage examples for java.util Properties getProperty
public String getProperty(String key)
From source file:com.barclays.dfe.fw.DFEWatcher.java
/** * Main entry point for application.//from ww w . jav a 2 s . co m * * @param args the arguments * @throws DFEException the DFE exception */ public static void main(String[] args) throws DFEException { Properties properties = System.getProperties(); String usage; //Package pkg = org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.class.getPackage(); //Package pkg = DFEWatcher.class.getPackage().getImplementationTitle(); //String ver = pkg.getImplementationVersion(); String impVer = DFEWatcher.class.getPackage().getImplementationVersion(); String impTitle = DFEWatcher.class.getPackage().getImplementationTitle(); String impVendor = DFEWatcher.class.getPackage().getImplementationVendor(); String specVer = DFEWatcher.class.getPackage().getSpecificationVersion(); String specTitle = DFEWatcher.class.getPackage().getSpecificationTitle(); String specVendor = DFEWatcher.class.getPackage().getSpecificationVendor(); //String ver = pkg.getImplementationVersion(); usage = "\nProduct: " + impTitle + "\nVersion: " + impVer + "\nVendor:" + impVendor; System.out.println("Barclays DTU File Express (DFE) (C) 2014 - Designed and Written by Barclays GTIS"); System.out.println(usage); System.out.printf("DFE is using Java Runtime Version: %s VM: %s Runtime:%s\n\n", properties.getProperty("java.version"), properties.getProperty("java.vm.version"), properties.getProperty("java.runtime.version")); // Run the main class here - start logging here // Load the config file - mandatory - should also contain the name of the XML for the props DFEProps.getDFEProps(); Logger logger = LoggerFactory.getLogger(DFEWatcher.class); logger.debug("Thread mulitplier {}", DFEProps.DFEThreadMultipler); DFEShutdownGraceful gs = new DFEShutdownGraceful(); gs.attachShutDownHook(); // create the command line parser - this is the main entry point to detect how we want to invoke the client CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); // boolean options options.addOption("h", "help", false, "General Help Page - this screen!"); options.addOption("wm", "WaitMode", false, "Run the DFE Client as a service and watched folder mode"); options.addOption("j", "TestJython", false, "Test a Jython Script"); options.addOption("sf", "SourceFile", false, "Test a Jython Script - Source File"); options.addOption("tf", "TargetFile", false, "Test a Jython Script - Target File"); options.addOption("lc", "LogConfig", false, "Print out the full log, system and DFE configuration for the client"); options.addOption("v", "version", false, "Build version of this client Major.Minor.Build"); options.addOption("jetty", "jetty", false, "Start the Jetty Server for testing"); if (args.length == 0) { printUsage("DFEclient" + " (Posix)", options, System.out); printHelp(options); System.exit(0); } try { int argsfound = 0; // parse the command line arguments line = parser.parse(options, args, true); // Pass down all the options if (line.hasOption("help") && args.length == 1) { printUsage("DFEclient" + " (Posix)", options, System.out); printHelp(options); System.exit(0); } if (line.hasOption("jetty")) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); StatusPrinter.print(lc); // Out put logging capability logger.info("System Config {} ", properties); //logger.info("DFE Client Config {} ",props.toString()); Server server = new Server(Integer.parseInt(DFEProps.getDFEAdminPort())); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/util"); server.setHandler(context); context.addServlet(new ServletHolder(new DFEServlet()), "/*"); context.addServlet(new ServletHolder(new DFEServlet("stop")), "/start/*"); context.addServlet(new ServletHolder(new DFEServlet("start")), "/stop/*"); context.addServlet(new ServletHolder(new DFEServlet("status")), "/status/*"); try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.debug("Completed"); System.exit(0); } if (line.hasOption("lc")) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); StatusPrinter.print(lc); // Out put logging capability logger.info("System Config {} ", properties); DFEProps props = new DFEProps(); logger.info("DFE Client Config {} ", props.toString()); System.exit(0); } // Launch a Jython script to test the engine if (line.hasOption("j")) { DFETransferContext DFE = new DFETransferContext(); String sf = line.getOptionValue("sf"); String tf = line.getOptionValue("tf"); logger.info("System Config {} ", properties); DFEProps props = new DFEProps(); logger.info("DFE Client Config {} ", props.toString()); DFE.setDFESourceFile(sf); DFE.setDFETransferMode("put"); DFE.setDFETargetFileName(tf); String scriptName = line.getOptionValue("j"); argsfound++; logger.debug("Jython Script now executed {}", scriptName); DFEScriptEngine se = new DFEScriptEngine(); int result = se.RunPython(scriptName, DFE); logger.debug("Result from Jython Script {}", result); System.exit(0); } if (line.hasOption("v")) { logger.info(usage); System.exit(0); } // // Call this by default - this will be the main folder watcher // if (line.hasOption("wm")) { // Chek the status of the hub - and fail if we dont see it TODO - something better try { DFEUtils.DFECheckHub(); // Check the hub - if we get a fauilure - we } catch (Exception e) { System.exit(DFEProps.getDFEErrorReturnCode("DFE_HUB_ATTACH_ERROR")); } logger.info("All active propserties from DFE.properties"); DFEProps.printActiveProperties(); logger.info("End of Property List"); DFETransferContext dtx = new DFETransferContext(); DFEStatus stat = new DFEStatus(); logger.debug("Starting watched folder mode as a service"); argsfound++; try { // Shift the args to the left and remove -wm String[] newArgs; newArgs = new String[args.length - 1]; int i; for (i = 0; i < args.length - 1; i++) { newArgs[i] = args[i + 1]; } // Start the jetty server if admin port is non zero if (Integer.parseInt(DFEProps.DFEAdminPort) != 0) { // Start the Jetty server here logger.info("Starting Embedded JETTY server on {} /util ", DFEProps.DFEAdminPort); DFEJetty jettyServer = new DFEJetty(); EventQueue.invokeLater(jettyServer); } DFEScriptEngine se = new DFEScriptEngine(); logger.info("Starting startup.py script"); //String scriptName = DFEProps.DFEStartupScript; // Add the startup script location String scriptName = DFEProps.getDFEScriptsDir() + "//" + DFEProps.getDFEStartupScript(); //String scriptName = "startup.py"; dtx.setDFETransferMode("startup"); int result = se.RunPython(scriptName, dtx); //int result=0; if (result != 0) { logger.info("Startup script has terminated the application with error code {}", result); System.exit(0); } logger.info("Registering startup on log"); stat.registerStartup(true); // register the startup in log file logger.info("Starting watcher service"); DFEMasterRunState.startWatcher(); // Set the state flag try { JFileWatcherService.runWaitMode(newArgs); } catch (Exception e) { System.out.println("Exit from watcher"); logger.info("Graceful exit"); } logger.info("Terminating Watcher Service"); System.exit(0); } catch (Exception e) { // TODO Auto-generated catch block logger.error("Cannot start File Watcher Service: ", e); System.exit(-10); } logger.debug("Wait mode complete - exiting DFE Java Client"); } if (line.hasOption("im")) { logger.debug("Interactive mode complete - exiting DFE Java Client"); } if (argsfound == 0) { logger.error("Error: Unknown argument"); printUsage("DFEclient" + " (Posix)", options, System.out); printHelp(options); System.exit(0); System.exit(-8); } } // Catch the argument parser - here - only on a start catch (Exception exp) { logger.warn("Error in argument parsing {}", exp.toString()); System.exit(-9); } }
From source file:com.marklogic.client.example.util.Bootstrapper.java
/** * Command-line invocation.//from w w w .j a v a 2 s.com * @param args command-line arguments specifying the configuration and REST server */ public static void main(String[] args) throws ClientProtocolException, IOException, FactoryConfigurationError { Properties properties = new Properties(); for (int i = 0; i < args.length; i++) { String name = args[i]; if (name.startsWith("-") && name.length() > 1 && ++i < args.length) { name = name.substring(1); if ("properties".equals(name)) { InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name); if (propsStream == null) throw new IOException("Could not read bootstrapper properties"); Properties props = new Properties(); props.load(propsStream); props.putAll(properties); properties = props; } else { properties.put(name, args[i]); } } else { System.err.println("invalid argument: " + name); System.err.println(getUsage()); System.exit(1); } } String invalid = joinList(listInvalidKeys(properties)); if (invalid != null && invalid.length() > 0) { System.err.println("invalid arguments: " + invalid); System.err.println(getUsage()); System.exit(1); } // TODO: catch invalid argument exceptions and provide feedback new Bootstrapper().makeServer(properties); System.out.println("Created " + properties.getProperty("restserver") + " server on " + properties.getProperty("restport") + " port for " + properties.getProperty("restdb") + " database"); }
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;// w ww .j a va2 s . c om 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:com.google.api.services.samples.youtube.cmdline.Topics.java
/** * Execute a search request that starts by calling the Freebase API to * retrieve a topic ID matching a user-provided term. Then initialize a * YouTube object to search for YouTube videos and call the YouTube Data * API's youtube.search.list method to retrieve a list of videos associated * with the selected Freebase topic and with another search query term, * which the user also enters. Finally, display the titles, video IDs, and * thumbnail images for the first five videos in the YouTube Data API * response./*ww w. j a v a 2 s .com*/ * * @param args This application does not use command line arguments. */ public static void main(String[] args) { // Read the developer key from the properties file. Properties properties = new Properties(); try { InputStream in = Topics.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); } try { // Retrieve a Freebase topic ID based on a user-entered query term. String topicsId = getTopicId(); if (topicsId.length() < 1) { System.out.println("No topic id will be applied to your search."); } // Prompt the user to enter a search query term. This term will be // used to retrieve YouTube search results related to the topic // selected above. String queryTerm = getInputQuery("search"); // This object is used to make YouTube Data API requests. The last // argument is required, but since we don't need anything // initialized when the HttpRequest is initialized, we override // the interface and provide a no-op function. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException { } }).setApplicationName("youtube-cmdline-search-sample").build(); YouTube.Search.List search = youtube.search().list("id,snippet"); // Set your developer key from the Google Developers Console for // non-authenticated requests. See: // https://cloud.google.com/console String apiKey = properties.getProperty("youtube.apikey"); search.setKey(apiKey); search.setQ(queryTerm); if (topicsId.length() > 0) { search.setTopicId(topicsId); } // Restrict the search results to only include videos. See: // https://developers.google.com/youtube/v3/docs/search/list#type search.setType("video"); // To increase efficiency, only retrieve the fields that the // application uses. search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); if (searchResultList != null) { prettyPrint(searchResultList.iterator(), queryTerm, topicsId); } else { System.out.println("There were no results for your query."); } } catch (GoogleJsonResponseException e) { System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); e.printStackTrace(); } }
From source file:com.google.api.services.samples.youtube.cmdline.data.Topics.java
/** * Execute a search request that starts by calling the Freebase API to * retrieve a topic ID matching a user-provided term. Then initialize a * YouTube object to search for YouTube videos and call the YouTube Data * API's youtube.search.list method to retrieve a list of videos associated * with the selected Freebase topic and with another search query term, * which the user also enters. Finally, display the titles, video IDs, and * thumbnail images for the first five videos in the YouTube Data API * response.//w w w . j av a2 s . co m * * @param args This application does not use command line arguments. */ public static void main(String[] args) { // Read the developer key from the properties file. Properties properties = new Properties(); try { InputStream in = Topics.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); } try { // Retrieve a Freebase topic ID based on a user-entered query term. String topicsId = getTopicId(); if (topicsId.length() < 1) { System.out.println("No topic id will be applied to your search."); } // Prompt the user to enter a search query term. This term will be // used to retrieve YouTube search results related to the topic // selected above. String queryTerm = getInputQuery("search"); // This object is used to make YouTube Data API requests. The last // argument is required, but since we don't need anything // initialized when the HttpRequest is initialized, we override // the interface and provide a no-op function. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException { } }).setApplicationName("youtube-cmdline-search-sample").build(); YouTube.Search.List search = youtube.search().list("id,snippet"); // Set your developer key from the {{ Google Cloud Console }} for // non-authenticated requests. See: // {{ https://cloud.google.com/console }} String apiKey = properties.getProperty("youtube.apikey"); search.setKey(apiKey); search.setQ(queryTerm); if (topicsId.length() > 0) { search.setTopicId(topicsId); } // Restrict the search results to only include videos. See: // https://developers.google.com/youtube/v3/docs/search/list#type search.setType("video"); // To increase efficiency, only retrieve the fields that the // application uses. search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); if (searchResultList != null) { prettyPrint(searchResultList.iterator(), queryTerm, topicsId); } else { System.out.println("There were no results for your query."); } } catch (GoogleJsonResponseException e) { System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); e.printStackTrace(); } }
From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics.java
/** * Method kicks off a search via the Freebase API for a topics id. It initializes a YouTube * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the * search more specific. The program then prints the names and thumbnails of each of the videos * (only first 5 videos). Please note, user input is taken for both search on Freebase and on * YouTube./*from ww w. j ava2s . c o m*/ * * @param args command line args not used. */ public static void main(String[] args) { // Read the developer key from youtube.properties Properties properties = new Properties(); try { InputStream in = Topics.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); } try { // Gets a topic id via the Freebase API based on user input. String topicsId = getTopicId(); if (topicsId.length() < 1) { System.out.println("No topic id will be applied to your search."); } /* * Get query term from user. The "search" parameter is just used as output to clarify that * we want a "search" term (vs. a "topics" term). */ String queryTerm = getInputQuery("search"); /* * The YouTube object is used to make all API requests. The last argument is required, but * because we don't need anything initialized when the HttpRequest is initialized, we * override the interface and provide a no-op function. */ youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException { } }).setApplicationName("youtube-cmdline-search-sample").build(); YouTube.Search.List search = youtube.search().list("id,snippet"); /* * It is important to set your developer key from the Google Developer Console for * non-authenticated requests (found under the API Access tab at this link: * code.google.com/apis/). This is good practice and increases your quota. */ String apiKey = properties.getProperty("youtube.apikey"); search.setKey(apiKey); search.setQ(queryTerm); if (topicsId.length() > 0) { search.setTopicId(topicsId); } /* * We are only searching for videos (not playlists or channels). If we were searching for * more, we would add them as a string like this: "video,playlist,channel". */ search.setType("video"); /* * This method reduces the info returned to only the fields we need. It makes things more * efficient, because we are transmitting less data. */ search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); if (searchResultList != null) { prettyPrint(searchResultList.iterator(), queryTerm, topicsId); } else { System.out.println("There were no results for your query."); } } catch (GoogleJsonResponseException e) { System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); e.printStackTrace(); } }
From source file:je3.rmi.MudClient.java
/** * This main() method is the standalone program that figures out what * database to connect to with what driver, connects to the database, * creates a PersistentBankServer object, and registers it with the registry, * making it available for client use/*from ww w .j a v a 2s. c om*/ **/ public static void main(String[] args) { try { // Create a new Properties object. Attempt to initialize it from // the BankDB.props file or the file optionally specified on the // command line, ignoring errors. Properties p = new Properties(); try { p.load(new FileInputStream(args[0])); } catch (Exception e) { try { p.load(new FileInputStream("BankDB.props")); } catch (Exception e2) {} } // The BankDB.props file (or file specified on the command line) // must contain properties "driver" and "database", and may // optionally contain properties "user" and "password". String driver = p.getProperty("driver"); String database = p.getProperty("database"); String user = p.getProperty("user", ""); String password = p.getProperty("password", ""); // Load the database driver class Class.forName(driver); // Connect to the database that stores our accounts Connection db = DriverManager.getConnection(database, user, password); // Configure the database to allow multiple queries and updates // to be grouped into atomic transactions db.setAutoCommit(false); db.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // Create a server object that uses our database connection PersistentBankServer bank = new PersistentBankServer(db); // Read a system property to figure out how to name this server. // Use "SecondRemote" as the default. String name = System.getProperty("bankname", "SecondRemote"); // Register the server with the name Naming.rebind(name, bank); // And tell everyone that we're up and running. System.out.println(name + " is open and ready for customers."); } catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException)e).getSQLState()); System.err.println("Usage: java [-Dbankname=<name>] " + "je3.rmi.PersistentBankServer " + "[<dbpropsfile>]"); System.exit(1); } }
From source file:com.strider.datadefender.DataDefender.java
@SuppressWarnings("unchecked") public static void main(final String[] args) throws ParseException, DatabaseDiscoveryException, IOException, SAXException, TikaException, java.text.ParseException, FileDiscoveryException { final long startTime = System.currentTimeMillis(); // Ensure we are not trying to run second instance of the same program final ApplicationLock al = new ApplicationLock("DataDefender"); if (al.isAppActive()) { LOG.error("Another instance of this program is already active"); displayExecutionTime(startTime); System.exit(1);/*from www. j av a2s. c om*/ } LOG.info("Command-line arguments: " + Arrays.toString(args)); final Options options = createOptions(); final CommandLine line = getCommandLine(options, args); @SuppressWarnings("unchecked") List<String> unparsedArgs = line.getArgList(); if (line.hasOption("help") || (args.length == 0) || (unparsedArgs.size() < 1)) { help(options); displayExecutionTime(startTime); return; } if (line.hasOption("debug")) { LogManager.getRootLogger().setLevel(Level.DEBUG); } else { LogManager.getRootLogger().setLevel(Level.INFO); } final String cmd = unparsedArgs.get(0); // get & remove command arg unparsedArgs = unparsedArgs.subList(1, unparsedArgs.size()); List<String> errors = new ArrayList(); if ("file-discovery".equals(cmd)) { errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String fileDiscoveryPropertyFile = line.getOptionValue('F', "filediscovery.properties"); final Properties fileDiscoveryProperties = loadPropertiesFromClassPath(fileDiscoveryPropertyFile); final FileDiscoverer discoverer = new FileDiscoverer(); discoverer.discover(fileDiscoveryProperties); displayExecutionTime(startTime); return; } // Get db properties file from command line argument or use default db.properties final String dbPropertiesFile = line.getOptionValue('P', "db.properties"); errors = PropertyCheck.checkDtabaseProperties(dbPropertiesFile); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final Properties props = loadProperties(dbPropertiesFile); try (final IDBFactory dbFactory = IDBFactory.get(props);) { switch (cmd) { case "anonymize": errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String anonymizerPropertyFile = line.getOptionValue('A', "anonymizer.properties"); final Properties anonymizerProperties = loadProperties(anonymizerPropertyFile); final IAnonymizer anonymizer = new DatabaseAnonymizer(); anonymizer.anonymize(dbFactory, anonymizerProperties); break; case "generate": errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final IGenerator generator = new DataGenerator(); final String generatorPropertyFile = line.getOptionValue('A', "anonymizer.properties"); final Properties generatorProperties = loadProperties(generatorPropertyFile); generator.generate(dbFactory, generatorProperties); break; case "database-discovery": if (line.hasOption('c')) { errors = PropertyCheck.check(cmd, 'c'); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String columnPropertyFile = line.getOptionValue('C', "columndiscovery.properties"); final Properties columnProperties = loadProperties(columnPropertyFile); final ColumnDiscoverer discoverer = new ColumnDiscoverer(); discoverer.discover(dbFactory, columnProperties, props.getProperty("vendor")); if (line.hasOption('r')) { discoverer.createRequirement("Sample-Requirement.xml"); } } else if (line.hasOption('d')) { errors = PropertyCheck.check(cmd, 'd'); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String datadiscoveryPropertyFile = line.getOptionValue('D', "datadiscovery.properties"); final Properties dataDiscoveryProperties = loadProperties(datadiscoveryPropertyFile); final DatabaseDiscoverer discoverer = new DatabaseDiscoverer(); discoverer.discover(dbFactory, dataDiscoveryProperties, props.getProperty("vendor")); if (line.hasOption('r')) { discoverer.createRequirement("Sample-Requirement.xml"); } } break; default: help(options); break; } } displayExecutionTime(startTime); }
From source file:de.uniwue.info2.main.CommandLineInterpreter.java
@SuppressWarnings("static-access") public static void main(String[] args) { /*-------------------------------------------------------- */ /*---------------SETTING TARGET LANGUAGE------------------ */ /*-------------------------------------------------------- */ LanguageFactory languageFactory = new LanguageFactory(); CommandLine line = null;//from w w w . java 2 s. co m CommandLineParser parser = new BasicParser(); Options options = new Options(); // options to display in the help page Options options_short = new Options(); // add help option Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION); options.addOption(help_option); options_short.addOption(help_option); // add extended help option Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION); options.addOption(help2_option); options_short.addOption(help2_option); // add optional operations option options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION)); options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION)); options.addOption( new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION)); // add optional operations config option options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION) .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT) .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg() .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT)); // add dsl option Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT) .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT); options.addOption(dsl_option); options_short.addOption(dsl_option); // add output-folder option Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT) .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT); options.addOption(output_option); options_short.addOption(output_option); // count possible language-specifications short optionCounter = 1; // get all possible language-specifications from language-factory and iterate through them List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_(); for (LanguageSpecification lSpec : lSpecs) { // get all possible unit-specifications for current language and iterate through them List<UnitTestLibrarySpecification> uSpecs = languageFactory .getAvailableUnitTestLibraries_(lSpec.getOptionName()); String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName(); String languageCounter = "s" + INDEX.format(optionCounter++); for (UnitTestLibrarySpecification uSpec : uSpecs) { // get all possible arithmetic-library-specifications for current language and iterate through // them List<ArithmeticLibrarySpecification> aSpecs = languageFactory .getAvailableArithmeticLibraries_(lSpec.getOptionName()); for (ArithmeticLibrarySpecification aSpec : aSpecs) { String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*[" + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName() + " - " + aSpec.getVersion() + "]"; // if there is more than one option, generate suitable option-names and add them all to // commandline options if (uSpecs.size() > 1 || aSpecs.size() > 1) { options.addOption(OptionBuilder .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_" + aSpec.getOptionName()) .withDescription(languageDescription).hasArg(false) .create("s" + INDEX.format(optionCounter++))); } else { // if there is only one option, use language-name as option-name languageDescriptionAll = languageDescription; } } // add specifications to options options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName()) .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter)); } } /*-------------------------------------------------------- */ /*-------------------PARSE USER INPUT--------------------- */ /*-------------------------------------------------------- */ try { // manual search for help-arguments for (String arg : args) { arg = arg.trim().replace("-", ""); if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) { printHelp(options_short); return; } if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) { printExtendedHelp(options); return; } } // parse arguments line = parser.parse(options, args); File dsl_file = null; File output_folder = null; File optional_config = null; Properties optional_operations = null; Boolean optional = false; Boolean little_endian = null; ArrayList<String> optional_exceptions = new ArrayList<String>(); // if help-option found print help if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) { printExtendedHelp(options); return; } // if help-option found print help if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) { System.out.println("\n"); printHelp(options_short); return; } if (line.hasOption(OPTIONAL_OPTION_SHORT)) { optional = true; } if (line.hasOption(LITTLE_ENDIAN_OPTION)) { little_endian = true; } if (line.hasOption(BIG_ENDIAN_OPTION)) { little_endian = false; } // if dsl-option found, check if file exists and is readable // print help if error occurs if (line.hasOption(DSL_OPTION_SHORT)) { dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT)); if (!dsl_file.exists()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file + "\n" + SEPERATOR + "\n"); printHelp(options_short); return; } else if (dsl_file.isDirectory()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file + "\n" + SEPERATOR + "\n"); printHelp(options_short); return; } else if (!dsl_file.canRead()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n" + dsl_file + "\n" + SEPERATOR + "\n"); printHelp(options_short); return; } } // if output-option found, check if folder exists and if write-permission was granted // print help if error occurs if (line.hasOption(OUTPUT_OPTION_SHORT)) { output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT)); if (!output_folder.exists()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n" + output_folder + "\n" + SEPERATOR + "\n"); printHelp(options_short); return; } else if (!output_folder.isDirectory()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n" + output_folder + "\n" + SEPERATOR + "\n"); printHelp(options_short); return; } else if (!output_folder.canWrite() || !output_folder.canRead()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n" + output_folder + "\n" + SEPERATOR + "\n"); printHelp(options_short); return; } } if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) { optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION)); if (!dsl_file.exists()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file + "\n" + SEPERATOR + "\n"); printExtendedHelp(options); return; } else if (dsl_file.isDirectory()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file + "\n" + SEPERATOR + "\n"); printExtendedHelp(options); return; } else if (!dsl_file.canRead()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n" + dsl_file + "\n" + SEPERATOR + "\n"); printExtendedHelp(options); return; } } if (optional_config != null) { optional_operations = new Properties(); BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config)); optional_operations.load(stream); stream.close(); String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL"); if (optional_prop != null) { if (optional_prop.trim().toLowerCase().equals("true")) { optional = true; } else if (optional_prop.trim().toLowerCase().equals("false")) { optional = false; } else if (!optional_prop.trim().isEmpty()) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n" + SEPERATOR + "\n"); printExtendedHelp(options); return; } } String exceptions = optional_operations.getProperty("EXCLUSIONS"); if (exceptions != null) { for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) { optional_exceptions.add(exc.trim()); } } } /*-------------------------------------------------------- */ /*-------------------START GENERATING--------------------- */ /*-------------------------------------------------------- */ // instantiate generator for unit-tests TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder); boolean overrideDefaultSpecs = false; // check if user input contains a language-specifications // if user specified language, set overrideDefaultSpecs to true, so that only given specifications // are used for (int i = 1; i <= optionCounter; i++) { String opt = "s" + INDEX.format(i); if (line.hasOption(opt)) { LanguageSpecification targetSpecification = languageFactory .getLanguageSpecification(options.getOption(opt).getLongOpt()); String output = (GENERATING_DIALOG + targetSpecification.getLanguageName()); // finally generate unit-test for current language-specification boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional, optional_exceptions, little_endian); if (successful) { System.out.println(output + "\n--> Successfully generated."); } else { System.err.println(output + "\n--> ERROR - see logfile"); } overrideDefaultSpecs = true; } } // skip, if user already defined one language-specification // if user did not define language-specification, generate unit-tests for all // possible language-specifications (default) if (!overrideDefaultSpecs) { for (int i = 0; i < lSpecs.size(); i++) { LanguageSpecification specification = languageFactory .getLanguageSpecification(lSpecs.get(i).getOptionName()); String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG + specification.getLanguageName(); // finally generate unit-test for current language-specification boolean successful = mainGenerator.generateUnitTest(specification, optional, optional_exceptions, little_endian); if (successful) { System.out.println(output + "\n--> Successfully generated."); } else { System.err.println(output + "\n--> ERROR - see logfile"); } } } } catch (ParseException | IOException p) { System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n" + SEPERATOR + "\n"); printHelp(options_short); System.out.println("\n"); } }
From source file:Main.java
public static boolean isMacOs() { Properties prop = System.getProperties(); String os = prop.getProperty("os.name"); // log.info("platform is:"+os); if (os.equals("Mac OS X")) { return true; }//from www . ja v a2s.co m return false; }