Esempio n. 1
0
  public void testRemovingListeners() throws Exception {
    TestSubscriptionEventBean subscriptionBean =
        (TestSubscriptionEventBean) context.getBean("testSubscribingEventBean1");
    assertNotNull(subscriptionBean);
    MuleEventMulticaster multicaster =
        (MuleEventMulticaster)
            context.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME);
    assertNotNull(multicaster);

    Latch whenFinished = new Latch();
    subscriptionBean.setEventCallback(new CountingEventCallback(eventCounter1, 1, whenFinished));

    multicaster.removeApplicationListener(subscriptionBean);
    MuleClient client = new MuleClient();
    client.send("vm://event.multicaster", "Test Spring Event", null);

    assertEquals(0, eventCounter1.get());

    multicaster.addApplicationListener(subscriptionBean);
    client.send("vm://event.multicaster", "Test Spring Event", null);

    assertTrue(whenFinished.await(3000, TimeUnit.MILLISECONDS));
    assertEquals(1, eventCounter1.get());
    eventCounter1.set(0);

    multicaster.removeAllListeners();
    client.send("vm://event.multicaster", "Test Spring Event", null);

    assertEquals(0, eventCounter1.get());
    multicaster.addApplicationListener(subscriptionBean);
    context.refresh();
    subscriptionBean.setEventCallback(null);
  }
  public static void main(String[] args) {
    ClassPathXmlApplicationContext context =
        new ClassPathXmlApplicationContext("classpath:integration-transformer.xml");

    JmsTemplate jmsTemplate = context.getBean("jmsTemplate", JmsTemplate.class);

    jmsTemplate.send(
        new MessageCreator() {

          @Override
          public javax.jms.Message createMessage(Session session) throws JMSException {
            MapMessage message = session.createMapMessage();
            message.setString("firstName", "John");
            message.setString("lastName", "Smith");
            message.setString("address", "100 State Street");
            message.setString("city", "Los Angeles");
            message.setString("state", "CA");
            message.setString("zip", "90064");
            System.out.println("Sending message: " + message);
            return message;
          }
        });

    PollableChannel output = (PollableChannel) context.getBean("output");
    Message<?> reply = output.receive();
    System.out.println("received: " + reply.getPayload());
  }
Esempio n. 3
0
  @Override
  public void setUp() throws Exception {
    super.setUp();

    this.fileFolderService = (FileFolderService) ctx.getBean("FileFolderService");
    this.repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
    this.nodeService = (NodeService) ctx.getBean("NodeService");
    this.transactionService = (TransactionService) ctx.getBean("transactionService");

    server.setServletAuthenticatorFactory(new LocalTestRunAsAuthenticatorFactory());

    NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();
    String guid = GUID.generate();

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

    folderWithoutAspect =
        fileFolderService
            .create(companyHomeNodeRef, "folder_" + guid, ContentModel.TYPE_FOLDER)
            .getNodeRef();
    assertNotNull("Doesn't create folder", folderWithoutAspect);

    folderWithAspect =
        fileFolderService
            .create(companyHomeNodeRef, "folder_aspect_" + guid, ContentModel.TYPE_FOLDER)
            .getNodeRef();
    assertNotNull("Doesn't create folder", folderWithoutAspect);
    // add 'dublincore' aspect
    Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(1);
    aspectProps.put(ContentModel.PROP_SUBJECT, "Test subject");
    nodeService.addAspect(folderWithAspect, ContentModel.ASPECT_DUBLINCORE, aspectProps);
  }
  @Test
  public void testServers() throws Exception {
    ClassPathXmlApplicationContext ctx =
        new ClassPathXmlApplicationContext(
            new String[] {"/org/apache/cxf/jaxrs/spring/servers.xml"});

    JAXRSServerFactoryBean sfb = (JAXRSServerFactoryBean) ctx.getBean("simple");
    assertEquals("Get a wrong address", "http://localhost:9090/rs", sfb.getAddress());
    assertNotNull("The resource classes should not be null", sfb.getResourceClasses());
    assertEquals("Get a wrong resource class", BookStore.class, sfb.getResourceClasses().get(0));
    QName serviceQName = new QName("http://books.com", "BookService");
    assertEquals(serviceQName, sfb.getServiceName());
    assertEquals(serviceQName, sfb.getServiceFactory().getServiceName());

    sfb = (JAXRSServerFactoryBean) ctx.getBean("inlineServiceBeans");
    assertNotNull("The resource classes should not be null", sfb.getResourceClasses());
    assertEquals("Get a wrong resource class", BookStore.class, sfb.getResourceClasses().get(0));
    assertEquals(
        "Get a wrong resource class",
        BookStoreSubresourcesOnly.class,
        sfb.getResourceClasses().get(1));

    sfb = (JAXRSServerFactoryBean) ctx.getBean("inlineProvider");
    assertNotNull("The provider should not be null", sfb.getProviders());
    assertEquals("Get a wrong provider size", 2, sfb.getProviders().size());
    verifyJaxbProvider(sfb.getProviders());
    sfb = (JAXRSServerFactoryBean) ctx.getBean("moduleServer");
    assertNotNull("The resource classes should not be null", sfb.getResourceClasses());
    assertEquals("Get a wrong ResourceClasses size", 1, sfb.getResourceClasses().size());
    assertEquals(
        "Get a wrong resource class",
        BookStoreNoAnnotations.class,
        sfb.getResourceClasses().get(0));
    ctx.close();
  }
Esempio n. 5
0
  public void run() {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    EmployeeManager employeeManager = context.getBean(EmployeeManagerImpl.class);
    ProjectManager projectManager = context.getBean(ProjectManagerImpl.class);
    UnitManager unitManager = context.getBean(UnitManagerImpl.class);

    Employee employeeOleksii =
        createEmployee("Junior Java Developer", "Oleksii", EmployeeStatus.NIIGER, 27);
    Employee employeeXZ = createEmployee("Middle Java Developer", "XZ", EmployeeStatus.NIIGER, 27);
    Long employeeOleksiiID = employeeManager.save(employeeOleksii);
    Long employeeXZID = employeeManager.save(employeeXZ);
    logger.info("Employee Oleksii saved with ID: " + employeeOleksiiID);
    logger.info("Employee XZ saved with ID: " + employeeXZID);
    //
    Project project = createProject();
    Long projectID = projectManager.save(project);
    logger.info("Project CTrack saved with ID: " + projectID);

    Unit unit = createUnit();
    Long unitID = unitManager.save(unit);
    logger.info("Unit CTrack saved with ID: " + unitID);

    employeeManager.addToUnit(employeeOleksiiID, unitID);
    employeeManager.addToUnit(employeeXZID, unitID);
    logger.info("Employee with ID: " + employeeOleksiiID + " added to Unit with ID: " + unitID);
    logger.info("Employee with ID: " + employeeXZID + " added to Unit with ID: " + unitID);

    employeeManager.assignToProject(employeeOleksiiID, projectID);
    logger.info(
        "Employee with ID: " + employeeOleksiiID + " assigned to Project with ID: " + projectID);

    // close resources
    context.close();
  }
 public static void main(String[] args) {
   ClassPathXmlApplicationContext classPathXmlApplicationContext =
       new ClassPathXmlApplicationContext("spring-config.xml");
   PropertyOverride propertyOverride =
       classPathXmlApplicationContext.getBean("propertyOverride", PropertyOverride.class);
   PropertyOverride propertyOverride1 =
       classPathXmlApplicationContext.getBean("propertyOverride1", PropertyOverride.class);
   System.out.println("propertyOverride = " + propertyOverride.getAlgorithmRequired());
   System.out.println(
       "propertyOverride1.getAlgorithmRequired() = " + propertyOverride1.getAlgorithmRequired());
 }
 @Before
 public void setUp() {
   ClassPathXmlApplicationContext ctx =
       new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
   highPrecedenceAspect = (PrecedenceTestAspect) ctx.getBean("highPrecedenceAspect");
   lowPrecedenceAspect = (PrecedenceTestAspect) ctx.getBean("lowPrecedenceAspect");
   highPrecedenceSpringAdvice =
       (SimpleSpringBeforeAdvice) ctx.getBean("highPrecedenceSpringAdvice");
   lowPrecedenceSpringAdvice = (SimpleSpringBeforeAdvice) ctx.getBean("lowPrecedenceSpringAdvice");
   testBean = (ITestBean) ctx.getBean("testBean");
 }
 @Test
 public void testGatewayWithMessageConverter() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsGatewayWithMessageConverter.xml", this.getClass());
   PollableChannel channel = (PollableChannel) context.getBean("requestChannel");
   JmsMessageDrivenEndpoint gateway = (JmsMessageDrivenEndpoint) context.getBean("jmsGateway");
   assertEquals(JmsMessageDrivenEndpoint.class, gateway.getClass());
   context.start();
   Message<?> message = channel.receive(3000);
   assertNotNull("message should not be null", message);
   assertEquals("converted-test-message", message.getPayload());
   context.stop();
 }
 @Test
 public void gatewayWithReplyChannel() {
   ActiveMqTestUtils.prepare();
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsGatewayWithReplyChannel.xml", this.getClass());
   JmsMessageDrivenEndpoint gateway = (JmsMessageDrivenEndpoint) context.getBean("gateway");
   Object replyChannel =
       TestUtils.getPropertyValue(gateway, "listener.gatewayDelegate.replyChannel");
   assertEquals(context.getBean("replies"), replyChannel);
   JmsTemplate template = new JmsTemplate(context.getBean(ConnectionFactory.class));
   template.convertAndSend("testDestination", "Hello");
   assertNotNull(template.receive("testReplyDestination"));
 }
 @Test
 public void adapterWithTaskExecutor() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsInboundWithTaskExecutor.xml", this.getClass());
   JmsMessageDrivenEndpoint endpoint =
       context.getBean("messageDrivenAdapter.adapter", JmsMessageDrivenEndpoint.class);
   DefaultMessageListenerContainer container =
       TestUtils.getPropertyValue(
           endpoint, "listenerContainer", DefaultMessageListenerContainer.class);
   assertSame(context.getBean("exec"), TestUtils.getPropertyValue(container, "taskExecutor"));
   endpoint.stop();
   context.close();
 }
 @Test
 public void testGatewayWithContainerReference() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext(
           "inboundGatewayWithContainerReference.xml", this.getClass());
   JmsMessageDrivenEndpoint gateway =
       (JmsMessageDrivenEndpoint) context.getBean("gatewayWithContainerReference");
   gateway.start();
   AbstractMessageListenerContainer container =
       (AbstractMessageListenerContainer)
           new DirectFieldAccessor(gateway).getPropertyValue("listenerContainer");
   assertEquals(context.getBean("messageListenerContainer"), container);
   gateway.stop();
 }
Esempio n. 12
0
  @Test
  public void testWithinJob() throws Exception {
    ClassPathXmlApplicationContext context =
        new ClassPathXmlApplicationContext(
            "/org/springframework/data/hadoop/fs/HdfsItemWriterTest-context.xml");
    JobLauncher launcher = context.getBean(JobLauncher.class);
    Job job = context.getBean(Job.class);

    JobParameters jobParameters = new JobParametersBuilder().toJobParameters();

    JobExecution execution = launcher.run(job, jobParameters);
    assertTrue(
        "status was: " + execution.getStatus(), execution.getStatus() == BatchStatus.COMPLETED);
  }
 @Test
 public void testDefaultRegistries() {
   ClassPathXmlApplicationContext ctx = null;
   try {
     ctx = new ClassPathXmlApplicationContext("classpath:default-registries.xml");
     Assert.assertNotNull("Should be a MetricRegistry.", ctx.getBean(MetricRegistry.class));
     Assert.assertNotNull(
         "Should be HealthCheckRegistry.", ctx.getBean(HealthCheckRegistry.class));
   } finally {
     if (ctx != null) {
       ctx.close();
     }
   }
 }
  @Before
  public void setUp() throws Exception {
    ClassPathXmlApplicationContext ctx =
        new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
    AdviceBindingTestAspect afterAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

    testBeanProxy = (ITestBean) ctx.getBean("testBean");
    assertTrue(AopUtils.isAopProxy(testBeanProxy));

    // we need the real target too, not just the proxy...
    testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

    mockCollaborator = createNiceMock(AdviceBindingCollaborator.class);
    afterAdviceAspect.setCollaborator(mockCollaborator);
  }
 @Test
 public void testSuppliedRegistries() {
   ClassPathXmlApplicationContext ctx = null;
   try {
     ctx = new ClassPathXmlApplicationContext("classpath:supplied-registries.xml");
     Assert.assertNotSame(
         "Should have provided MetricRegistry.", ctx.getBean(MetricRegistry.class));
     Assert.assertNotSame(
         "Should have provided HealthCheckRegistry.", ctx.getBean(HealthCheckRegistry.class));
   } finally {
     if (ctx != null) {
       ctx.close();
     }
   }
 }
  @BeforeClass
  public static void loadCommonApplicationContextAndStartTheNode() {
    context = new ClassPathXmlApplicationContext("commonApplicationContext.xml");

    xenRefreshHandler = (XenRefreshHandler) context.getBean("xenRefreshHandler");
    xenRefreshHandler.setInitialIntervalMillis(1000);
    xenRefreshHandler.setRepeatingIntervalMillis(1000);

    properties = (Properties) context.getBean("properties");
    KoalaNode koalaNode = (KoalaNode) context.getBean("koalaNode");
    koalaNode.start();
    AnycastHandler anycastHandler = (AnycastHandler) context.getBean("anycastHandler");
    anycastHandler.refreshInstanceTypes();
    FileUtils.deleteQuietly(new File("tmp"));
  }
Esempio n. 17
0
  @Test
  public void testInjectConverter() throws Exception {
    DozerBeanMapper mapper = context.getBean("mapperWithConverter", DozerBeanMapper.class);

    assertNotNull(mapper);
    assertNotNull(mapper.getMappingFiles());

    List<CustomConverter> customConverters = mapper.getCustomConverters();
    assertEquals(1, customConverters.size());

    InjectedCustomConverter converter = context.getBean(InjectedCustomConverter.class);
    converter.setInjectedName("inject");

    assertBasicMapping(mapper);
  }
Esempio n. 18
0
  public static void main(String[] args) throws Throwable {
    // you can setup $GRIDGAIN_HOME as an environmental variable
    File whereImKeepingGridgain =
        new File(new File(SystemUtils.getUserHome(), "Desktop"), "gridgain-2.1.1");
    System.setProperty("GRIDGAIN_HOME", whereImKeepingGridgain.getAbsolutePath());

    ClassPathXmlApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("gridservice.xml");
    applicationContext.registerShutdownHook();
    applicationContext.start();

    SalutationService salutationServiceImpl =
        (SalutationService) applicationContext.getBean("salutationService");

    String[] names =
        ("Alan,Arin,Clark,Craig,Drew,Gary,Gordon,Fumiko,"
                + "Hicham,Jordon,Kathy,Ken,Makani,Mario, "
                + "Mark,Mia,Mike,Nick,Richard,Richelle, "
                + "Rod,Ron,Scott,Shaun,Srinivas,Valerie,Venkatesh")
            .split(",");

    System.out.println(StringUtils.repeat("=", 100));

    for (String name : names) {
      System.out.println("Result: " + salutationServiceImpl.saluteSomeoneInForeignLanguage(name));
    }

    System.out.println(StringUtils.repeat("=", 100));
    System.out.println(
        "Results:"
            + StringUtils.join(
                salutationServiceImpl.saluteManyPeopleInRandomForeignLanguage(names), ","));
  }
 @Test
 public void testGatewayWithTransactionManagerReference() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext(
           "jmsGatewayTransactionManagerTests.xml", this.getClass());
   JmsMessageDrivenEndpoint gateway =
       (JmsMessageDrivenEndpoint) context.getBean("gatewayWithTransactionManager");
   DirectFieldAccessor accessor = new DirectFieldAccessor(gateway);
   accessor = new DirectFieldAccessor(accessor.getPropertyValue("listenerContainer"));
   Object txManager = accessor.getPropertyValue("transactionManager");
   assertEquals(JmsTransactionManager.class, txManager.getClass());
   assertEquals(context.getBean("txManager"), txManager);
   assertEquals(
       context.getBean("testConnectionFactory"),
       ((JmsTransactionManager) txManager).getConnectionFactory());
 }
Esempio n. 20
0
 @Test
 public void testAutowireByAutoDetect() throws IOException {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("chapter3/autowire-autodetect.xml");
   HelloApi helloApi = context.getBean("bean", HelloApi.class);
   helloApi.sayHello();
 }
Esempio n. 21
0
  public static void main(String[] args) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("AC-test.xml");
    IRuleEngine ruleEngine = ctx.getBean("ruleEngine", IRuleEngine.class);

    System.out.println(ruleEngine.getRulePackages());

    //		ruleEngine.execute("p2", "1");

    PremiumCalcBom bom = new PremiumCalcBom();
    bom.setInsuredSex("F");
    bom.setInsPeriodUnit("Y");
    bom.setInsPeriod("10");
    bom.setPayMode("T");
    bom.setAmount(10000.0);
    bom.setInsuredBirthday("1990-01-01");

    System.out.println("start");

    StopWatch sw = new StopWatch();
    sw.start();
    //		for (int j = 0; j < 10000; j++) {
    for (int i = 80; i < 90; i++) {
      bom.setInsuredBirthday("19" + i + "-01-01");
      int r = ruleEngine.execute("com.enci.ecp.bizprocess.product.rule.premiumcalc_00177000", bom);
      //			System.out.println(bom.getTotalPremium());
    }
    //		}
    sw.stop();
    System.out.println(sw.prettyPrint());
  }
Esempio n. 22
0
 public static void main(String[] args) {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("ApplicationBeans.xml");
   App main = context.getBean(App.class);
   main.run();
   context.close();
 }
Esempio n. 23
0
 @Before
 public void Before() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
   lampService = (LampService) context.getBean("lampService");
   System.out.println(lampService);
 }
Esempio n. 24
0
  public void testPublishWithEventAwareTransformer() throws Exception {
    CountDownLatch transformerLatch = new CountDownLatch(1);

    TestEventAwareTransformer trans = new TestEventAwareTransformer();
    trans.setLatch(transformerLatch);
    managementContext.getRegistry().registerTransformer(trans);

    MuleApplicationEvent event =
        new MuleApplicationEvent(
            "Event from a spring bean", "vm://testBean2?transformers=dummyTransformer");

    TestSubscriptionEventBean bean2 =
        (TestSubscriptionEventBean) context.getBean("testSubscribingEventBean2");
    assertNotNull(bean2);

    Latch whenFinished = new Latch();
    bean2.setEventCallback(new CountingEventCallback(eventCounter1, 1, whenFinished));

    // publish asynchronously
    this.doPublish(event, 1);

    whenFinished.await(3000, TimeUnit.MILLISECONDS);
    assertTrue(transformerLatch.await(3000, TimeUnit.MILLISECONDS));
    assertEquals(1, eventCounter1.get());
  }
Esempio n. 25
0
  public void testReceivingASpringEvent() throws Exception {
    TestApplicationEventBean bean =
        (TestApplicationEventBean) context.getBean("testEventSpringBean");
    assertNotNull(bean);

    final Latch whenFinished = new Latch();
    EventCallback callback =
        new EventCallback() {
          public void eventReceived(UMOEventContext context, Object o) throws Exception {
            assertNull(context);
            if (o instanceof TestApplicationEvent) {
              if (eventCounter1.incrementAndGet() == 1) {
                whenFinished.countDown();
              }
            }
          }
        };

    bean.setEventCallback(callback);

    context.publishEvent(new TestApplicationEvent(context));

    whenFinished.await(3000, TimeUnit.MILLISECONDS);
    assertEquals(1, eventCounter1.get());
  }
Esempio n. 26
0
  private void commandPong(DeferredResult<Result> defResult, String usernameFromToken) {
    UsersService usersServ = context.getBean(UsersService.class);

    usersServ.updateCallsForUser(usernameFromToken);
    Users user = usersServ.getUserByName(usernameFromToken).get(0);
    defResult.setResult(new Result("pong", user.getNumberOfCalls()));
  }
Esempio n. 27
0
  public static void main(String[] args) {
    ClassPathXmlApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("/mon/spring-http.xml", "spring-orac.xml");
    final EventBus eventBus = applicationContext.getBean("eventBus", EventBus.class);
    eventBus.register(new BothSub());

    eventBus.start();

    /* final CountDownLatch countDownLatch = new CountDownLatch(1);
    for (int i = 0; i < 10 ; i++) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int a = 0; a < 10 ; a++) {
                    int v = a % 3;
                    if(a % 3 != 0 ) {
                        Threads.sleep(1000 * v);
                    }
                    eventBus.publish(new EventA());//发送事件消息
                }
            }
        }).start();
    }
    countDownLatch.countDown();*/
  }
Esempio n. 28
0
  /** @param args the command line arguments */
  public static void main(String args[]) {
    ClassPathXmlApplicationContext context =
        new ClassPathXmlApplicationContext(
            new String[] {
              "xml/custom/collector-beans.xml",
              "xml/global/global-beans.xml",
              "xml/custom/swing.xml"
            });
    final OPCClientGlance opcCollectorGlance =
        (OPCClientGlance) context.getBean("opcCollectorGlance");

    java.awt.EventQueue.invokeLater(
        new Runnable() {
          public void run() {
            SelectOPCItemView dialog =
                new SelectOPCItemView(
                    new javax.swing.JFrame(), null, true, opcCollectorGlance, 0, 0);
            dialog.addWindowListener(
                new java.awt.event.WindowAdapter() {
                  public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                  }
                });
            dialog.setVisible(true);
          }
        });
  }
 public void testSerializableWithoutPreviousUsage() throws Exception {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("annotationDrivenProxyTargetClassTests.xml", getClass());
   TransactionalService service = context.getBean("service", TransactionalService.class);
   service = (TransactionalService) SerializationTestUtils.serializeAndDeserialize(service);
   service.setSomething("someName");
 }
Esempio n. 30
0
 public static void main(String[] args) {
   ClassPathXmlApplicationContext ac =
       new ClassPathXmlApplicationContext(new String[] {"config.xml"});
   Hello h = (Hello) ac.getBean("hello");
   System.out.println(h.getWho() + ":");
   h.sayHi();
 }