List of usage examples for java.util Properties load
public synchronized void load(InputStream inStream) throws IOException
From source file:io.s4.MainApp.java
public static void main(String args[]) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(/*from w w w .ja va2 s .co m*/ OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a")); options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d")); options.addOption(OptionBuilder.withArgName("seedtime").hasArg() .withDescription("event clock initialization time").create("s")); options.addOption( OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e")); options.addOption( OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; String clockType = "wall"; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } int instanceId = -1; if (commandLine.hasOption("i")) { String instanceIdStr = commandLine.getOptionValue("i"); try { instanceId = Integer.parseInt(instanceIdStr); } catch (NumberFormatException nfe) { System.err.println("Bad instance id: %s" + instanceIdStr); System.exit(1); } } if (commandLine.hasOption("c")) { coreHome = commandLine.getOptionValue("c"); } if (commandLine.hasOption("a")) { appsHome = commandLine.getOptionValue("a"); } if (commandLine.hasOption("d")) { clockType = commandLine.getOptionValue("d"); } if (commandLine.hasOption("e")) { extsHome = commandLine.getOptionValue("e"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } long seedTime = 0; if (commandLine.hasOption("s")) { seedTime = Long.parseLong(commandLine.getOptionValue("s")); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } File appsHomeFile = new File(appsHome); if (!appsHomeFile.isDirectory()) { System.err.println("Bad applications home: " + appsHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } List loArgs = commandLine.getArgList(); if (loArgs.size() < 1) { // System.err.println("No bean configuration file specified"); // System.exit(1); } // String s4ConfigXml = (String) loArgs.get(0); // System.out.println("s4ConfigXml is " + s4ConfigXml); ClassPathResource propResource = new ClassPathResource("s4-core.properties"); Properties prop = new Properties(); if (propResource.exists()) { prop.load(propResource.getInputStream()); } else { System.err.println("Unable to find s4-core.properties. It must be available in classpath"); System.exit(1); } ApplicationContext coreContext = null; String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = ""; List<String> coreConfigUrls = new ArrayList<String>(); File configFile = null; // load clock configuration configPath = configBase + File.separatorChar + clockType + "-clock.xml"; coreConfigUrls.add(configPath); // load core config xml configPath = configBase + File.separatorChar + "s4-core-conf.xml"; configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("S4 core config file %s does not exist\n", configPath); System.exit(1); } coreConfigUrls.add(configPath); String[] coreConfigFiles = new String[coreConfigUrls.size()]; coreConfigUrls.toArray(coreConfigFiles); String[] coreConfigFileUrls = new String[coreConfigFiles.length]; for (int i = 0; i < coreConfigFiles.length; i++) { coreConfigFileUrls[i] = "file:" + coreConfigFiles[i]; } coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext); ApplicationContext context = coreContext; Clock s4Clock = (Clock) context.getBean("clock"); if (s4Clock instanceof EventClock && seedTime > 0) { EventClock s4EventClock = (EventClock) s4Clock; s4EventClock.updateTime(seedTime); System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime()); } PEContainer peContainer = (PEContainer) context.getBean("peContainer"); Watcher w = (Watcher) context.getBean("watcher"); w.setConfigFilename(configPath); // load extension modules String[] configFileNames = getModuleConfigFiles(extsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); } // load application modules configFileNames = getModuleConfigFiles(appsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); // attach any beans that implement ProcessingElement to the PE // Container String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class); for (String processingElementBeanName : processingElementBeanNames) { Object bean = context.getBean(processingElementBeanName); try { Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock"); if (getS4ClockMethod.getReturnType().equals(Clock.class)) { if (getS4ClockMethod.invoke(bean) == null) { Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class); setS4ClockMethod.invoke(bean, coreContext.getBean("clock")); } } } catch (NoSuchMethodException mnfe) { // acceptable } System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id " + ((ProcessingElement) bean).getId()); peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName); } } }
From source file:org.apache.s4.MainApp.java
public static void main(String args[]) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(/*from w w w .j a va 2s. c om*/ OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a")); options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d")); options.addOption(OptionBuilder.withArgName("seedtime").hasArg() .withDescription("event clock initialization time").create("s")); options.addOption( OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e")); options.addOption( OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; String clockType = "wall"; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } int instanceId = -1; if (commandLine.hasOption("i")) { String instanceIdStr = commandLine.getOptionValue("i"); try { instanceId = Integer.parseInt(instanceIdStr); } catch (NumberFormatException nfe) { System.err.println("Bad instance id: %s" + instanceIdStr); System.exit(1); } } if (commandLine.hasOption("c")) { coreHome = commandLine.getOptionValue("c"); } if (commandLine.hasOption("a")) { appsHome = commandLine.getOptionValue("a"); } if (commandLine.hasOption("d")) { clockType = commandLine.getOptionValue("d"); } if (commandLine.hasOption("e")) { extsHome = commandLine.getOptionValue("e"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } long seedTime = 0; if (commandLine.hasOption("s")) { seedTime = Long.parseLong(commandLine.getOptionValue("s")); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } File appsHomeFile = new File(appsHome); if (!appsHomeFile.isDirectory()) { System.err.println("Bad applications home: " + appsHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } List loArgs = commandLine.getArgList(); if (loArgs.size() < 1) { // System.err.println("No bean configuration file specified"); // System.exit(1); } // String s4ConfigXml = (String) loArgs.get(0); // System.out.println("s4ConfigXml is " + s4ConfigXml); ClassPathResource propResource = new ClassPathResource("s4-core.properties"); Properties prop = new Properties(); if (propResource.exists()) { prop.load(propResource.getInputStream()); } else { System.err.println("Unable to find s4-core.properties. It must be available in classpath"); System.exit(1); } ApplicationContext coreContext = null; String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = ""; List<String> coreConfigUrls = new ArrayList<String>(); File configFile = null; // load clock configuration configPath = configBase + File.separatorChar + clockType + "-clock.xml"; coreConfigUrls.add(configPath); // load core config xml configPath = configBase + File.separatorChar + "s4-core-conf.xml"; configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("S4 core config file %s does not exist\n", configPath); System.exit(1); } coreConfigUrls.add(configPath); String[] coreConfigFiles = new String[coreConfigUrls.size()]; coreConfigUrls.toArray(coreConfigFiles); String[] coreConfigFileUrls = new String[coreConfigFiles.length]; for (int i = 0; i < coreConfigFiles.length; i++) { coreConfigFileUrls[i] = "file:" + coreConfigFiles[i]; } coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext); ApplicationContext context = coreContext; Clock clock = (Clock) context.getBean("clock"); if (clock instanceof EventClock && seedTime > 0) { EventClock s4EventClock = (EventClock) clock; s4EventClock.updateTime(seedTime); System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime()); } PEContainer peContainer = (PEContainer) context.getBean("peContainer"); Watcher w = (Watcher) context.getBean("watcher"); w.setConfigFilename(configPath); // load extension modules String[] configFileNames = getModuleConfigFiles(extsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); } // load application modules configFileNames = getModuleConfigFiles(appsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); // attach any beans that implement ProcessingElement to the PE // Container String[] processingElementBeanNames = context.getBeanNamesForType(AbstractPE.class); for (String processingElementBeanName : processingElementBeanNames) { AbstractPE bean = (AbstractPE) context.getBean(processingElementBeanName); bean.setClock(clock); try { bean.setSafeKeeper((SafeKeeper) context.getBean("safeKeeper")); } catch (NoSuchBeanDefinitionException ignored) { // no safe keeper = no checkpointing / recovery } // if the application did not specify an id, use the Spring bean name if (bean.getId() == null) { bean.setId(processingElementBeanName); } System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id " + ((AbstractPE) bean).getId()); peContainer.addProcessor((AbstractPE) bean); } } }
From source file:ab.demo.MainEntry.java
public static void main(String args[]) { LoggingHandler.initConsoleLog();//w w w . j a v a 2 s.c o 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.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.//from ww w . j ava 2 s .c o 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.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 ww . jav a2 s .c o 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 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.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./*ww w. jav a 2 s . co 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:MondrianService.java
public static void main(String[] arg) { System.out.println("Starting Mondrian Connector for Infoveave"); Properties prop = new Properties(); InputStream input = null;/*from ww w . j a v a 2 s . c o m*/ int listenPort = 9998; int threads = 100; try { System.out.println("Staring from :" + getSettingsPath()); input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties"); prop.load(input); listenPort = Integer.parseInt(prop.getProperty("port")); threads = Integer.parseInt(prop.getProperty("maxThreads")); if (input != null) { input.close(); } System.out.println("Found MondrianService.Properties"); } catch (FileNotFoundException e) { } catch (IOException e) { } port(listenPort); threadPool(threads); enableCORS("*", "*", "*"); ObjectMapper mapper = new ObjectMapper(); MondrianConnector connector = new MondrianConnector(); get("/ping", (request, response) -> { response.type("application/json"); return "\"Here\""; }); post("/cubes", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetCubes(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/measures", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetMeasures(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/dimensions", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetDimensions(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/cleanCache", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.CleanCubeCache(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/executeQuery", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject)); return content; } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); }
From source file:com.digitalgeneralists.assurance.Application.java
public static void main(String[] args) { Logger logger = Logger.getLogger(Application.class); logger.info("App is starting."); Properties applicationProperties = new Properties(); String applicationInfoFileName = "/version.txt"; InputStream inputStream = Application.class.getResourceAsStream(applicationInfoFileName); applicationInfoFileName = null;/* w ww . j a va2s .c om*/ try { if (inputStream != null) { applicationProperties.load(inputStream); Application.applicationShortName = applicationProperties.getProperty("name"); Application.applicationName = applicationProperties.getProperty("applicationName"); Application.applicationVersion = applicationProperties.getProperty("version"); Application.applicationBuildNumber = applicationProperties.getProperty("buildNumber"); applicationProperties = null; } } catch (IOException e) { logger.warn("Could not load application version information.", e); } finally { try { inputStream.close(); } catch (IOException e) { logger.error("Couldn't close the application version input stream."); } inputStream = null; } javax.swing.SwingUtilities.invokeLater(new Runnable() { private Logger logger = Logger.getLogger(Application.class); public void run() { logger.info("Starting the Swing run thread."); try { Application.installDb(); } catch (IOException e) { logger.fatal("Unable to install the application database.", e); System.exit(1); } catch (SQLException e) { logger.fatal("Unable to install the application database.", e); System.exit(1); } IApplicationUI window = null; ClassPathXmlApplicationContext springContext = null; try { springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml"); StringBuffer message = new StringBuffer(256); logger.info(message.append("Spring Context: ").append(springContext)); message.setLength(0); window = (IApplicationUI) springContext.getBean("ApplicationUI"); } finally { if (springContext != null) { springContext.close(); } springContext = null; } if (window != null) { logger.info("Launching the window."); window.display(); } else { logger.fatal("The main application window object is null."); } logger = null; } }); }
From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java
public static void main(String[] argv) throws Exception { if (argv.length != 2) { System.err.println("Usage: Bootstrap <jpa.properties> <output file>"); System.exit(1);//from w ww . j ava 2s . co m } Properties properties = new Properties(); try (InputStream is = new FileInputStream(new File(argv[0]))) { properties.load(is); } EntityManagerFactory emf = Persistence.createEntityManagerFactory(WellKnownObject.CORE, properties); EntityManager em = emf.createEntityManager(); Bootstrap bootstrap = new Bootstrap(em); bootstrap.clear(); em.getTransaction().begin(); bootstrap.bootstrap(); em.getTransaction().commit(); em.clear(); bootstrap.serialize(argv[1]); }
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"); }// w w w.j a v a 2s. 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"); } }