public void testInitializingBeanAndInitMethod() throws Exception {
   assertFalse(InitAndIB.constructed);
   InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib");
   assertTrue(InitAndIB.constructed);
   assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked);
   assertTrue(!iib.destroyed && !iib.customDestroyed);
   this.applicationContext.close();
   assertTrue(!iib.destroyed && !iib.customDestroyed);
   ConfigurableApplicationContext parent =
       (ConfigurableApplicationContext) this.applicationContext.getParent();
   parent.close();
   assertTrue(iib.destroyed && iib.customDestroyed);
   parent.close();
   assertTrue(iib.destroyed && iib.customDestroyed);
 }
 public static void main(String arg[]) throws IOException {
   ApplicationContext applicationContext =
       new ClassPathXmlApplicationContext(applicationContextXmlName);
   EmailService emailService = (EmailService) applicationContext.getBean(className);
   emailServiceHelperLogger.debug(emailService.sortEmailFromFile(inputFileName));
   ((ConfigurableApplicationContext) applicationContext).close();
 }
Beispiel #3
0
 void close() {
   if (ignoreCaseLookup) {
     applicationContext.getBean("atomicIgnoreCase", AtomicBoolean.class).set(false);
     ignoreCaseLookup = false;
   }
   ctx.close();
 }
  @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());
  }
  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();
  }
 @After
 public void tearDown() throws Exception {
   ctx.close();
   File cache = new File(IMAGE_CACHE_PATH);
   if (cache.exists()) {
     FileUtil.forceDeletion(new File(IMAGE_CACHE_PATH));
   }
 }
 @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();
 }
 @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();
 }
  @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");
  }
 @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();
 }
  public void refuserEntreprise() {
    System.out.println("REFUSER");
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    EntrepriseDAO entrepriseDAO = (EntrepriseDAO) context.getBean("entrepriseDao");

    // Supprimer l'entreprise de la bdd
    entrepriseDAO.supprimerEntreprise(entreprise.getId());
    ((ConfigurableApplicationContext) context).close();

    entreprises.remove(entreprise);
  }
  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();
  }
  // ajouter adresse a la liste des adresses de l admin
  public void ajouterAdresse() {
    adresse.setUtilisateur(admin);

    // Mettre à jour l'étudiant
    adresseDao.ajouterAdresse(adresse);

    admin.getAdresses().add(adresse);

    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    adresse = (Adresse) context.getBean("adresse");
    ((ConfigurableApplicationContext) context).close();
  }
  public void accepterEntreprise() {
    System.out.println("ACCEPTER");
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    EntrepriseDAO entrepriseDAO = (EntrepriseDAO) context.getBean("entrepriseDao");

    // Mettre à jour l'état de l'entreprise
    entreprise.setEtatCompte(EtatCompte.ACTIVE);
    entrepriseDAO.modifierEntreprise(entreprise);
    ((ConfigurableApplicationContext) context).close();

    entreprises.remove(entreprise);
  }
  // La méthode appelée quand l'admin retire une adresse
  public void retirerAdresse() {
    admin.getAdresses().remove(adresse);

    adresse.setUtilisateur(null);
    adresseDao.modifierAdresse(adresse);
    adresseDao.supprimerAdresse(adresse.getId());

    // Réinitialiser l'adresse par une nouvelle instance vide
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    adresse = (Adresse) context.getBean("adresse");
    ((ConfigurableApplicationContext) context).close();
  }
 @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();
 }
  @SuppressWarnings("resource")
  public static void main(String[] args) {

    ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext("example-xmlconfig.xml");

    BusinessLogic businessLogic = context.getBean("businessLogic", BusinessLogic.class);

    businessLogic.doBusiness("http://example.org/remotefile");

    context.close();
    System.out.println("Application ended");
  }
 @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();
 }
 @Test
 public void testSubscribersNotInterrupted() throws Exception {
   ConfigurableApplicationContext context =
       SpringApplication.run(TestTimeWindows.class, "--server.port=0");
   Sink sink = context.getBean(Sink.class);
   TestTimeWindows testTimeWindows = context.getBean(TestTimeWindows.class);
   sink.input().send(MessageBuilder.withPayload("hello1").build());
   sink.input().send(MessageBuilder.withPayload("hello2").build());
   sink.input().send(MessageBuilder.withPayload("hello3").build());
   assertThat(testTimeWindows.latch.await(5, TimeUnit.SECONDS)).isTrue();
   assertThat(testTimeWindows.interruptionState).isNotNull();
   assertThat(testTimeWindows.interruptionState).isFalse();
   context.close();
 }
 @Test
 public void propertySourceAnnotationWithPlaceholder() throws Exception {
   EnvironmentTestUtils.addEnvironment(this.environment, "source.location:specificlocation");
   SpringApplication application = new SpringApplication(WithPropertySourcePlaceholders.class);
   application.setEnvironment(this.environment);
   application.setWebEnvironment(false);
   ConfigurableApplicationContext context = application.run();
   String property = context.getEnvironment().getProperty("the.property");
   assertThat(property, equalTo("fromspecificlocation"));
   assertThat(
       context.getEnvironment(),
       containsPropertySource("class path resource " + "[specificlocation.properties]"));
   context.close();
 }
 @Test
 public void reverseEndpoint() throws Exception {
   ConfigurableApplicationContext context =
       new SpringApplicationBuilder(
               ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class)
           .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse")
           .run("--spring.main.web_environment=false");
   long count = context.getBean(ClientConfiguration.class).latch.getCount();
   AtomicReference<String> messagePayloadReference =
       context.getBean(ClientConfiguration.class).messagePayload;
   context.close();
   assertThat(count).isEqualTo(0);
   assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH");
 }
  @Test
  public void test() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AppConfig.class);
    ctx.scan("hu.neuron.java.core.example.java");
    ctx.refresh();

    HelloWordBeanJava bean = ctx.getBean(HelloWordBeanJava.class);
    bean.hello();

    HelloWordRunnerJava runnerJava = ctx.getBean(HelloWordRunnerJava.class);

    runnerJava.run();
    ((ConfigurableApplicationContext) ctx).close();
  }
 @Test
 public void propertySourceAnnotationInProfile() throws Exception {
   SpringApplication application = new SpringApplication(WithPropertySourceInProfile.class);
   application.setWebEnvironment(false);
   ConfigurableApplicationContext context = application.run("--spring.profiles.active=myprofile");
   String property = context.getEnvironment().getProperty("the.property");
   assertThat(property, equalTo("frompropertiesfile"));
   assertThat(
       context.getEnvironment(),
       containsPropertySource("class path resource " + "[enableprofile.properties]"));
   assertThat(
       context.getEnvironment(),
       not(containsPropertySource("classpath:/" + "enableprofile-myprofile.properties")));
   context.close();
 }
  @Test
  public void metaAnnotationIsDiscovered() {
    ConfigurableApplicationContext context =
        new AnnotationConfigApplicationContext(Config.class, MetaAnnotationTestBean.class);

    try {
      JmsListenerContainerTestFactory factory =
          context.getBean(JmsListenerContainerTestFactory.class);
      assertEquals(
          "one container should have been registered", 1, factory.getListenerContainers().size());
      JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint();
      assertEquals("metaTestQueue", ((AbstractJmsListenerEndpoint) endpoint).getDestination());
    } finally {
      context.close();
    }
  }
  public static void main(String[] args) {

    String config = System.getProperty(CONFIG_KEY, CONFIG_VAL);

    ApplicationContext c = new ClassPathXmlApplicationContext(config);

    try {

      TickLoader loader = c.getBean(TickLoader.class);

      loader.load();

    } finally {

      ((ConfigurableApplicationContext) c).close();
    }
  }
  public static void main(String args[]) {

    ConfigurableApplicationContext context = null;

    try {
      context = new ClassPathXmlApplicationContext("application-context.xml");
      System.out.println("Submitting example");
      YarnClient client = (YarnClient) context.getBean("yarnClient");
      client.submitApplication();
      System.out.println("Submitted example");
    } catch (Throwable e) {
      log.error("Error in main method", e);
    } finally {
      if (context != null) {
        context.close();
      }
    }
  }
 @Test
 public void sendToAnnotationFoundOnProxy() {
   ConfigurableApplicationContext context =
       new AnnotationConfigApplicationContext(
           Config.class, ProxyConfig.class, ProxyTestBean.class);
   try {
     JmsListenerContainerTestFactory factory =
         context.getBean(JmsListenerContainerTestFactory.class);
     assertEquals(
         "one container should have been registered", 1, factory.getListenerContainers().size());
     JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint();
     Method m = ReflectionUtils.findMethod(endpoint.getClass(), "getDefaultResponseDestination");
     ReflectionUtils.makeAccessible(m);
     Object destination = ReflectionUtils.invokeMethod(m, endpoint);
     assertEquals("SendTo annotation not found on proxy", "foobar", destination);
   } finally {
     context.close();
   }
 }
 static {
   if (Boolean.getBoolean(Constants.SKIP_EXTERNAL_DB_TESTS_KEY)) {
     dbmsAvailable = true;
   } else {
     final ConfigurableApplicationContext context =
         new OracleSpringTxnPersistentWorkflowTest().createContext(DS_CONTEXT);
     try {
       DataSource ds = context.getBean(DataSource.class);
       ds.setLoginTimeout(10);
       ds.getConnection();
       dbmsAvailable = true;
     } catch (Exception e) {
       logger.error("Oracle DBMS not available! Skipping Oracle unit tests.", e);
       e.printStackTrace();
     } finally {
       context.close();
     }
   }
 }
Beispiel #30
0
  public static void main(String[] args) throws InterruptedException {
    final ConfigurableApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("/spring/service-context.xml");

    System.out.println("Spring Integration Demo");

    applicationContext.refresh();
    applicationContext.start();
    try {
      LOG.info("Starting context!");
      applicationContext.getBean("launcherService", Runnable.class).run();

      // sleep for a while before close to let all the pending message be processed
      Thread.sleep(500);
      LOG.info("Going to stop now!");
    } finally {
      applicationContext.close();
    }
  }