List of usage examples for org.springframework.context ApplicationContext getBean
Object getBean(String name) throws BeansException;
From source file:org.openvpms.tools.archetype.diff.ArchDiff.java
/** * Main line./*from w w w . ja va 2 s. com*/ * * @param args the command line arguments */ public static void main(String[] args) { BasicConfigurator.configure(); try { JSAP parser = createParser(); JSAPResult config = parser.parse(args); if (!config.success()) { displayUsage(parser, config); } else { boolean recurse = !config.getBoolean("no-recurse"); boolean verbose = config.getBoolean("verbose"); String contextPath = config.getString("context"); String version1 = config.getString("version1"); String version2 = config.getString("version2"); if (!StringUtils.isEmpty(version1) && !StringUtils.isEmpty(version2)) { ApplicationContext context; if (!new File(contextPath).exists()) { context = new ClassPathXmlApplicationContext(contextPath); } else { context = new FileSystemXmlApplicationContext(contextPath); } IArchetypeService service = (IArchetypeService) context.getBean("archetypeService"); ArchDiff diff = new ArchDiff(); if (config.getBoolean("list")) { DescriptorLoader loader = getDescriptorLoader(version1, service, recurse); diff.list(loader, verbose); } else { DescriptorLoader oldVersion = getDescriptorLoader(version1, service, recurse); DescriptorLoader newVersion = getDescriptorLoader(version2, service, recurse); diff.compare(oldVersion, newVersion, verbose); } } else { displayUsage(parser, config); } } } catch (Throwable throwable) { log.error(throwable, throwable); } }
From source file:th.co.aoe.imake.pst.rest.application.Main.java
public static void main(String[] args) throws Exception { // Load the Spring application context final ApplicationContext springContext = new ClassPathXmlApplicationContext( new String[] { "th/co/aoe/imake/pst/rest/config/applicationContext-common.xml", "th/co/aoe/imake/pst/rest/config/applicationContext-hibernate.xml", "th/co/aoe/imake/pst/rest/config/applicationContext-pst-resource.xml", "th/co/aoe/imake/pst/rest/config/applicationContext-root-router.xml", "th/co/aoe/imake/pst/rest/config/applicationContext-server.xml" }); // Obtain the Restlet component from the Spring context and start it ((Component) springContext.getBean("top")).start(); /* applicationContext-bps-resource.xml applicationContext-common.xml/*from ww w . ja v a 2 s. c om*/ applicationContext-hibernate.xml applicationContext-root-router.xml applicationContext-server.xml*/ //testXStream(); }
From source file:edu.internet2.middleware.shibboleth.common.attribute.AttributeAuthorityCLI.java
/** * Runs this application. Help message prints if no arguments are given or if the "help" argument is given. * /*from w w w .j a v a2s .co m*/ * @param args command line arguments * * @throws Exception thrown if there is a problem during program execution */ public static void main(String[] args) throws Exception { CmdLineParser parser = parseCommandArguments(args); ApplicationContext appCtx = loadConfigurations( (String) parser.getOptionValue(CLIParserBuilder.CONFIG_DIR_ARG), (String) parser.getOptionValue(CLIParserBuilder.SPRING_EXTS_ARG)); saml1AA = (SAML1AttributeAuthority) appCtx.getBean("shibboleth.SAML1AttributeAuthority"); saml2AA = (SAML2AttributeAuthority) appCtx.getBean("shibboleth.SAML2AttributeAuthority"); SAMLObject attributeStatement; Boolean saml1 = (Boolean) parser.getOptionValue(CLIParserBuilder.SAML1_ARG, Boolean.FALSE); if (saml1.booleanValue()) { protocol = SAMLConstants.SAML11P_NS; attributeStatement = performSAML1AttributeResolution(parser, appCtx); } else { protocol = SAMLConstants.SAML20P_NS; attributeStatement = performSAML2AttributeResolution(parser, appCtx); } printAttributeStatement(attributeStatement); }
From source file:com.threadswarm.imagefeedarchiver.driver.CommandLineDriver.java
public static void main(String[] args) throws InterruptedException, ExecutionException, ParseException { // define available command-line options Options options = new Options(); options.addOption("h", "help", false, "display usage information"); options.addOption("u", "url", true, "RSS feed URL"); options.addOption("a", "user-agent", true, "User-Agent header value to use when making HTTP requests"); options.addOption("o", "output-directory", true, "output directory for downloaded images"); options.addOption("t", "thread-count", true, "number of worker threads, defaults to cpu-count + 1"); options.addOption("d", "delay", true, "delay between image downloads (in milliseconds)"); options.addOption("p", "notrack", false, "tell websites that you don't wish to be tracked (DNT)"); options.addOption("s", "https", false, "Rewrite image URLs to leverage SSL/TLS"); CommandLineParser commandLineParser = new BasicParser(); CommandLine commandLine = commandLineParser.parse(options, args); // print usage information if 'h'/'help' or no-args were given if (args.length == 0 || commandLine.hasOption("h")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar ImageFeedArchiver.jar", options); return; //abort execution }/* w w w. j a v a 2 s . c o m*/ URI rssFeedUri = null; if (commandLine.hasOption("u")) { String rssFeedUrlString = commandLine.getOptionValue("u"); try { rssFeedUri = FeedUtils.getUriFromUrlString(rssFeedUrlString); } catch (MalformedURLException | URISyntaxException e) { LOGGER.error("The Feed URL you supplied was malformed or violated syntax rules.. exiting", e); System.exit(1); } LOGGER.info("Target RSS feed URL: {}", rssFeedUri); } else { throw new IllegalStateException("RSS feed URL was not specified!"); } File outputDirectory = null; if (commandLine.hasOption("o")) { outputDirectory = new File(commandLine.getOptionValue("o")); if (!outputDirectory.isDirectory()) throw new IllegalArgumentException("output directory must be a *directory*!"); LOGGER.info("Using output directory: '{}'", outputDirectory); } else { throw new IllegalStateException("output directory was not specified!"); } String userAgentString = null; if (commandLine.hasOption("a")) { userAgentString = commandLine.getOptionValue("a"); LOGGER.info("Setting 'User-Agent' header value to '{}'", userAgentString); } int threadCount; if (commandLine.hasOption("t")) { threadCount = Integer.parseInt(commandLine.getOptionValue("t")); } else { threadCount = Runtime.getRuntime().availableProcessors() + 1; } LOGGER.info("Using {} worker threads", threadCount); long downloadDelay = 0; if (commandLine.hasOption("d")) { String downloadDelayString = commandLine.getOptionValue("d"); downloadDelay = Long.parseLong(downloadDelayString); } LOGGER.info("Using a download-delay of {} milliseconds", downloadDelay); boolean doNotTrackRequested = commandLine.hasOption("p"); boolean forceHttps = commandLine.hasOption("s"); ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml"); ((ConfigurableApplicationContext) context).registerShutdownHook(); HttpClient httpClient = (HttpClient) context.getBean("httpClient"); if (userAgentString != null) httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgentString); ProcessedRssItemDAO processedRssItemDAO = (ProcessedRssItemDAO) context.getBean("processedRssItemDAO"); CommandLineDriver.Builder driverBuilder = new CommandLineDriver.Builder(rssFeedUri); driverBuilder.setDoNotTrackRequested(doNotTrackRequested).setOutputDirectory(outputDirectory) .setDownloadDelay(downloadDelay).setThreadCount(threadCount).setHttpClient(httpClient) .setForceHttps(forceHttps).setProcessedRssItemDAO(processedRssItemDAO); CommandLineDriver driver = driverBuilder.build(); driver.run(); }
From source file:org.ala.hbase.RepoDataLoader.java
/** * This takes a list of infosource ids... * <p/>//from ww w.ja v a2 s. com * Usage: -stats or -reindex or -gList and list of infosourceId * * @param args */ public static void main(String[] args) throws Exception { //RepoDataLoader loader = new RepoDataLoader(); ApplicationContext context = SpringUtils.getContext(); RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class); long start = System.currentTimeMillis(); loader.loadInfoSources(); String filePath = repositoryDir; if (args.length > 0) { if (args[0].equalsIgnoreCase("-stats")) { loader.statsOnly = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); } if (args[0].equalsIgnoreCase("-reindex")) { loader.reindex = true; loader.indexer = context.getBean(PartialIndex.class); args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -reindex: " + loader.reindex); logger.debug("reindex url: " + loader.reindexUrl); } if (args[0].equalsIgnoreCase("-gList")) { loader.gList = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -gList: " + loader.gList); } if (args[0].equalsIgnoreCase("-biocache")) { Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); RestfulClient restfulClient = new RestfulClient(0); String fq = "&fq="; if (args.length > 1) { java.util.Date date = new java.util.Date(); if (args[1].equals("-lastWeek")) { date = DateUtils.addWeeks(date, -1); } else if (args[1].equals("-lastMonth")) { date = DateUtils.addMonths(date, -1); } else if (args[1].equals("-lastYear")) { date = DateUtils.addYears(date, -1); } else date = null; if (date != null) { SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D"; } } Object[] resp = restfulClient .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0", hashTable); logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0"); if ((Integer) resp[0] == HttpStatus.SC_OK) { String content = resp[1].toString(); logger.debug(resp[1]); if (content != null && content.length() > "[]".length()) { Map map = mapper.readValue(content, Map.class); try { List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map .get("facetResults")).get(0)).get("fieldResult")); Set<String> arg = new LinkedHashSet<String>(); for (int i = 0; i < list.size(); i++) { java.util.LinkedHashMap<String, String> value = list.get(i); String dataResource = getDataResource(value.get("fq")); Object provider = (loader.getUidInfoSourceMap().get(dataResource)); if (provider != null) { arg.add(provider.toString()); } } logger.info("Set of biocache infosource ids to load: " + arg); args = new String[] {}; args = arg.toArray(args); //handle the situation where biocache-service reports no data resources if (args.length < 1) { logger.error("No biocache data resources found. Unable to load."); System.exit(0); } } catch (Exception e) { logger.error("ERROR: exit process....." + e); e.printStackTrace(); System.exit(0); } } } else { logger.warn("Unable to process url: "); } } } int filesRead = loader.load(filePath, args); //FIX ME - move to config long finish = System.currentTimeMillis(); logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes " + ((finish - start) / 1000) + " seconds."); System.exit(1); }
From source file:org.openvpms.archetype.tools.account.AccountBalanceTool.java
/** * Main line.//from w w w . ja va2s. c om * * @param args command line arguments */ public static void main(String[] args) { try { JSAP parser = createParser(); JSAPResult config = parser.parse(args); if (!config.success()) { displayUsage(parser); } else { String contextPath = config.getString("context"); String name = config.getString("name"); long id = config.getLong("id"); boolean generate = config.getBoolean("generate"); boolean check = config.getBoolean("check"); ApplicationContext context; if (!new File(contextPath).exists()) { context = new ClassPathXmlApplicationContext(contextPath); } else { context = new FileSystemXmlApplicationContext(contextPath); } IArchetypeService service = (IArchetypeService) context.getBean("archetypeService"); AccountBalanceTool tool = new AccountBalanceTool(service); if (check) { if (id == -1) { tool.check(name); } else { tool.check(id); } } else if (generate) { tool.setFailOnError(config.getBoolean("failOnError")); if (id == -1) { tool.generate(name); } else { tool.generate(id); } } else { displayUsage(parser); } } } catch (Throwable throwable) { log.error(throwable, throwable); } }
From source file:org.ala.harvester.FlickrHarvester.java
/** * Main method for testing this particular Harvester * * @param args//from www . j a va 2s . com */ public static void main(String[] args) throws Exception { String[] locations = { "classpath*:spring.xml" }; ApplicationContext context = new ClassPathXmlApplicationContext(locations); FlickrHarvester h = new FlickrHarvester(); Repository r = (Repository) context.getBean("repository"); h.setDocumentMapper(new FlickrDocumentMapper()); h.setRepository(r); //set the connection params Map<String, String> connectParams = new HashMap<String, String>(); connectParams.put("endpoint", "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=08f5318120189e9d12669465c0113351&page=1"); // connectParams.put("eolGroupId", "806927@N20"); connectParams.put("eolGroupId", "22545712@N05"); connectParams.put("flickrRestBaseUrl", "http://api.flickr.com/services/rest"); connectParams.put("flickrApiKey", "08f5318120189e9d12669465c0113351"); connectParams.put("recordsPerPage", "50"); h.setConnectionParams(connectParams); h.start(1106); //1013 is the ID for the data source flickr }
From source file:org.ala.dao.RankingDaoImpl.java
public static void main(String[] args) { try {/* www . j ava2s .com*/ ApplicationContext context = SpringUtils.getContext(); RankingDao rankingDao = context.getBean(RankingDaoImpl.class); if (args.length == 1) { try { if (args[0].equals("-caab")) rankingDao.loadCAAB(); } catch (Exception e) { e.printStackTrace(); } try { if (args[0].equals("-reload")) rankingDao.reloadAllRanks(); } catch (Exception e) { e.printStackTrace(); } try { if (args[0].equals("-optimise")) rankingDao.optimiseIndex(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Please provide args: -reload or -caab"); } /* //below code for debug only ....... FulltextSearchDao searchDao = context.getBean(FulltextSearchDaoImplSolr.class); //create ranking solr index of 'rk' columnFamily // rankingDao.createIndex(); String guid = "urn:lsid:biodiversity.org.au:afd.taxon:f6e0d6c9-80fe-4355-bbe9-d94b426ab52e"; String userId = "waiman.mok@csiro.au"; BaseRanking baseRanking = new BaseRanking(); baseRanking.setUserId(userId); baseRanking.setUserIP("127.0.0.1"); baseRanking.setFullName("hello"); baseRanking.setBlackListed(false); baseRanking.setPositive(true); Map<String, String> map = new Hashtable<String, String> (); //ranking common name.... // baseRanking.setUri("http://www.environment.gov.au/biodiversity/abrs/online-resources/fauna/afd/taxa/47d3bff0-5df7-41d9-b682-913428aed5f0"); map.put(RankingType.RK_COMMON_NAME.getCompareFieldName()[0], "Fine-spotted Porcupine-fish"); baseRanking.setCompareFieldValue(map); // boolean b = rankingDao.rankingForTaxon(guid, ColumnType.VERNACULAR_COL, baseRanking); //ranking image.... // baseRanking.setUri("http://upload.wikimedia.org/wikipedia/commons/d/de/Ameisenigel_Unterseite-drawing.jpg"); map.clear(); map.put(RankingType.RK_IMAGE.getCompareFieldName()[0], "http://upload.wikimedia.org/wikipedia/commons/d/de/Ameisenigel_Unterseite-drawing.jpg"); baseRanking.setCompareFieldValue(null); // b = rankingDao.rankingForTaxon(guid, ColumnType.IMAGE_COL, baseRanking); //search ranking info.... Collection result = searchDao.getRankingFacetByUserIdAndGuid(userId, null); printFacetResult(result); System.out.println("\n===========================\n"); result = searchDao.getRankingFacetByUserIdAndGuid(userId, guid); printFacetResult(result); System.out.println("\n===========================\n"); result = searchDao.getUserIdFacetByGuid(guid); printFacetResult(result); */ } catch (Exception e) { e.printStackTrace(); } System.exit(0); }
From source file:org.ala.harvester.LocalCSVHarvester.java
/** * Main method for testing this particular Harvester * * @param args/*from ww w . j ava2 s.c o m*/ */ public static void main(String[] args) throws Exception { String[] locations = { "classpath*:spring.xml" }; ApplicationContext context = new ClassPathXmlApplicationContext(locations); LocalCSVHarvester h = new LocalCSVHarvester(); Repository r = (Repository) context.getBean("repository"); h.setRepository(r); int infosourceId = 0; String csvMapper = null; if (args.length == 2) { try { infosourceId = Integer.valueOf(args[0]); } catch (NumberFormatException nfe) { System.out.println("Invalid infosource ID!"); System.exit(1); } csvMapper = args[1]; } else { System.out.println("Usage: LocalCSVHarvester INFOSOURCE_ID CSV_MAPPER_NAME"); System.exit(1); } CsvMapper csvMapperClass = (CsvMapper) Class.forName(csvMapper).newInstance(); // displayMapContent(csvMapperClass.getParams()); h.setConnectionParams(csvMapperClass.getParams()); //set the connection params h.start(infosourceId); }
From source file:org.openvpms.tools.archetype.loader.ArchetypeLoader.java
/** * ArchDiff line./*w w w .j a v a 2s .c om*/ * * @param args the command line arguments */ public static void main(String[] args) { BasicConfigurator.configure(); try { JSAP parser = createParser(); JSAPResult config = parser.parse(args); if (!config.success()) { displayUsage(parser, config); } else { String contextPath = config.getString("context"); ApplicationContext context; if (!new File(contextPath).exists()) { context = new ClassPathXmlApplicationContext(contextPath); } else { context = new FileSystemXmlApplicationContext(contextPath); } IArchetypeService service = (IArchetypeService) context.getBean("archetypeService"); ArchetypeLoader loader = new ArchetypeLoader(service); String file = config.getString("file"); String dir = config.getString("dir"); boolean recurse = config.getBoolean("subdir"); loader.setOverwrite(config.getBoolean("overwrite")); loader.setFailOnError(config.getBoolean("failOnError")); loader.setVerbose(config.getBoolean("verbose")); boolean clean = config.getBoolean("clean"); String mappingFile = config.getString("mappingFile"); int processed = 0; PlatformTransactionManager mgr; mgr = (PlatformTransactionManager) context.getBean("txnManager"); TransactionStatus status = mgr.getTransaction(new DefaultTransactionDefinition()); try { if (clean) { loader.clean(); ++processed; } if (mappingFile != null) { loader.loadAssertions(mappingFile); ++processed; } if (file != null) { loader.loadArchetypes(file); ++processed; } else if (dir != null) { loader.loadArchetypes(dir, recurse); ++processed; } mgr.commit(status); if (processed == 0) { displayUsage(parser, config); } } catch (Throwable throwable) { log.error(throwable, throwable); log.error("Rolling back changes"); mgr.rollback(status); } } } catch (Throwable throwable) { log.error(throwable, throwable); } }