示例#1
0
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
   CustomEventPublisher customEventPublisher =
       (CustomEventPublisher) context.getBean("customEventPublisher");
   customEventPublisher.publish();
   customEventPublisher.publish();
 }
示例#2
0
  public static void main(String[] args) {
    System.out.println("load context");
    ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext("spring-config.xml");

    Projects johnsproject = new Projects();
    johnsproject.setProjectTitle("APP project");
    johnsproject.setProjectType("IOS");

    List<Projects> projectList = new ArrayList<Projects>();
    projectList.add(johnsproject);

    Employee em = new Employee();
    em.setId("11");
    em.setName("eee");
    em.setAge(22);
    em.setProjects(projectList);

    EmployeeService emService = (EmployeeService) context.getBean("employeeService");

    emService.persistEmployee(em);
    System.out.println("Updated age :" + emService.findEmployeeById("11").getAge());

    //        em.setAge(53);
    //        emService.updateEmployee(em);
    //        System.out.println("Updated age :" + emService.findEmployeeById("88").getAge());

    emService.deleteEmployee(em);

    context.close();
  }
 public static void main(String[] args) {
   ConfigurableApplicationContext context =
       new ClassPathXmlApplicationContext("/META-INF/spring/integration/http-outbound-config.xml");
   RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);
   String reply = requestGateway.echo("Hello");
   logger.info("\n\n++++++++++++ Replied with: " + reply + " ++++++++++++\n");
 }
  protected void registerAcAnnotations(
      ConfigurableApplicationContext context, final AcServiceConfig serviceConfig) {
    // Process Annotation AcStatusSubscriber
    AcMethodAnnotationProcessor statusSubscriberAnnotationProcessor =
        new AcMethodAnnotationProcessor(AcStatusSubscriber.class) {

          @Override
          protected void processBean(Object bean) {
            serviceConfig.getStatusListenerRegistry().processStatusListener(bean);
          }
        };
    context.addBeanFactoryPostProcessor(statusSubscriberAnnotationProcessor);
    context.addApplicationListener(statusSubscriberAnnotationProcessor);
    // Process Annotation AcDataSubscriber
    AcMethodAnnotationProcessor dataSubscriberAnnotationProcessor =
        new AcMethodAnnotationProcessor(AcDataSubscriber.class) {

          @Override
          protected void processBean(Object bean) {
            serviceConfig.getDispatchRegistry().processRegister(bean, metadata().getServiceId());
          }
        };
    context.addBeanFactoryPostProcessor(dataSubscriberAnnotationProcessor);
    context.addApplicationListener(dataSubscriberAnnotationProcessor);
  }
  @Test
  public void simpleMessageListener() {
    ConfigurableApplicationContext context =
        new AnnotationConfigApplicationContext(Config.class, SimpleMessageListenerTestBean.class);

    JmsListenerContainerTestFactory factory =
        context.getBean(JmsListenerContainerTestFactory.class);
    assertEquals(
        "One container should have been registered", 1, factory.getListenerContainers().size());
    MessageListenerTestContainer container = factory.getListenerContainers().get(0);

    JmsListenerEndpoint endpoint = container.getEndpoint();
    assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass());
    MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint;
    assertNotNull(methodEndpoint.getBean());
    assertNotNull(methodEndpoint.getMethod());

    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
    methodEndpoint.setupListenerContainer(listenerContainer);
    assertNotNull(listenerContainer.getMessageListener());

    assertTrue("Should have been started " + container, container.isStarted());
    context.close(); // Close and stop the listeners
    assertTrue("Should have been stopped " + container, container.isStopped());
  }
示例#6
0
 public void initialize() throws TaskSystemException {
   try {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     DocumentBuilder builder = factory.newDocumentBuilder();
     Document document = builder.parse(getTaskConfigurationInputSource());
     NodeList rootElement =
         document.getElementsByTagName(SchedulerConstants.SPRING_BEANS_FILE_ROOT_TAG);
     if (rootElement.getLength() > 0) { // new Quartz scheduler
       springTaskContext =
           new FileSystemXmlApplicationContext("file:" + getTaskConfigurationFilePath());
       scheduler =
           (Scheduler) springTaskContext.getBean(SchedulerConstants.SPRING_SCHEDULER_BEAN_NAME);
       jobExplorer =
           (JobExplorer) springTaskContext.getBean(SchedulerConstants.JOB_EXPLORER_BEAN_NAME);
       jobRepository =
           (JobRepository) springTaskContext.getBean(SchedulerConstants.JOB_REPOSITORY_BEAN_NAME);
       jobLauncher =
           (JobLauncher) springTaskContext.getBean(SchedulerConstants.JOB_LAUNCHER_BEAN_NAME);
       jobLocator =
           (JobLocator) springTaskContext.getBean(SchedulerConstants.JOB_LOCATOR_BEAN_NAME);
     } else { // old legacy Mifos Scheduler
       StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
       String configPath = getQuartzSchedulerConfigurationFilePath();
       schedulerFactory.initialize(configPath);
       scheduler = schedulerFactory.getScheduler();
       if (!scheduler.isInStandbyMode()) {
         scheduler.standby();
       }
       registerTasksOldConfigurationFile(document);
       scheduler.start();
     }
   } catch (Exception e) {
     throw new TaskSystemException(e);
   }
 }
 @SuppressWarnings("unchecked")
 private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
     String className, ConfigurableApplicationContext wac) {
   try {
     Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
     Class<?> initializerContextClass =
         GenericTypeResolver.resolveTypeArgument(
             initializerClass, ApplicationContextInitializer.class);
     if (initializerContextClass != null) {
       Assert.isAssignable(
           initializerContextClass,
           wac.getClass(),
           String.format(
               "Could not add context initializer [%s] since its generic parameter [%s] "
                   + "is not assignable from the type of application context used by this "
                   + "framework servlet [%s]: ",
               initializerClass.getName(),
               initializerContextClass.getName(),
               wac.getClass().getName()));
     }
     return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
   } catch (Exception ex) {
     throw new IllegalArgumentException(
         String.format(
             "Could not instantiate class [%s] specified "
                 + "via 'contextInitializerClasses' init-param",
             className),
         ex);
   }
 }
 public JHipsterReloaderThread(
     ConfigurableApplicationContext applicationContext, Collection<Reloader> reloaders) {
   this.reloaders = reloaders;
   domainPackageName = applicationContext.getEnvironment().getProperty("hotReload.package.domain");
   dtoPackageName = applicationContext.getEnvironment().getProperty("hotReload.package.restdto");
   isStarted = true;
 }
 @Override
 public void destroy() {
   appContext.close();
   if (appContext.getParent() instanceof ConfigurableApplicationContext) {
     ((ConfigurableApplicationContext) appContext.getParent()).close();
   }
   appContext = null;
 }
 @Before
 public void init() {
   ConfigurableApplicationContext context =
       new SpringApplicationBuilder(NativeEnvironmentRepositoryTests.class).web(false).run();
   this.repository = new NativeEnvironmentRepository(context.getEnvironment());
   this.repository.setVersion("myversion");
   context.close();
 }
 @Test
 public void testDefaultProfile() {
   SpringApplication app = new SpringApplication(AdminApplication.class);
   ConfigurableApplicationContext context = app.run(new String[] {"--server.port=0"});
   assertThat(context.containsBean("processModuleDeployer"), is(true));
   assertThat(context.getBean("processModuleDeployer"), instanceOf(LocalModuleDeployer.class));
   context.close();
 }
示例#12
0
 public static void main(String[] args) {
   @SuppressWarnings("resource")
   ConfigurableApplicationContext context =
       new ClassPathXmlApplicationContext("BeansCustEvent.xml");
   CustomEventPublisher cvp = (CustomEventPublisher) context.getBean("customEventPublisher");
   cvp.publish();
   cvp.publish();
 }
示例#13
0
 // works sort of. doesn't resolve placeholders in the loaded context. can;t load beans from
 // bootstrap context
 public static void bootstrap() {
   //	    System.setProperty("context", "Spel-context2.xml");
   ConfigurableApplicationContext ctx =
       new ClassPathXmlApplicationContext(
           "classpath:/com/rooney/spring/spel/Spel-bootstrap-context.xml");
   System.out.println(ctx.getBean("stringBean"));
   // System.out.println(ctx.getBean("stringBeanBootstrap"));
 }
示例#14
0
文件: Main.java 项目: HarishM/adbcj
  public static void main(String[] args) {
    ConfigurableApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml");

    ServerBootstrap bootstrap = applicationContext.getBean("bootstrap", ServerBootstrap.class);
    bootstrap.bind(new InetSocketAddress(8080));
    System.out.println("Server ready");
  }
  @Scheduled(fixedDelay = Integer.MAX_VALUE)
  public void startListening() {

    if (disable) {
      return;
    }

    log.info("Starting UPNP Discovery Listener");

    try (DatagramSocket responseSocket = new DatagramSocket(upnpResponsePort);
        MulticastSocket upnpMulticastSocket = new MulticastSocket(UPNP_DISCOVERY_PORT); ) {
      InetSocketAddress socketAddress =
          new InetSocketAddress(UPNP_MULTICAST_ADDRESS, UPNP_DISCOVERY_PORT);
      Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();

      while (ifs.hasMoreElements()) {
        NetworkInterface xface = ifs.nextElement();
        Enumeration<InetAddress> addrs = xface.getInetAddresses();
        String name = xface.getName();
        int IPsPerNic = 0;

        while (addrs.hasMoreElements()) {
          InetAddress addr = addrs.nextElement();
          log.debug(name + " ... has addr " + addr);
          if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) {
            IPsPerNic++;
          }
        }
        log.debug("Checking " + name + " to our interface set");
        if (IPsPerNic > 0) {
          upnpMulticastSocket.joinGroup(socketAddress, xface);
          log.debug("Adding " + name + " to our interface set");
        }
      }

      while (true) { // trigger shutdown here
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        upnpMulticastSocket.receive(packet);
        String packetString = new String(packet.getData());
        if (isSSDPDiscovery(packetString)) {
          log.debug(
              "Got SSDP Discovery packet from "
                  + packet.getAddress().getHostAddress()
                  + ":"
                  + packet.getPort());
          sendUpnpResponse(responseSocket, packet.getAddress(), packet.getPort());
        }
      }

    } catch (IOException e) {
      log.error("UpnpListener encountered an error. Shutting down", e);
      ConfigurableApplicationContext context =
          (ConfigurableApplicationContext) UpnpListener.this.applicationContext;
      context.close();
    }
    log.info("UPNP Discovery Listener Stopped");
  }
 public MongoEngine() {
   context = new ClassPathXmlApplicationContext("org/soldieringup/mongo-config.xml");
   userRepository = context.getBean(UserRepository.class);
   accountRepository = context.getBean(SoldierUpAccountRepository.class);
   zipRepository = context.getBean(ZipRepository.class);
   tagRepository = context.getBean(TagRepository.class);
   questionRepository = context.getBean(QuestionRepository.class);
   meetingRepository = context.getBean(MeetingRequestRepository.class);
 }
  @BeforeClass
  public static void prepare() throws Exception // NOPMD
      {
    Registry.activateStandaloneMode();
    Utilities.setJUnitTenant();
    LOG.debug("Preparing...");

    final ApplicationContext appCtx = Registry.getGlobalApplicationContext();

    assertTrue(
        "Application context of type "
            + appCtx.getClass()
            + " is not a subclass of "
            + ConfigurableApplicationContext.class,
        appCtx instanceof ConfigurableApplicationContext);

    final ConfigurableApplicationContext applicationContext =
        (ConfigurableApplicationContext) appCtx;
    final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
    assertTrue(
        "Bean Factory of type "
            + beanFactory.getClass()
            + " is not of type "
            + BeanDefinitionRegistry.class,
        beanFactory instanceof BeanDefinitionRegistry);
    final XmlBeanDefinitionReader xmlReader =
        new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
    xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class);
    xmlReader.loadBeanDefinitions(
        new ClassPathResource(
            "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-test.xml"));
    xmlReader.loadBeanDefinitions(
        new ClassPathResource(
            "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-test-fraudcheck.xml"));
    xmlReader.loadBeanDefinitions(
        new ClassPathResource(
            "/merchandisefulfilmentprocess/test/process/order-process-spring.xml"));
    modelService = (ModelService) getBean("modelService");
    processService = (DefaultBusinessProcessService) getBean("businessProcessService");
    definitonFactory = processService.getProcessDefinitionFactory();

    LOG.warn("Prepare Process Definition factory...");
    definitonFactory.add(
        "classpath:/merchandisefulfilmentprocess/test/process/payment-process.xml");

    // setup command factory to mock
    final DefaultCommandFactoryRegistryImpl commandFactoryReg =
        appCtx.getBean(DefaultCommandFactoryRegistryImpl.class);
    commandFactoryReg.setCommandFactoryList(
        Arrays.asList((CommandFactory) appCtx.getBean("mockupCommandFactory")));

    taskServiceStub = appCtx.getBean(TaskServiceStub.class);
    productService = appCtx.getBean("defaultProductService", DefaultProductService.class);
    cartService = appCtx.getBean("defaultCartService", DefaultCartService.class);
    userService = appCtx.getBean("defaultUserService", DefaultUserService.class);
  }
 @Test
 public void propertySourceAnnotationWithName() throws Exception {
   SpringApplication application = new SpringApplication(WithPropertySourceAndName.class);
   application.setWebEnvironment(false);
   ConfigurableApplicationContext context = application.run();
   String property = context.getEnvironment().getProperty("the.property");
   assertThat(property, equalTo("fromspecificlocation"));
   assertThat(context.getEnvironment(), containsPropertySource("foo"));
   context.close();
 }
示例#19
0
 public static void main(final String[] args) {
   try (ConfigurableApplicationContext ctx =
       new SpringApplicationBuilder()
           .bannerMode(Mode.OFF)
           .sources(Application.class)
           .build()
           .run(args)) {
     ctx.getBean(CamelSpringBootApplicationController.class).blockMainThread();
   }
 }
 @Test
 public void checkMessageRouting() {
   context.start();
   Message<?> message = new GenericMessage<Integer>(1);
   channel.send(message);
   PollableChannel chanel1 = (PollableChannel) context.getBean("channel1");
   PollableChannel chanel2 = (PollableChannel) context.getBean("channel2");
   assertTrue(chanel1.receive(0).getPayload().equals(1));
   assertTrue(chanel2.receive(0).getPayload().equals(1));
 }
 @Test
 public void simpleDynamicRouter() {
   context.start();
   Message<?> message = new GenericMessage<Integer>(1);
   simpleDynamicInput.send(message);
   PollableChannel chanel1 = (PollableChannel) context.getBean("channel1");
   PollableChannel chanel2 = (PollableChannel) context.getBean("channel2");
   assertTrue(chanel1.receive(0).getPayload().equals(1));
   assertNull(chanel2.receive(0));
 }
示例#22
0
  public static void main(String[] args) {
    ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext("springMailContext.xml");
    SendMailExample bean = (SendMailExample) context.getBean("mailService");

    // bean.sendMail("*****@*****.**", "*****@*****.**", "FYME email test",
    //		"Testing.. \n Hello Spring Email Sender");
    // bean.sendMailWithTemplate("User", "Welcome to FYME");
    bean.sendMailWithAttachment("User", "Welcome to FYME");
    context.close();
  }
 public static void main(String[] args) {
   ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
   CompositePropertySource compositePropertySource =
       (CompositePropertySource) run.getEnvironment().getPropertySources().get("bootstrap");
   for (PropertySource<?> propertySource : compositePropertySource.getPropertySources()) {
     System.out.println("propertySource name: " + propertySource.getName());
     for (String name : ((EnumerablePropertySource<?>) propertySource).getPropertyNames()) {
       System.out.println(String.format("%s=%s", name, propertySource.getProperty(name)));
     }
   }
 }
  @Before
  public void setUp() throws Exception {
    // get the original path
    originalImage = new File(getClass().getResource("/" + IMAGE_NAME).getPath());
    assertThat(originalImage.exists(), is(true));

    // bootstrap the Spring context
    ctx = new ClassPathXmlApplicationContext("classpath:/spring-image.xml");
    ctx.start();
    processor = ctx.getBean(ImageResizingProcessor.class);
  }
  @After
  public void tearDown() {
    final ConfigurableApplicationContext ctx =
        (ConfigurableApplicationContext) Registry.getApplicationContext();
    final DefaultListableBeanFactory beanFactory =
        (DefaultListableBeanFactory) ctx.getBeanFactory();

    beanFactory.removeBeanDefinition(PROCEDURAL_ACTION_ID);
    beanFactory.removeBeanDefinition(JOURNAL_ID);

    processDefinitionsCache.clear();
  }
 @Test
 public void propertySourceAnnotationAndNonActiveProfile() throws Exception {
   SpringApplication application = new SpringApplication(WithPropertySourceAndProfile.class);
   application.setWebEnvironment(false);
   ConfigurableApplicationContext context = application.run();
   String property = context.getEnvironment().getProperty("my.property");
   assertThat(property, equalTo("fromapplicationproperties"));
   assertThat(
       context.getEnvironment(),
       not(containsPropertySource("classpath:" + "/enableprofile-myprofile.properties")));
   context.close();
 }
 @Test
 public void noSelectorMatchRouter() {
   context.start();
   Message<?> message = new GenericMessage<Integer>(1);
   noSelectorMatchInput.send(message);
   PollableChannel chanel1 = (PollableChannel) context.getBean("channel1");
   PollableChannel chanel2 = (PollableChannel) context.getBean("channel2");
   Message<?> output = chanel1.receive(0);
   assertNotNull(output);
   assertTrue(output.getPayload().equals(1));
   assertNull(chanel2.receive(0));
 }
  public static void main(String[] args) {
    try {
      ConfigurableApplicationContext applicationContext =
          SpringApplication.run(SwitterBotApplication.class, args);

      final PostService postService = (PostService) applicationContext.getBean("postService");
      Thread postThread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  int delayMultiplier = 1;
                  while (true) {
                    try {
                      if (!postService.postNewPicture()) {
                        System.out.println("NO PICTURES TO POST!");
                        delayMultiplier = delayMultiplier * 2;
                      } else {
                        delayMultiplier = 1;
                      }
                      Thread.sleep(60000 * 30 * delayMultiplier);
                    } catch (Exception e) {
                      e.printStackTrace();
                      return;
                    }
                  }
                }
              });
      postThread.start();
      postThread.join();

      /*final CleanService cleanService = (CleanService) applicationContext.getBean("cleanService");
      Thread cleanThread = new Thread(new Runnable() {
          @Override
          public void run() {
              while (true) {
                  try {
                      cleanService.clean();
                      Thread.sleep(60000*60*24);
                  } catch (Exception e) {
                      e.printStackTrace();
                      return;
                  }
              }
          }
      });
      cleanThread.start();
      cleanThread.join();*/

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Test
  public void withAnnotationOnArgumentAndCglibProxy() {
    ConfigurableApplicationContext ctx =
        new AnnotationConfigApplicationContext(
            ConfigWithCglibProxy.class, SampleService.class, LoggingAspect.class);

    SampleService sampleService = ctx.getBean(SampleService.class);
    sampleService.execute(new SampleDto());
    sampleService.execute(new SampleInputBean());
    sampleService.execute((SampleDto) null);
    sampleService.execute((SampleInputBean) null);
  }
 @Test
 public void propertySourceAnnotationMultipleLocations() throws Exception {
   SpringApplication application =
       new SpringApplication(WithPropertySourceMultipleLocations.class);
   application.setWebEnvironment(false);
   ConfigurableApplicationContext context = application.run();
   String property = context.getEnvironment().getProperty("the.property");
   assertThat(property, equalTo("frommorepropertiesfile"));
   assertThat(
       context.getEnvironment(),
       containsPropertySource("class path resource " + "[specificlocation.properties]"));
   context.close();
 }