List of usage examples for org.springframework.context.support GenericXmlApplicationContext getBean
@Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException
From source file:com.home.ln_spring.ch8.sample.AnnotationJdbcDaoSample.java
public static void main(String[] args) { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load("classpath:ch8/app-context-annotation.xml"); context.refresh();/*w w w . jav a 2s. co m*/ ContactDao contactDao = context.getBean("contactDao", ContactDao.class); List<Contact> contacts = contactDao.findAll(); listContacts(contacts); System.out.println("Find by first name: "); contacts = contactDao.findByFirstName("Clarence"); listContacts(contacts); // System.out.println("Update contact with id : "); // Contact contact = new Contact(); // contact.setId(2); // contact.setFirstName("Jack"); // contact.setLastName("Rodwell"); // contact.setBirthDate( // new Date((new GregorianCalendar(1987, 1, 8)).getTime().getTime())); // contactDao.update(contact); // // contacts = contactDao.findAll(); // listContacts(contacts); // System.out.println("Insert contact"); // System.out.println(); // Contact contact1 = new Contact(); // contact1.setFirstName("Rod"); // contact1.setLastName("Johnson"); // contact1.setBirthDate( // new Date((new GregorianCalendar(1987, 1, 8)).getTime().getTime())); // contactDao.insert(contact1); // // contacts = contactDao.findAll(); // listContacts(contacts); System.out.println("Insert with BatchSqlUpdate"); System.out.println(); Contact contact2 = new Contact(); contact2.setFirstName("Michael"); contact2.setLastName("Jackson"); contact2.setBirthDate(new Date((new GregorianCalendar(1964, 10, 1)).getTime().getTime())); List<ContactTelDetail> contactTelDetails = new ArrayList<ContactTelDetail>(); ContactTelDetail contactTelDetail = new ContactTelDetail(); contactTelDetail.setTelType("Home"); contactTelDetail.setTelNumber("111111"); contactTelDetails.add(contactTelDetail); contactTelDetail = new ContactTelDetail(); contactTelDetail.setTelType("Mobile"); contactTelDetail.setTelNumber("222222"); contactTelDetails.add(contactTelDetail); contact2.setContactTelDetails(contactTelDetails); contactDao.insertWithDetail(contact2); contacts = contactDao.findAllWithDetail(); listContacts(contacts); }
From source file:com.home.ln_spring.ch10.sample.JpaSampleOld.java
public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:ch10/app-context.xml"); ctx.refresh();//from w w w . ja v a2 s.c o m ContactServiceOld contactService = ctx.getBean("jpaContactService", ContactServiceOld.class); //List<Contact> contacts = contactService.findAll(); //listContacts(contacts); //List<Contact> contacts = contactService.findAllWithDetail(); //listContactsWithDetail(contacts); //Contact contact = contactService.findById(1L); //getContactWithDetail(contact); // Inserting new contact // Contact contact = new Contact(); // contact.setFirstName("Michael"); // contact.setLastName("Jackson"); // contact.setBirthDate(new Date()); // ContactTelDetail contactTelDetail = // new ContactTelDetail("Home", "11111111111"); // contact.addContactTelDetail(contactTelDetail); // contactTelDetail = new ContactTelDetail("Mobile", "2222222222"); // contact.addContactTelDetail(contactTelDetail); // contactService.save(contact); // List<Contact> contacts = contactService.findAllWithDetail(); // listContactsWithDetail(contacts); // Update contact // Contact contact = new Contact(); // contact = contactService.findById(1l); // System.out.println(""); // System.err.println("Contact with id 1 " + contact); // System.out.println(""); // // contact.setFirstName("Kim Fung"); // Set<ContactTelDetail> contactTels = contact.getContactTelDetails(); // ContactTelDetail toDeleteContactTel = null; // for(ContactTelDetail telDetail: contactTels) { // if(telDetail.getTelType().equalsIgnoreCase("Home")) { // toDeleteContactTel = telDetail; // } // } // contactTels.remove(toDeleteContactTel); // contactService.save(contact); // contacts = contactService.findAllWithDetail(); // listContactsWithDetail(contacts); // Contact contact = new Contact(); // contact = contactService.findById(1l); // contactService.delete(contact); // contacts = contactService.findAllWithDetail(); // listContactsWithDetail(contacts); // List<Contact> contacts = contactService.findAllByNativeQuery(); // listContacts(contacts); List<Contact> conatcts = contactService.findByCriteriaQuery(null, "Jackson"); listContactsWithDetail(conatcts); }
From source file:com.home.ln_spring.ch9.sample.SpringHibernateSample.java
public static void main(String[] args) { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load("classpath:ch9/app-context.xml"); context.refresh();//w ww .ja v a2 s . c o m ContactDao contactDao = context.getBean("contactDao", ContactDao.class); //List<Contact> contacts = contactDao.findAll(); //List<Contact> contacts = contactDao.findAllWithDetail(); //listContacts(contacts); //listContactsWithDetail(contacts); //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //output: //Listing contacts with details : //Contact Tel Detail - Id: 2, Contact id: 1, Type: Home, Number: 1234567890 //Contact Tel Detail - Id: 1, Contact id: 1, Type: Mobile, Number: 1234567890 //Hobby :Movies //Hobby :Swimming //Contact Tel Detail - Id: 3, Contact id: 2, Type: Home, Number: 1234567890 //Hobby :Swimming //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //Contact contact; //contact = contactDao.findById(1); //System.out.println(); //System.out.println("Contact with id 1: " + contact); //System.out.println(); //output: //Contact with id 1: Contact - Id: 1, First name: Clarence, Last name: Ho, Birthday: 1980-07-30 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //Contact contact = new Contact(); //contact.setFirstName("James"); //contact.setLastName("Rodriguez"); //contact.setBirthDate(new Date()); //ContactTelDetail contactTelDetail = // new ContactTelDetail("Mobile", "111111111"); //contact.addContactTelDetail(contactTelDetail); //contactDao.save(contact); //List<Contact> contacts = contactDao.findAllWithDetail(); //listContactsWithDetail(contacts); //output: //Listing contacts with details: //Contact - Id: 3, First name: John, Last name: Smith, Birthday: 1964-02-28 //Contact - Id: 1, First name: Clarence, Last name: Ho, Birthday: 1980-07-30 //Contact Tel Detail - Id: 1, Contact id: 1, Type: Mobile, Number: 1234567890 //Contact Tel Detail - Id: 2, Contact id: 1, Type: Home, Number: 1234567890 //Hobby :Movies //Hobby :Swimming //Contact - Id: 5, First name: James, Last name: Rodriguez, Birthday: 2014-07-05 //Contact Tel Detail - Id: 5, Contact id: 5, Type: Mobile, Number: 111111111 //Contact - Id: 2, First name: Scott, Last name: Tiger, Birthday: 1990-11-02 //Contact Tel Detail - Id: 3, Contact id: 2, Type: Home, Number: 1234567890 //Hobby :Swimming //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Contact contact = new Contact(); // contact = contactDao.findById(1); // contact.setFirstName("Kim Fung"); // Set<ContactTelDetail> contactTels = contact.getContactTelDetails(); // ContactTelDetail toDeteteContactTel = null; // for(ContactTelDetail contactTelDetail: contactTels) { // if(contactTelDetail.getTelType().equals("Home")) { // toDeteteContactTel = contactTelDetail; // } // } // contact.removeContactTelDetail(toDeteteContactTel); // contactDao.save(contact); // List<Contact> contacts = contactDao.findAllWithDetail(); // listContactsWithDetail(contacts); // // Listing contacts with details: // Contact - Id: 3, First name: John, Last name: Smith, Birthday: 1964-02-28 // // Contact - Id: 5, First name: James, Last name: Rodriguez, Birthday: 2014-07-05 // Contact Tel Detail - Id: 5, Contact id: 5, Type: Mobile, Number: 111111111 // // Contact - Id: 1, First name: Kim Fung, Last name: Ho, Birthday: 1980-07-30 // Contact Tel Detail - Id: 1, Contact id: 1, Type: Mobile, Number: 1234567890 // Hobby :Movies // Hobby :Swimming // // Contact - Id: 2, First name: Scott, Last name: Tiger, Birthday: 1990-11-02 // Contact Tel Detail - Id: 3, Contact id: 2, Type: Home, Number: 1234567890 // Hobby :Swimming //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //Contact contact = contactDao.findById(1); //contactDao.delete(contact); //List<Contact> contacts = contactDao.findAllWithDetail(); //listContactsWithDetail(contacts); //output: //Listing contacts with details: //Contact - Id: 3, First name: John, Last name: Smith, Birthday: 1964-02-28 //Contact - Id: 5, First name: James, Last name: Rodriguez, Birthday: 2014-07-05 //Contact Tel Detail - Id: 5, Contact id: 5, Type: Mobile, Number: 111111111 //Contact - Id: 2, First name: Scott, Last name: Tiger, Birthday: 1990-11-02 //Contact Tel Detail - Id: 3, Contact id: 2, Type: Home, Number: 1234567890 //Hobby :Swimming }
From source file:com.mycompany.mavenproject3.Application.java
public static void main(String[] args) { // ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/spring/app-context.xml"); // MessageRenderer mr = ctx.getBean("renderer", MessageRenderer.class); // mr.render(); ////from w ww . j a v a 2 s . c o m // DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); // XmlBeanDefinitionReader rdr = new XmlBeanDefinitionReader(factory); // rdr.loadBeanDefinitions(new ClassPathResource("META-INF/spring/xml-bean-factory-config.xml")); // Oracle oracle = (Oracle) factory.getBean("oracle"); // System.out.println(oracle.defineMeaningOfLife()); GenericXmlApplicationContext ctx2 = new GenericXmlApplicationContext(); ctx2.load("classpath:app-context-xml.xml"); // ctx2.load("classpath:app-context-annotation.xml"); ctx2.refresh(); // MessageProvider messageProvider = ctx2.getBean("messageProvider", MessageProvider.class); // System.out.println(messageProvider.getMessage()); MessageRenderer messageRenderer = ctx2.getBean("messageRenderer", MessageRenderer.class); messageRenderer.render(); IfInjectSimple simple = (IfInjectSimple) ctx2.getBean("injectSimple"); System.out.println(simple); IfInjectSimpleSpel simple2 = (IfInjectSimpleSpel) ctx2.getBean("injectSimpleSpel"); System.out.println(simple2); IfInjectRef injectRef = (IfInjectRef) ctx2.getBean("injectRef"); System.out.println(injectRef); }
From source file:org.ptm.translater.App.java
public static void main(String... args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("file:src/main/resources/spring/datasource.xml"); ctx.refresh();//from w ww. j av a 2s . c o m GenericXmlApplicationContext ctx2 = new GenericXmlApplicationContext(); ctx2.load("file:src/main/resources/spring/datasource2.xml"); ctx2.refresh(); ArchiveDao archiveDao = ctx.getBean("archiveDao", ArchiveDao.class); List<Archive> archives = archiveDao.findAll(); UserDao userDao = ctx2.getBean("userDao", UserDao.class); TagDao tagDao = ctx2.getBean("tagDao", TagDao.class); PhotoDao photoDao = ctx2.getBean("photoDao", PhotoDao.class); List<Tag> tagz = tagDao.findAll(); Map<String, Long> hashTags = new HashMap<String, Long>(); for (Tag tag : tagz) hashTags.put(tag.getName(), tag.getId()); MongoCache cache = new MongoCache(); Calendar calendar = Calendar.getInstance(); Map<String, String> associates = new HashMap<String, String>(); for (Archive archive : archives) { AppUser appUser = new AppUser(); appUser.setName(archive.getName()); appUser.setEmail(archive.getUid() + "@mail.th"); appUser.setPassword("123456"); Role role = new Role(); role.setRoleId("ROLE_USER"); appUser.setRole(role); userDao.save(appUser); System.out.println("\tCreate user " + appUser); for (Photo photo : archive.getPhotos()) { // ? ??? if (cache.contains(photo.getUid())) continue; System.out.println("\tNew photo"); org.ptm.translater.ch2.domain.Photo photo2 = new org.ptm.translater.ch2.domain.Photo(); photo2.setAppUser(appUser); photo2.setName(photo.getTitle()); photo2.setLicense((byte) 7); photo2.setDescription(photo.getDescription()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { calendar.setTime(sdf.parse(photo.getTaken())); if (calendar.get(Calendar.YEAR) != 0 && calendar.get(Calendar.YEAR) > 1998) continue; photo2.setYear(calendar.get(Calendar.YEAR)); photo2.setMonth(calendar.get(Calendar.MONTH) + 1); photo2.setDay(calendar.get(Calendar.DAY_OF_MONTH)); } catch (Exception ex) { ex.printStackTrace(); } if (photo.getLongitude() != null && photo.getLongitude().length() > 0) { // String key = photo.getLongitude()+"#"+photo.getLatitude(); photo2.setLatitude(photo.getLatitude()); photo2.setLongitude(photo.getLongitude()); // if (associates.containsKey(key)) { // photo2.setAddress(associates.get(key)); // } else { // Geocoder geocoder = new Geocoder(); // GeocoderRequestBuilder geocoderRequest = new GeocoderRequestBuilder(); // GeocoderRequest request = // geocoderRequest.setLocation(new LatLng(photo.getLongitude(), photo.getLatitude())).getGeocoderRequest(); // // GeocodeResponse response = geocoder.geocode(request); // if (response.getResults().size() > 0) { // photo2.setAddress(response.getResults().get(0).getFormattedAddress()); // } // try { Thread.sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); } // } } System.out.println("\tFind tags"); Set<Tag> tags = new HashSet<Tag>(); for (org.ptm.translater.ch1.domain.Tag tag : photo.getTags()) { Tag item = new Tag(); item.setName(tag.getName()); if (hashTags.containsKey(tag.getName())) { item.setId(hashTags.get(tag.getName())); } else { tagDao.save(item); hashTags.put(item.getName(), item.getId()); } System.out.println("\t\tinit tag " + tag.getName()); tags.add(item); } photo2.setTags(tags); System.out.println("\tFind " + tags.size() + " tags"); photoDao.save(photo2); System.out.println("\tSave photo"); Imaginator img = new Imaginator(); img.setFolder(photo2.getId().toString()); img.setPath(); for (PhotoSize ps : photo.getSizes()) { if (ps.getLabel().equals("Original")) { img.setImage(ps.getSource()); break; } } img.generate(); System.out.println("\tGenerate image of photo"); img = null; cache.create(photo.getUid()); cache.create(photo2); System.out.println("Generate: " + photo2); } } }
From source file:com.home.ln_spring.ch10.sample.ContactSummarySample.java
public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:ch10/app-context.xml"); ctx.refresh();// w ww. j a v a 2s. c o m // ? ? ? . // ContactSummaryUntypeImpl contactSummaryUntypeImpl = // ctx.getBean("contactSummaryUntype", ContactSummaryUntypeImpl.class); // // contactSummaryUntypeImpl.displayAllContactSummary(); ContactSummaryService contactSummaryService = ctx.getBean("contactSummaryService", ContactSummaryService.class); List<ContactSummary> contacts = contactSummaryService.findAll(); for (ContactSummary contactSummary : contacts) { System.out.println(contactSummary); } }
From source file:com.amazonaws.services.simpleworkflow.flow.examples.deployment.DeploymentWorkflowImpl.java
@Override public Promise<String> deploy(String springTemplate) { Resource templateResource = new ByteArrayResource(springTemplate.getBytes()); GenericXmlApplicationContext appContext = new GenericXmlApplicationContext(); appContext.setParent(applicationContext); appContext.load(templateResource);// w w w.j ava 2s .c o m appContext.refresh(); ApplicationStack applicationStack = appContext.getBean("applicationStack", ApplicationStack.class); applicationStack.deploy(); return applicationStack.getUrl(); }
From source file:com.opensourceagility.springintegration.alerts.AlertsIntegrationTest.java
@SuppressWarnings("unchecked") @Test/*from w ww. j a v a 2s . c om*/ public void testChannelAdapterDemo() throws InterruptedException, ParseException { System.setProperty("spring.profiles.active", "testCase"); final GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext( configFilesChannelAdapterDemo); final MessageChannel createAlertRequestChannel = applicationContext.getBean("createAlertRequestChannel", MessageChannel.class); createAlertTestData(createAlertRequestChannel, thisMinuteDate); final QueueChannel queueChannel = applicationContext.getBean("queueChannel", QueueChannel.class); for (int counter = 1; counter <= 50; counter++) { int id = counter * 2; Message<String> reply = (Message<String>) queueChannel.receive(10000); Assert.assertNotNull(reply); String out = reply.getPayload(); Assert.assertEquals(getExpectedXml(id), out); LOGGER.debug("Received expected Alert XML from queue:" + out); } LOGGER.debug( "Asserted that urgent alerts are those 50 alerts with even ids, ranging from 2 up to 100... and that these are received from the queue"); Message<String> reply = (Message<String>) queueChannel.receive(10000); Assert.assertNull(reply); LOGGER.debug("Sleeping for 2 minutes until files are expected to have been (mock) uploaded..."); Thread.sleep(120 * 1000); final MockAmazonS3FileUploader mockFileProcessor = applicationContext.getBean("amazonS3FileUploader", MockAmazonS3FileUploader.class); Assert.assertEquals(2, mockFileProcessor.getLinesByFileName().size()); LOGGER.debug("Asserted successfully that 2 csv files were expected"); List<String> minute1Lines = mockFileProcessor.getLinesByFileName().get(thisMinuteString); List<String> minute2Lines = mockFileProcessor.getLinesByFileName().get(nextMinuteString); // Assert we have the correct 30 entries in the csv file for the 1st minute Assert.assertEquals(30, minute1Lines.size()); LOGGER.debug("Asserted successfully that 30 alerts found in file:" + thisMinuteString); // Assert we have 20 correct entries in the csv file for the 2nd minute Assert.assertEquals(20, minute2Lines.size()); LOGGER.debug("Asserted successfully that 20 alerts found in file:" + nextMinuteString); // Check that the 1st minute's csv lines are as expected for (int counter = 1; counter <= 30; counter++) { int id = counter * 2 - 1; String line = minute1Lines.get(counter - 1); Assert.assertEquals(getExpectedCsvLine(id), line); LOGGER.debug("Found expected csv line in file:" + thisMinuteString + ":" + line); } // Check that the 2nd minute's csv lines are as expected for (int counter = 31; counter <= 50; counter++) { int id = counter * 2 - 1; String line = minute2Lines.get(counter - 31); Assert.assertEquals(getExpectedCsvLine(id), line); LOGGER.debug("Found expected csv line in file:" + nextMinuteString + " : " + line); } LOGGER.debug( "Asserted that non-urgent alerts are those 50 alerts with odd ids, ranging from 1 up to 99... and that these are written to csv files and uploaded"); LOGGER.debug("Completed test successfully, closing application context"); applicationContext.close(); }
From source file:nz.co.jsrsolutions.tideservice.scraper.TideScraper.java
public static void main(String[] args) { logger.info("Starting application [ tide scraper ] ..."); GenericXmlApplicationContext context = null; try {/*from ww w.j av a2 s .c om*/ CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(CommandLineOptions.Options, args); if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) { context = new GenericXmlApplicationContext(); //ConfigurableEnvironment env = ctx.getEnvironment(); //env.setActiveProfiles("test1"); context.load(SPRING_CONFIG); context.refresh(); context.registerShutdownHook(); if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) { Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class); scheduler.start(); Object lock = new Object(); synchronized (lock) { lock.wait(); } } else { TideScraperController controller = context.getBean(CONTROLLER_BEAN_ID, TideScraperController.class); controller.executeCommandLine(commandLine); } } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ts", CommandLineOptions.Options); } } catch (TideScraperException tse) { logger.error("Failed to execute command", tse); } catch (ParseException pe) { logger.error("Failed to parse command line", pe); } catch (Exception e) { logger.error("Failed to execute command", e); } finally { if (context != null) { context.close(); } } logger.info("Exiting application [ tide scraper ] ..."); }
From source file:org.springframework.integration.core.MessageIdGenerationTests.java
@Test public void testCustomIdGenerationWithParentChildIndependentCreation() throws Exception { ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext( "MessageIdGenerationTests-context-withGenerator.xml", this.getClass()); GenericXmlApplicationContext child = new GenericXmlApplicationContext(); child.load("classpath:/org/springframework/integration/core/MessageIdGenerationTests-context.xml"); child.setParent(parent);/*from w w w .jav a2 s . c o m*/ child.refresh(); IdGenerator idGenerator = child.getBean("idGenerator", IdGenerator.class); MessageChannel inputChannel = child.getBean("input", MessageChannel.class); inputChannel.send(new GenericMessage<Integer>(0)); verify(idGenerator, atLeastOnce()).generateId(); child.close(); parent.close(); this.assertDestroy(); }