Java 类org.apache.camel.NoSuchBeanException 实例源码

项目:Camel    文件:ManagedBeanProcessor.java   
@Override
public String getBeanClassName() {
    if (beanClassName != null) {
        return beanClassName;
    }
    try {
        Object bean = getProcessor().getBean();
        if (bean != null) {
            beanClassName = ObjectHelper.className(bean);
        }
    } catch (NoSuchBeanException e) {
        // ignore
    }

    return beanClassName;
}
项目:Camel    文件:JndiRegistry.java   
public <T> T lookupByNameAndType(String name, Class<T> type) {
    Object answer = lookupByName(name);

    // just to be safe
    if (answer == null) {
        return null;
    }

    try {
        return type.cast(answer);
    } catch (Throwable e) {
        String msg = "Found bean: " + name + " in JNDI Context: " + context
                + " of type: " + answer.getClass().getName() + " expected type was: " + type;
        throw new NoSuchBeanException(name, msg, e);
    }
}
项目:Camel    文件:SimpleRegistry.java   
public <T> T lookupByNameAndType(String name, Class<T> type) {
    Object answer = lookupByName(name);

    // just to be safe
    if (answer == null) {
        return null;
    }

    try {
        return type.cast(answer);
    } catch (Throwable e) {
        String msg = "Found bean: " + name + " in SimpleRegistry: " + this
                + " of type: " + answer.getClass().getName() + " expected type was: " + type;
        throw new NoSuchBeanException(name, msg, e);
    }
}
项目:Camel    文件:RegistryBean.java   
public Object getBean() throws NoSuchBeanException {
    // must always lookup bean first
    Object value = lookupBean();

    if (value != null) {
        // could be a class then create an instance of it
        if (value instanceof Class) {
            // bean is a class so create an instance of it
            value = context.getInjector().newInstance((Class<?>)value);
        }
        return value;
    }

    // okay bean is not in registry, so try to resolve if its a class name and create a shared instance
    if (clazz == null) {
        clazz = context.getClassResolver().resolveClass(name);
    }

    if (clazz == null) {
        // no its not a class then we cannot find the bean
        throw new NoSuchBeanException(name);
    }

    // bean is a class so create an instance of it
    return context.getInjector().newInstance(clazz);
}
项目:Camel    文件:CamelPostProcessorHelperTest.java   
public void testEndpointInjectProducerTemplateFieldNameUnknown() throws Exception {
    CamelPostProcessorHelper helper = new CamelPostProcessorHelper(context);

    MyEndpointInjectProducerTemplateNameUnknown bean = new MyEndpointInjectProducerTemplateNameUnknown();
    Field field = bean.getClass().getField("producer");

    EndpointInject endpointInject = field.getAnnotation(EndpointInject.class);
    Class<?> type = field.getType();
    String propertyName = "producer";

    try {
        helper.getInjectionValue(type, endpointInject.uri(), endpointInject.ref(), endpointInject.property(), propertyName, bean, "foo");
        fail("Should throw exception");
    } catch (NoSuchBeanException e) {
        assertEquals("No bean could be found in the registry for: unknown of type: org.apache.camel.Endpoint", e.getMessage());
    }
}
项目:Camel    文件:MethodCallBeanRefNotFoundTest.java   
public void testMethodCallBeanRefNotFound() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:a").routeId("a").split().method("foo", "hello").to("mock:a");

            from("direct:b").routeId("b").split().method("bar", "hello").to("mock:b");
        }
    });
    try {
        context.start();
        fail("Should have thrown exception");
    } catch (FailedToCreateRouteException e) {
        assertEquals("b", e.getRouteId());
        NoSuchBeanException cause = assertIsInstanceOf(NoSuchBeanException.class, e.getCause());
        assertEquals("bar", cause.getName());
    }
}
项目:Camel    文件:BeanRefNotFoundTest.java   
public void testBeanRefNotFound() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:a").routeId("a").bean("foo").to("mock:a");

            from("direct:b").routeId("b").bean("bar").to("mock:b");
        }
    });
    try {
        context.start();
        fail("Should have thrown exception");
    } catch (FailedToCreateRouteException e) {
        assertEquals("b", e.getRouteId());
        NoSuchBeanException cause = assertIsInstanceOf(NoSuchBeanException.class, e.getCause());
        assertEquals("bar", cause.getName());
    }
}
项目:Camel    文件:JavaDslTransactedNoTXManagerTest.java   
public void testTransactedNoTXManager() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .transacted()
                .to("mock:result");
        }
    });
    try {
        context.start();
        fail("Should have thrown an exception");
    } catch (FailedToCreateRouteException e) {
        NoSuchBeanException cause = assertIsInstanceOf(NoSuchBeanException.class, e.getCause());
        assertEquals("No bean could be found in the registry of type: PlatformTransactionManager", cause.getMessage());
    }
}
项目:Camel    文件:ConsulRegistry.java   
public void remove(String key) {
    // create session to avoid conflicts (not sure if that is safe enough)
    SessionClient sessionClient = consul.sessionClient();
    String sessionName = "session_" + UUID.randomUUID().toString();

    SessionCreatedResponse response = sessionClient
            .createSession(ImmutableSession.builder().name(sessionName).build());
    String sessionId = response.getId();
    kvClient = consul.keyValueClient();
    String lockKey = "lock_" + key;
    kvClient.acquireLock(lockKey, sessionName, sessionId);
    Object object = lookupByName(key);
    if (object == null) {
        String msg = "Bean with key '" + key + "' did not exist in Consul Registry.";
        throw new NoSuchBeanException(msg);
    }
    kvClient.deleteKey(key);
    kvClient.deleteKey(object.getClass().getName() + "/" + key);
    kvClient.releaseLock(lockKey, sessionId);
}
项目:microservice-bundle    文件:GuiceRegistry.java   
@Override
public <T> T lookupByNameAndType(String name, Class<T> type) {
  Object answer = lookupByName(name);

  if (answer != null) {
    try {
      return type.cast(answer);
    } catch (ClassCastException e) {
      String msg = "Found bean: " + name + " in GuiceRegistry: " + this + " of type: " + answer.getClass().getName() + " expected type was: " + type;
      logger.error(msg, e);
      throw new NoSuchBeanException(name, msg, e);
    }
  } else {
    return null;
  }
}
项目:syndesis    文件:VerifierEndpoint.java   
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{id}")
public List<VerifierResponse> verify(@PathParam("id") String connectorId, Map<String, Object> parameters) {
    List<VerifierResponse> answer;
    Verifier verifier;

    try {
        // First find try to lookup the verifier from the application context
        verifier = applicationContext.getBean(connectorId, Verifier.class);
    } catch (NoSuchBeanDefinitionException|NoSuchBeanException ignored) {
        LOGGER.debug("No bean of type: {} with id: {} found in application context, switch to factory finder", Verifier.class.getName(), connectorId);

        verifier = null;

        try {
            // Then fallback to camel's factory finder
            final FactoryFinder finder = camelContext.getFactoryFinder(RESOURCE_PATH);
            final Class<?> type = finder.findClass(connectorId);

            verifier = (Verifier) camelContext.getInjector().newInstance(type);
        } catch (Exception e) {
            LOGGER.warn("No factory finder of type: {} for id: {}", Verifier.class.getName(), connectorId, e);
        }
    }


    if (verifier != null) {
        answer = verifier.verify(camelContext, connectorId, parameters);
        answer = filterExceptions(answer);
    } else {
        answer = Collections.singletonList(createUnsupportedResponse(connectorId));
    }


    return answer;
}
项目:Camel    文件:CamelContextHelper.java   
/**
 * Look up the given named bean in the {@link org.apache.camel.spi.Registry} on the
 * {@link CamelContext} or throws {@link NoSuchBeanException} if not found.
 */
public static Object mandatoryLookup(CamelContext context, String name) {
    Object answer = lookup(context, name);
    if (answer == null) {
        throw new NoSuchBeanException(name);
    }
    return answer;
}
项目:Camel    文件:CamelContextHelper.java   
/**
 * Look up the given named bean of the given type in the {@link org.apache.camel.spi.Registry} on the
 * {@link CamelContext} or throws NoSuchBeanException if not found.
 */
public static <T> T mandatoryLookup(CamelContext context, String name, Class<T> beanType) {
    T answer = lookup(context, name, beanType);
    if (answer == null) {
        throw new NoSuchBeanException(name, beanType.getName());
    }
    return answer;
}
项目:Camel    文件:CamelPostProcessorHelper.java   
public Object getInjectionBeanValue(Class<?> type, String name) {
    if (ObjectHelper.isEmpty(name)) {
        Set<?> found = getCamelContext().getRegistry().findByType(type);
        if (found == null || found.isEmpty()) {
            throw new NoSuchBeanException(name, type.getName());
        } else if (found.size() > 1) {
            throw new NoSuchBeanException("Found " + found.size() + " beans of type: " + type + ". Only one bean expected.");
        } else {
            // we found only one
            return found.iterator().next();
        }
    } else {
        return CamelContextHelper.mandatoryLookup(getCamelContext(), name, type);
    }
}
项目:Camel    文件:BeanProcessor.java   
protected void doStart() throws Exception {
    // optimize to only get (create) a processor if really needed
    if (beanHolder.supportProcessor() && allowProcessor(method, beanHolder.getBeanInfo())) {
        processor = beanHolder.getProcessor();
        ServiceHelper.startService(processor);
    } else if (beanHolder instanceof ConstantBeanHolder) {
        try {
            // Start the bean if it implements Service interface and if cached
            // so meant to be reused
            ServiceHelper.startService(beanHolder.getBean());
        } catch (NoSuchBeanException e) {
            // ignore
        }
    }
}
项目:Camel    文件:BeanProcessor.java   
protected void doStop() throws Exception {
    if (processor != null) {
        ServiceHelper.stopService(processor);
    } else if (beanHolder instanceof ConstantBeanHolder) {
        try {
            // Stop the bean if it implements Service interface and if cached
            // so meant to be reused
            ServiceHelper.stopService(beanHolder.getBean());
        } catch (NoSuchBeanException e) {
            // ignore
        }
    }
}
项目:Camel    文件:BeanProducer.java   
@Override
protected void doStart() throws Exception {
    super.doStart();

    if (processor.getBeanHolder() instanceof ConstantBeanHolder) {
        try {
            // Start the bean if it implements Service interface and if cached
            // so meant to be reused
            ServiceHelper.startService(processor.getBean());
            beanStarted = true;
        } catch (NoSuchBeanException e) {
        }
    }
}
项目:Camel    文件:BeanProducer.java   
@Override
protected void doStop() throws Exception {
    if (beanStarted) {
        try {
            // Stop the bean if it implements Service interface and if cached
            // so meant to be reused
            ServiceHelper.stopService(processor.getBean());
            beanStarted = false;
        } catch (NoSuchBeanException e) {
        }
    }

    super.doStop();
}
项目:Camel    文件:ExchangeHelperTest.java   
public void testNoSuchBean() throws Exception {
    try {
        ExchangeHelper.lookupMandatoryBean(exchange, "foo");
        fail("Should have thrown an exception");
    } catch (NoSuchBeanException e) {
        assertEquals("No bean could be found in the registry for: foo", e.getMessage());
        assertEquals("foo", e.getName());
    }
}
项目:Camel    文件:ExchangeHelperTest.java   
public void testNoSuchBeanType() throws Exception {
    try {
        ExchangeHelper.lookupMandatoryBean(exchange, "foo", String.class);
        fail("Should have thrown an exception");
    } catch (NoSuchBeanException e) {
        assertEquals("No bean could be found in the registry for: foo", e.getMessage());
        assertEquals("foo", e.getName());
    }
}
项目:Camel    文件:JndiRegistryTest.java   
public void testLookupByType() throws Exception {
    JndiRegistry jndi = new JndiRegistry(JndiTest.createInitialContext());
    jndi.bind("foo", new SimpleLanguage());
    jndi.bind("bar", "Hello bar");

    assertEquals("Hello bar", jndi.lookup("bar"));
    assertEquals("Hello bar", jndi.lookupByName("bar"));
    assertEquals("Hello bar", jndi.lookupByNameAndType("bar", String.class));
    assertNull(jndi.lookup("unknown"));
    assertNull(jndi.lookupByName("unknown"));

    try {
        assertNull(jndi.lookupByNameAndType("bar", Language.class));
        fail("Should throw exception");
    } catch (NoSuchBeanException e) {
        // expected
    }

    assertNotNull(jndi.lookupByNameAndType("foo", Language.class));
    assertNotNull(jndi.lookupByNameAndType("foo", SimpleLanguage.class));
    assertSame(jndi.lookupByNameAndType("foo", Language.class), jndi.lookupByNameAndType("foo", SimpleLanguage.class));

    Map<String, ?> set = jndi.lookupByType(Language.class);
    assertNotNull(set);
    assertEquals(1, set.size());

    String key = set.keySet().iterator().next();
    assertEquals("foo", key);
    assertSame(jndi.lookupByName("foo"), set.values().iterator().next());
}
项目:Camel    文件:CamelPostProcessorHelperTest.java   
public void testBeanInjectNotFound() throws Exception {
    CamelPostProcessorHelper helper = new CamelPostProcessorHelper(context);

    MyBeanInjectBean bean = new MyBeanInjectBean();
    Field field = bean.getClass().getField("foo");

    Class<?> type = field.getType();
    try {
        helper.getInjectionBeanValue(type, "bar");
        fail("Should have thrown exception");
    } catch (NoSuchBeanException e) {
        assertEquals("No bean could be found in the registry for: bar of type: org.apache.camel.impl.FooBar", e.getMessage());
        assertEquals("bar", e.getName());
    }
}
项目:Camel    文件:DefaultComponentTest.java   
public void testResolveAndRemoveReferenceParameterNotInRegistry() {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("date", "#somewhen");
    MyComponent my = new MyComponent(this.context);
    try {
        my.resolveAndRemoveReferenceParameter(parameters, "date", Date.class);
        fail("returned without finding object in registry");
    } catch (NoSuchBeanException e) {
        assertEquals("No bean could be found in the registry for: somewhen of type: java.util.Date", e.getMessage());
    }
}
项目:Camel    文件:DefaultComponentTest.java   
public void testResolveAndRemoveReferenceListParameterInvalidBean() {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("dates", "#bean1,#bean3");
    MyComponent my = new MyComponent(this.context);
    try {
        my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class);
        fail("returned without finding object in registry");
    } catch (NoSuchBeanException e) {
        assertEquals("No bean could be found in the registry for: bean3 of type: java.util.Date", e.getMessage());
    }
}
项目:Camel    文件:SimpleRegistryTest.java   
public void testLookupByNameAndWrongType() {
    try {
        registry.lookupByNameAndType("a", Float.class);
        fail();
    } catch (NoSuchBeanException e) {
        // expected
        assertEquals("a", e.getName());
        assertTrue(e.getMessage().endsWith("of type: java.lang.String expected type was: class java.lang.Float"));
    }
}
项目:Camel    文件:RegistryLookupTypeClassCastExceptionTest.java   
public void testLookupClassCast() throws Exception {
    SimpleRegistry simple = new SimpleRegistry();

    MyClass my = new MyClass();
    simple.put("my", my);

    try {
        simple.lookupByNameAndType("my", String.class);
        fail("Should have thrown exception");
    } catch (NoSuchBeanException e) {
        assertEquals("my", e.getName());
        assertTrue(e.getMessage().endsWith("expected type was: class java.lang.String"));
    }
}
项目:Camel    文件:RegistryLookupTypeClassCastExceptionTest.java   
public void testCamelContextLookupClassCast() throws Exception {
    SimpleRegistry simple = new SimpleRegistry();
    CamelContext context = new DefaultCamelContext(simple);

    MyClass my = new MyClass();
    simple.put("my", my);

    try {
        context.getRegistry().lookupByNameAndType("my", String.class);
        fail("Should have thrown exception");
    } catch (NoSuchBeanException e) {
        assertEquals("my", e.getName());
        assertTrue(e.getMessage().endsWith("expected type was: class java.lang.String"));
    }
}
项目:Camel    文件:RefInvalidTest.java   
public void testInvalid() throws Exception {
    try {
        template.sendBody("ref:xxx", "Hello World");
        fail("Should have thrown an exception");
    } catch (ResolveEndpointFailedException e) {
        assertEquals("Failed to resolve endpoint: ref://xxx due to: No bean could be found in the registry for: xxx of type: org.apache.camel.Endpoint", e.getMessage());
        NoSuchBeanException cause = assertIsInstanceOf(NoSuchBeanException.class, e.getCause());
        assertEquals("xxx", cause.getName());
    }
}
项目:Camel    文件:BeanRegistryBeanTest.java   
public void testNoBean() {
    RegistryBean rb = new RegistryBean(context, "bar");
    try {
        rb.getBean();
        fail("Should have thrown exception");
    } catch (NoSuchBeanException e) {
        assertEquals("bar", e.getName());
    }
}
项目:Camel    文件:ErrorHandlerRouteContextRefNotFoundTest.java   
@Override
protected void setUp() throws Exception {
    try {
        super.setUp();
        fail("Should have thrown exception");
    } catch (RuntimeCamelException e) {
        FailedToCreateRouteException cause = assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause());
        NoSuchBeanException nsbe = assertIsInstanceOf(NoSuchBeanException.class, cause.getCause());
        assertEquals("No bean could be found in the registry for: bar of type: org.apache.camel.builder.ErrorHandlerBuilder", nsbe.getMessage());
    }
}
项目:Camel    文件:ErrorHandlerCamelContextRefNotFoundTest.java   
@Override
protected void setUp() throws Exception {
    try {
        super.setUp();
        fail("Should have thrown an exception");
    } catch (RuntimeCamelException e) {
        FailedToCreateRouteException cause = assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause());
        NoSuchBeanException nsbe = assertIsInstanceOf(NoSuchBeanException.class, cause.getCause());
        assertEquals("No bean could be found in the registry for: foo of type: org.apache.camel.builder.ErrorHandlerBuilder", nsbe.getMessage());
    }
}
项目:Camel    文件:ReactivePostProcessorHelper.java   
@Override
public Object getInjectionBeanValue(Class<?> type, String name) {
    try {
        return super.getInjectionBeanValue(type, name);
    } catch (NoSuchBeanException e) {
        // ignore
    }

    // lets build a proxy
    return "";
}
项目:Camel    文件:ConsulRegistry.java   
@Override
public <T> T lookupByNameAndType(String name, Class<T> type) {
    Object object = lookupByName(name);
    if (object == null) {
        return null;
    }
    try {
        return type.cast(object);
    } catch (Throwable e) {
        String msg = "Found bean: " + name + " in Consul Registry: " + this + " of type: "
                + object.getClass().getName() + "expected type was: " + type;
        throw new NoSuchBeanException(name, msg, e);
    }
}
项目:Camel    文件:TransactedDefinition.java   
protected static Policy doResolvePolicy(RouteContext routeContext, String ref, Class<? extends Policy> type) {
    // explicit ref given so lookup by it
    if (ObjectHelper.isNotEmpty(ref)) {
        return CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), ref, Policy.class);
    }

    // no explicit reference given from user so we can use some convention over configuration here

    // try to lookup by scoped type
    Policy answer = null;
    if (type != null) {
        // try find by type, note that this method is not supported by all registry
        Map<String, ?> types = routeContext.lookupByType(type);
        if (types.size() == 1) {
            // only one policy defined so use it
            Object found = types.values().iterator().next();
            if (type.isInstance(found)) {
                return type.cast(found);
            }
        }
    }

    // for transacted routing try the default REQUIRED name
    if (type == TransactedPolicy.class) {
        // still not found try with the default name PROPAGATION_REQUIRED
        answer = routeContext.lookup(PROPAGATION_REQUIRED, TransactedPolicy.class);
    }

    // this logic only applies if we are a transacted policy
    // still no policy found then try lookup the platform transaction manager and use it as policy
    if (answer == null && type == TransactedPolicy.class) {
        Class<?> tmClazz = routeContext.getCamelContext().getClassResolver().resolveClass("org.springframework.transaction.PlatformTransactionManager");
        if (tmClazz != null) {
            // see if we can find the platform transaction manager in the registry
            Map<String, ?> maps = routeContext.lookupByType(tmClazz);
            if (maps.size() == 1) {
                // only one platform manager then use it as default and create a transacted
                // policy with it and default to required

                // as we do not want dependency on spring jars in the camel-core we use
                // reflection to lookup classes and create new objects and call methods
                // as this is only done during route building it does not matter that we
                // use reflection as performance is no a concern during route building
                Object transactionManager = maps.values().iterator().next();
                LOG.debug("One instance of PlatformTransactionManager found in registry: {}", transactionManager);
                Class<?> txClazz = routeContext.getCamelContext().getClassResolver().resolveClass("org.apache.camel.spring.spi.SpringTransactionPolicy");
                if (txClazz != null) {
                    LOG.debug("Creating a new temporary SpringTransactionPolicy using the PlatformTransactionManager: {}", transactionManager);
                    TransactedPolicy txPolicy = ObjectHelper.newInstance(txClazz, TransactedPolicy.class);
                    Method method;
                    try {
                        method = txClazz.getMethod("setTransactionManager", tmClazz);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeCamelException("Cannot get method setTransactionManager(PlatformTransactionManager) on class: " + txClazz);
                    }
                    ObjectHelper.invokeMethod(method, txPolicy, transactionManager);
                    return txPolicy;
                } else {
                    // camel-spring is missing on the classpath
                    throw new RuntimeCamelException("Cannot create a transacted policy as camel-spring.jar is not on the classpath!");
                }
            } else {
                if (maps.isEmpty()) {
                    throw new NoSuchBeanException(null, "PlatformTransactionManager");
                } else {
                    throw new IllegalArgumentException("Found " + maps.size() + " PlatformTransactionManager in registry. "
                            + "Cannot determine which one to use. Please configure a TransactionTemplate on the transacted policy.");
                }
            }
        }
    }

    return answer;
}
项目:Camel    文件:ConsulRegistryTest.java   
@Test(expected = NoSuchBeanException.class)
public void deleteNonExisting() {
    registry.remove("nonExisting");
}
项目:Camel    文件:ExchangeHelper.java   
/**
 * Performs a lookup in the registry of the mandatory bean name and throws an exception if it could not be found
 *
 * @param exchange the exchange
 * @param name     the bean name
 * @return the bean
 * @throws NoSuchBeanException if no bean could be found in the registry
 */
public static Object lookupMandatoryBean(Exchange exchange, String name) throws NoSuchBeanException {
    Object value = lookupBean(exchange, name);
    if (value == null) {
        throw new NoSuchBeanException(name);
    }
    return value;
}
项目:Camel    文件:ExchangeHelper.java   
/**
 * Performs a lookup in the registry of the mandatory bean name and throws an exception if it could not be found
 *
 * @param exchange the exchange
 * @param name     the bean name
 * @param type     the expected bean type
 * @return the bean
 * @throws NoSuchBeanException if no bean could be found in the registry
 */
public static <T> T lookupMandatoryBean(Exchange exchange, String name, Class<T> type) {
    T value = lookupBean(exchange, name, type);
    if (value == null) {
        throw new NoSuchBeanException(name);
    }
    return value;
}
项目:Camel    文件:BeanHolder.java   
/**
 * Gets the bean.
 *
 * @throws NoSuchBeanException is thrown if the bean cannot be found.
 */
Object getBean() throws NoSuchBeanException;