@Test
  public void testCreateEndpointWithParameters() throws Exception {
    JmsEndpointComponent component = new JmsEndpointComponent();

    reset(applicationContext);
    expect(applicationContext.containsBean("connectionFactory")).andReturn(false).once();
    expect(applicationContext.containsBean("specialConnectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("specialConnectionFactory"))
        .andReturn(connectionFactory)
        .once();
    replay(applicationContext);

    Endpoint endpoint =
        component.createEndpoint(
            "jms:queuename?connectionFactory=specialConnectionFactory&timeout=10000", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);

    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(), "queuename");
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().isPubSubDomain(), false);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getConnectionFactory(),
        connectionFactory);
    Assert.assertNull(((JmsEndpoint) endpoint).getEndpointConfiguration().getDestination());
    Assert.assertEquals(((JmsEndpoint) endpoint).getEndpointConfiguration().getTimeout(), 10000L);

    verify(applicationContext);
  }
 @Test
 public void testLoaderAndConfig() {
   assertNotNull(ctx);
   assertTrue(ctx.containsBean("yarnCluster"));
   assertTrue(ctx.containsBean("yarnConfiguration"));
   assertTrue(ctx.containsBean("myCustomBean"));
   Configuration config = (Configuration) ctx.getBean("yarnConfiguration");
   assertNotNull(config);
 }
  @Test
  public void testDependencyBeanFromXml() throws Exception {
    assertNotNull(ctx);
    assertTrue(ctx.containsBean("simpleConfig"));
    assertTrue(ctx.containsBean("simpleConfigBeanB"));
    assertTrue(ctx.containsBean("dependencyBean"));

    DependencyBean dependencyBean = ctx.getBean(DependencyBean.class);
    assertThat(dependencyBean, notNullValue());
    assertThat(dependencyBean.getBeanB(), notNullValue());
  }
Beispiel #4
0
  protected void initMule() {
    try {
      // endpointsCache.clear();
      // See if there has been a discriptor explicitly configured
      if (applicationContext.containsBean(EVENT_MULTICASTER_DESCRIPTOR_NAME)) {
        descriptor = (UMODescriptor) applicationContext.getBean(EVENT_MULTICASTER_DESCRIPTOR_NAME);
      }
      // If the mule manager has been initialised in the contain
      // there is not need to do anything here
      if (applicationContext.containsBean("muleManager")) {
        // Register the multicaster descriptor
        registerMulticasterDescriptor();
        return;
      }
      UMOManager manager = MuleManager.getInstance();
      Map map = applicationContext.getBeansOfType(MuleConfiguration.class);
      if (map != null && map.size() > 0) {
        MuleManager.setConfiguration((MuleConfiguration) map.values().iterator().next());
      }
      if (!manager.isStarted()) {
        MuleManager.getConfiguration().setSynchronous(!asynchronous);
        // register any endpointUri mappings
        registerEndpointMappings();
      }
      // tell mule to load component definitions from spring
      SpringContainerContext containerContext = new SpringContainerContext();
      containerContext.setBeanFactory(applicationContext);
      manager.setContainerContext(null);
      manager.setContainerContext(containerContext);

      // see if there are any UMOConnectors to register
      registerConnectors();

      // Next see if there are any UMOTransformers to register
      registerTransformers();

      registerGlobalEndpoints();

      // Register the multicaster descriptor
      registerMulticasterDescriptor();

      if (!manager.isStarted()) {
        manager.start();
      }
    } catch (UMOException e) {
      throw new MuleRuntimeException(SpringMessages.failedToReinitMule(), e);
    }
  }
 @Test
 public void testMongoSingleton() throws Exception {
   assertTrue(ctx.containsBean("noAttrMongo"));
   MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&noAttrMongo");
   assertNull(getField(mfb, "host"));
   assertNull(getField(mfb, "port"));
 }
  private static GrailsDomainClass getDomainClass(Object instance) {
    GrailsDomainClass domainClass =
        GrailsMetaClassUtils.getPropertyIfExists(
            instance, GrailsDomainClassProperty.DOMAIN_CLASS, GrailsDomainClass.class);
    if (domainClass == null) {
      GrailsWebRequest webRequest = GrailsWebRequest.lookup();
      if (webRequest != null) {
        ApplicationContext applicationContext = webRequest.getApplicationContext();

        GrailsApplication grailsApplication =
            applicationContext.containsBean(GrailsApplication.APPLICATION_ID)
                ? applicationContext.getBean(
                    GrailsApplication.APPLICATION_ID, GrailsApplication.class)
                : null;
        if (grailsApplication != null) {
          domainClass =
              (GrailsDomainClass)
                  grailsApplication.getArtefact(
                      DomainClassArtefactHandler.TYPE, instance.getClass().getName());
        }
      }
    }

    return domainClass;
  }
Beispiel #7
0
 @Override
 public Object get(final String key) {
   if (applicationContext.containsBean(key)) {
     return applicationContext.getBean(key);
   }
   return super.get(key);
 }
 @Ignore // TODO: SPR-6310
 @Test
 public void testImportXmlByConvention() {
   ApplicationContext ctx =
       new AnnotationConfigApplicationContext(ImportXmlByConventionConfig.class);
   assertTrue("context does not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean"));
 }
  @Test
  public void testCreateTopicEndpoint() throws Exception {
    JmsEndpointComponent component = new JmsEndpointComponent();

    reset(applicationContext);
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(connectionFactory)
        .once();
    replay(applicationContext);

    Endpoint endpoint = component.createEndpoint("jms:topic:topicname", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);

    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(), "topicname");
    Assert.assertEquals(((JmsEndpoint) endpoint).getEndpointConfiguration().isPubSubDomain(), true);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getConnectionFactory(),
        connectionFactory);
    Assert.assertNull(((JmsEndpoint) endpoint).getEndpointConfiguration().getDestination());
    Assert.assertEquals(((JmsEndpoint) endpoint).getEndpointConfiguration().getTimeout(), 5000L);

    verify(applicationContext);
  }
  @Test
  public void testResolveJmsEndpoint() throws Exception {
    reset(applicationContext);

    expect(applicationContext.getBeansOfType(EndpointComponent.class))
        .andReturn(Collections.<String, EndpointComponent>emptyMap())
        .once();
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(EasyMock.createMock(ConnectionFactory.class))
        .once();

    replay(applicationContext);

    TestContext context = new TestContext();
    context.setApplicationContext(applicationContext);

    DefaultEndpointFactory factory = new DefaultEndpointFactory();
    Endpoint endpoint = factory.create("jms:Sample.Queue.Name", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(),
        "Sample.Queue.Name");

    verify(applicationContext);
  }
 private void trySettingClassLoaderOnContextIfFoundInParent(ApplicationContext parentCtx) {
   if (parentCtx.containsBean(GrailsRuntimeConfigurator.CLASS_LOADER_BEAN)) {
     Object cl = parentCtx.getBean(GrailsRuntimeConfigurator.CLASS_LOADER_BEAN);
     if (cl instanceof ClassLoader) {
       setClassLoaderOnContext((ClassLoader) cl);
     }
   }
 }
  /**
   * Getter for video codec factory.
   *
   * @return Video codec factory
   */
  public VideoCodecFactory getVideoCodecFactory() {
    final IContext context = scope.getContext();
    ApplicationContext appCtx = context.getApplicationContext();
    if (!appCtx.containsBean(VIDEO_CODEC_FACTORY)) {
      return null;
    }

    return (VideoCodecFactory) appCtx.getBean(VIDEO_CODEC_FACTORY);
  }
 @Test
 public void testMongoSingletonWithAttributes() throws Exception {
   assertTrue(ctx.containsBean("defaultMongo"));
   MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&defaultMongo");
   String host = (String) getField(mfb, "host");
   Integer port = (Integer) getField(mfb, "port");
   assertEquals("localhost", host);
   assertEquals(new Integer(27017), port);
 }
Beispiel #14
0
  public synchronized void configureBean(String bn, Object beanInstance, boolean checkWildcards) {

    if (null == appContexts) {
      return;
    }

    if (null == bn) {
      bn = getBeanName(beanInstance);
    }

    if (null == bn) {
      return;
    }
    // configure bean with * pattern style.
    if (checkWildcards) {
      configureWithWildCard(bn, beanInstance);
    }

    final String beanName = bn;
    setBeanWiringInfoResolver(
        new BeanWiringInfoResolver() {
          @Override
          public BeanWiringInfo resolveWiringInfo(Object instance) {
            if (!"".equals(beanName)) {
              return new BeanWiringInfo(beanName);
            }
            return null;
          }
        });

    for (ApplicationContext appContext : appContexts) {
      if (appContext.containsBean(bn)) {
        this.setBeanFactory(appContext.getAutowireCapableBeanFactory());
      }
    }

    try {
      // this will prevent a call into the AbstractBeanFactory.markBeanAsCreated(...)
      // which saves ALL the names into a HashSet.  For URL based configuration,
      // this can leak memory
      if (beanFactory instanceof AbstractBeanFactory) {
        ((AbstractBeanFactory) beanFactory).getMergedBeanDefinition(bn);
      }
      super.configureBean(beanInstance);
      if (LOG.isTraceEnabled()) {
        LOG.trace("Successfully performed injection,used beanName:{}", beanName);
      }
    } catch (NoSuchBeanDefinitionException ex) {
      // users often wonder why the settings in their configuration files seem
      // to have no effect - the most common cause is that they have been using
      // incorrect bean ids
      if (LOG.isDebugEnabled()) {
        LOG.debug("No matching bean {}", beanName);
      }
    }
  }
  private ResourceLoader establishResourceLoader(GrailsApplication application) {
    ApplicationContext ctx = getApplicationContext();

    if (application != null
        && !application.isWarDeployed()
        && ctx.containsBean(GROOVY_PAGE_RESOURCE_LOADER)) {
      return (ResourceLoader) ctx.getBean(GROOVY_PAGE_RESOURCE_LOADER);
    }
    return resourceLoader;
  }
 /**
  * Listener method which waits for a {@link ContextRefreshedEvent} and then extracts the {@link
  * SessionFactory} from the {@link ApplicationContext} and pases it to {@link
  * #setSessionFactory(SessionFactory)}.
  */
 @Override
 public void handleContextRefreshedEvent(ContextRefreshedEvent cre) {
   ApplicationContext ctx = cre.getApplicationContext();
   if (ctx.containsBean("sessionFactory")) {
     SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
     setSessionFactory(sessionFactory);
   } else {
     log.warn("No session factory found. Cannot initialize");
   }
 }
 @SuppressWarnings("rawtypes")
 @Test
 public void testRegionLookup() throws Exception {
   Cache cache = context.getBean(Cache.class);
   Region existing = cache.createRegionFactory().create("existing");
   assertTrue(context.containsBean("lookup"));
   RegionLookupFactoryBean lfb = context.getBean("&lookup", RegionLookupFactoryBean.class);
   assertEquals("existing", TestUtils.readField("name", lfb));
   assertEquals(existing, context.getBean("lookup"));
 }
 @SuppressWarnings("rawtypes")
 @Test
 public void testPublishingReplica() throws Exception {
   assertTrue(context.containsBean("pub"));
   RegionFactoryBean fb = context.getBean("&pub", RegionFactoryBean.class);
   assertTrue(fb instanceof ReplicatedRegionFactoryBean);
   assertEquals(Scope.DISTRIBUTED_ACK, TestUtils.readField("scope", fb));
   assertEquals("publisher", TestUtils.readField("name", fb));
   RegionAttributes attrs = TestUtils.readField("attributes", fb);
   assertFalse(attrs.getPublisher());
 }
 @Test
 public void testSecondMongoDbFactory() throws Exception {
   assertTrue(ctx.containsBean("secondMongoDbFactory"));
   MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory");
   Mongo mongo = (Mongo) getField(dbf, "mongo");
   assertEquals("localhost", mongo.getAddress().getHost());
   assertEquals(27017, mongo.getAddress().getPort());
   assertEquals("joe", getField(dbf, "username"));
   assertEquals("secret", getField(dbf, "password"));
   assertEquals("database", getField(dbf, "databaseName"));
 }
 public static MimeTypeResolver getMimeTypeResolver(GrailsApplication grailsApplication) {
   MimeTypeResolver mimeTypeResolver = null;
   if (grailsApplication != null) {
     ApplicationContext context = grailsApplication.getMainContext();
     if (context != null) {
       if (context.containsBean(MimeTypeResolver.BEAN_NAME)) {
         mimeTypeResolver = context.getBean(MimeTypeResolver.BEAN_NAME, MimeTypeResolver.class);
       }
     }
   }
   return mimeTypeResolver;
 }
  @SuppressWarnings("rawtypes")
  @Test
  public void testComplexReplica() throws Exception {
    assertTrue(context.containsBean("complex"));
    RegionFactoryBean fb = context.getBean("&complex", RegionFactoryBean.class);
    CacheListener[] listeners = TestUtils.readField("cacheListeners", fb);
    assertFalse(ObjectUtils.isEmpty(listeners));
    assertEquals(2, listeners.length);
    assertSame(listeners[0], context.getBean("c-listener"));

    assertSame(context.getBean("c-loader"), TestUtils.readField("cacheLoader", fb));
    assertSame(context.getBean("c-writer"), TestUtils.readField("cacheWriter", fb));
  }
 public Encoder lookupFilteringEncoder() {
   if (filteringEncoder == null
       && applicationContext != null
       && applicationContext.containsBean(FilteringCodecsByContentTypeSettings.BEAN_NAME)) {
     filteringEncoder =
         applicationContext
             .getBean(
                 FilteringCodecsByContentTypeSettings.BEAN_NAME,
                 FilteringCodecsByContentTypeSettings.class)
             .getEncoderForContentType(getResponse().getContentType());
   }
   return filteringEncoder;
 }
  /**
   * リソースマネージャのプロパティを設定します.
   *
   * @param manager
   * @return {@link ResourceManager}
   */
  @SuppressWarnings("unchecked")
  protected ResourceManager setUpResourceManager(DefaultResourceManager manager) {

    manager.setMessageMetadata(messageMetadata());

    // 設定されている場合のみ上書き
    if (applicationContext.containsBean("resourceInterfaceList")) {
      manager.setResourceInterfaceList(
          (List<Class<?>>) applicationContext.getBean("resourceInterfaceList"));
    }

    return manager;
  }
  public RedirectDynamicMethod(ApplicationContext applicationContext) {
    super(METHOD_PATTERN);
    if (applicationContext.containsBean(UrlMappingsHolder.BEAN_ID))
      this.urlMappingsHolder =
          (UrlMappingsHolder) applicationContext.getBean(UrlMappingsHolder.BEAN_ID);

    GrailsApplication application =
        (GrailsApplication) applicationContext.getBean(GrailsApplication.APPLICATION_ID);
    Object o = application.getFlatConfig().get(GRAILS_VIEWS_ENABLE_JSESSIONID);
    if (o instanceof Boolean) {
      useJessionId = (Boolean) o;
    }
    this.applicationContext = applicationContext;
  }
 private static DataBinder getGrailsWebDataBinder(final GrailsApplication grailsApplication) {
   DataBinder dataBinder = null;
   if (grailsApplication != null) {
     final ApplicationContext mainContext = grailsApplication.getMainContext();
     if (mainContext != null && mainContext.containsBean(DATA_BINDER_BEAN_NAME)) {
       dataBinder = mainContext.getBean(DATA_BINDER_BEAN_NAME, DataBinder.class);
     }
   }
   if (dataBinder == null) {
     // this should really never happen in the running app as the binder
     // should always be found in the context
     dataBinder = new GrailsWebDataBinder(grailsApplication);
   }
   return dataBinder;
 }
 /**
  * Return whether the constraint is valid for the owning class
  *
  * @return true if it is
  */
 public boolean isValid() {
   if (applicationContext.containsBean("sessionFactory")) {
     GrailsApplication grailsApplication =
         applicationContext.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
     GrailsDomainClass domainClass =
         (GrailsDomainClass)
             grailsApplication.getArtefact(
                 DomainClassArtefactHandler.TYPE, constraintOwningClass.getName());
     if (domainClass != null) {
       String mappingStrategy = domainClass.getMappingStrategy();
       return mappingStrategy.equals(GrailsDomainClass.GORM)
           || mappingStrategy.equals(AbstractGrailsHibernateDomainClass.HIBERNATE);
     }
   }
   return false;
 }
 @SuppressWarnings("unchecked")
 private <T> T fetchBeanFromAppCtx(String name) {
   if (appContext == null) {
     return null;
   }
   try {
     if (appContext.containsBean(name)) {
       return (T) appContext.getBean(name);
     } else {
       return null;
     }
   } catch (BeansException e) {
     LOG.warn("Bean named '" + name + "' is missing.");
     return null;
   }
 }
  /**
   * リソースプロセッサのプロパティを設定します.
   *
   * @param resourceProcessor
   * @return {@link ResourceProcessor}
   */
  protected ResourceProcessor setUpResourceProcessor(ResourceProcessor resourceProcessor) {

    boolean strategyExists = applicationContext.containsBean("processContinuationStrategy");
    ProcessContinuationStrategy strategy =
        strategyExists
            ? (ProcessContinuationStrategy)
                applicationContext.getBean("processContinuationStrategy")
            : new AlwaysTerminatingStrategy();

    resourceProcessor.setProcessContinuationStrategy(strategy);
    resourceProcessor.setMessageMetadata(messageMetadata());
    resourceProcessor.setResourceConfigurationParameter(resourceConfigurationParameter());
    resourceProcessor.setResourceManager(resourceManager());

    return resourceProcessor;
  }
  public static DataBindingSourceRegistry getDataBindingSourceRegistry(
      GrailsApplication grailsApplication) {
    DataBindingSourceRegistry registry = null;
    if (grailsApplication != null) {
      ApplicationContext context = grailsApplication.getMainContext();
      if (context != null) {
        if (context.containsBean(DataBindingSourceRegistry.BEAN_NAME)) {
          registry =
              context.getBean(DataBindingSourceRegistry.BEAN_NAME, DataBindingSourceRegistry.class);
        }
      }
    }
    if (registry == null) {
      registry = new DefaultDataBindingSourceRegistry();
    }

    return registry;
  }
Beispiel #30
0
 public void initRun(Writer target, GrailsWebRequest webRequest) {
   this.outputStack = GroovyPageOutputStack.currentStack(true, target, false, true);
   this.out = outputStack.getProxyWriter();
   this.webRequest = webRequest;
   final Map map = getBinding().getVariables();
   if (map.containsKey(APPLICATION_CONTEXT)) {
     final ApplicationContext applicationContext =
         (ApplicationContext) map.get(APPLICATION_CONTEXT);
     if (applicationContext != null
         && applicationContext.containsBean(GrailsPluginManager.BEAN_NAME)) {
       final GrailsPluginManager pluginManager =
           applicationContext.getBean(GrailsPluginManager.BEAN_NAME, GrailsPluginManager.class);
       this.pluginContextPath = pluginManager.getPluginPathForInstance(this);
     }
   }
   if (webRequest != null) {
     this.webRequest.setOut(this.out);
   }
   getBinding().setVariable(OUT, this.out);
 }