@SuppressWarnings("Convert2streamapi") private void unregisterExecutorComponent(Executor... executors) { for (Executor executor : executors) { //unregister beans Registry registry = context.getRegistry(); if (registry instanceof PropertyPlaceholderDelegateRegistry) { registry = ((PropertyPlaceholderDelegateRegistry) registry).getRegistry(); } SimpleRegistry openexRegistry = (SimpleRegistry) registry; Set<Map.Entry<String, Object>> beansEntries = executor.beans().entrySet(); for (Map.Entry<String, Object> beansEntry : beansEntries) { if (openexRegistry.containsKey(beansEntry.getKey())) { openexRegistry.remove(beansEntry.getKey()); } } //unregister components Set<String> keys = executor.components().keySet(); for (String key : keys) { if (context.getComponentNames().contains(key)) { context.removeComponent(key); } } } }
@SuppressWarnings("Convert2streamapi") private void registerExecutorComponent(Executor... executors) { for (Executor executor : executors) { //register beans Registry registry = context.getRegistry(); if (registry instanceof PropertyPlaceholderDelegateRegistry) { registry = ((PropertyPlaceholderDelegateRegistry) registry).getRegistry(); } SimpleRegistry openexRegistry = (SimpleRegistry) registry; Set<Map.Entry<String, Object>> beansEntries = executor.beans().entrySet(); for (Map.Entry<String, Object> beansEntry : beansEntries) { if (!openexRegistry.containsKey(beansEntry.getKey())) { openexRegistry.put(beansEntry.getKey(), beansEntry.getValue()); } } //register components Set<Map.Entry<String, org.apache.camel.Component>> components = executor.components().entrySet(); for (Map.Entry<String, org.apache.camel.Component> entry : components) { if (!context.getComponentNames().contains(entry.getKey())) { context.addComponent(entry.getKey(), entry.getValue()); } } } }
public <T> T getRegistry(Class<T> type) { Registry reg = getRegistry(); // unwrap the property placeholder delegate if (reg instanceof PropertyPlaceholderDelegateRegistry) { reg = ((PropertyPlaceholderDelegateRegistry) reg).getRegistry(); } if (type.isAssignableFrom(reg.getClass())) { return type.cast(reg); } else if (reg instanceof CompositeRegistry) { List<Registry> list = ((CompositeRegistry) reg).getRegistryList(); for (Registry r : list) { if (type.isAssignableFrom(r.getClass())) { return type.cast(r); } } } return null; }
public RegistryBean(Registry registry, CamelContext context, String name) { this.registry = registry; this.context = context; if (name != null) { // for ref it may have "ref:" or "bean:" as prefix by mistake if (name.startsWith("ref:")) { this.name = name.substring(4); } else if (name.startsWith("bean:")) { this.name = name.substring(5); } else { this.name = name; } } else { this.name = null; } }
private FactoryRegistry tryToGetFactoryRegistry() { Function<CamelContext, Registry> f = CamelContext::getRegistry; Function<Registry, Set<FactoryRegistry>> g = r -> r.findByType(FactoryRegistry.class); Function<Set<FactoryRegistry>, FactoryRegistry> h = factoryRegistries -> { if (factoryRegistries.size() > 1) { LOGGER.warn("Number of registered {}: {}", FactoryRegistry.class.getCanonicalName(), factoryRegistries.size()); } if (factoryRegistries.iterator().hasNext()) { return factoryRegistries.iterator().next(); } else { return new DefaultFactoryRegistry(); } }; return Optional.ofNullable(camelContext) .map(f) .map(g) .map(h) .orElse(new DefaultFactoryRegistry()); }
protected CompositeRegistry createRegistry() { final ServiceLoader<Registry> registriesLoaders = ServiceLoader.load(Registry.class, getClass().getClassLoader()); final List<Registry> registries = new ArrayList<Registry>(); registries.add(new JndiRegistry()); if (isEnableCdiIntegration()) { registries.add(new CdiBeanRegistry()); } registries.add(_writeableRegistry); for (Registry registry : registriesLoaders) { registries.add(registry); } return new CompositeRegistry(registries); }
public static <T extends Registry> void addToRegistry(final T registry, final String name, final Object bean) { Registry reg = registry; // Unwrap PropertyPlaceholderDelegateRegistry if (registry instanceof PropertyPlaceholderDelegateRegistry) { reg = ((PropertyPlaceholderDelegateRegistry) reg).getRegistry(); } if (reg instanceof CompositeRegistry) { // getRegistryList() not available in Camel 2.12 SimpleRegistry r = new SimpleRegistry(); r.put(name, bean); ((CompositeRegistry) reg).addRegistry(r); } else if (reg instanceof JndiRegistry) { ((JndiRegistry) reg).bind(name, bean); } else if (reg instanceof SimpleRegistry) { ((SimpleRegistry) reg).put(name, bean); } else { throw new IllegalArgumentException("Couldn't add bean. Unknown registry type: " + reg.getClass()); } if (registry.lookupByName(name) != bean) { throw new IllegalArgumentException("Couldn't add bean. Bean not found from the registry."); } }
/** * Initialize the ClientMappers from Camel registry. Note that this initial * implementation only supports one mapper. * <p> */ private void initClientMapper(Registry registry) throws Exception { Set<ClientMapper> mappers = null; try { // find the one client mapper mappers = registry.findByType(ClientMapper.class); } catch (Exception ignore) { } if (mappers != null && !mappers.isEmpty()) { Object objs[] = mappers.toArray(); getComponentProfile().setClientMapper((ClientMapper) objs[0]); LOG.trace("initClientMapper: using a client mapper from registry"); } else { LOG.trace("initClientMapper: not using a client mapper"); } }
@Override public void configure() throws Exception { final CryptoDataFormat crypto = new CryptoDataFormat("DES", null); from("direct:encrypt") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Registry registry = exchange.getContext().getRegistry(); Message in = exchange.getIn(); Key key = registry.lookupByNameAndType("shared_" + in.getHeader("system"), Key.class); in.setHeader(CryptoDataFormat.KEY, key); } }) .log("Encrypting message: ${body} using ${header[CamelCryptoKey]}") .marshal(crypto) .log("Message encrypted: ${body}") .to("direct:decrypt"); from("direct:decrypt") .log("Decrypting message: ${body} using ${header[CamelCryptoKey]}") .unmarshal(crypto) .log("Message decrypted: ${body}") .to("mock:decrypted"); }
private static DefaultCamelContext createCamelContext(String prefix, String name, Registry registry) { DefaultCamelContext ctx = createWithRegistry(registry); ctx.setName(prefix + name); ctx.disableJMX(); ctx.setStreamCaching(true); return ctx; }
private static DefaultCamelContext createWithRegistry(Registry registry) { if (registry == null) { return new DefaultCamelContext(); } return new DefaultCamelContext(registry); }
public static void registerBean(Registry registry, String beanName, Object bean) { if (registry instanceof SimpleRegistry) { ((SimpleRegistry) registry).put(beanName, bean); } else if (registry instanceof PropertyPlaceholderDelegateRegistry) { Registry wrappedRegistry = ((PropertyPlaceholderDelegateRegistry) registry).getRegistry(); registerBean(wrappedRegistry, beanName, bean); } else if (registry instanceof JndiRegistry) { ((JndiRegistry) registry).bind(beanName, bean); } else { throw new RuntimeException("could not identify the registry type while registering core beans"); } }
private ObjectMapper resolveObjectMapper(Registry registry) { Set<ObjectMapper> mappers = registry.findByType(ObjectMapper.class); if (mappers.size() == 1) { return mappers.iterator().next(); } return new ObjectMapper(); }
public Object lookupByName(String name) { Object answer = null; for (Registry registry : registryList) { answer = registry.lookupByName(name); if (answer != null) { break; } } return answer; }
public <T> Map<String, T> findByTypeWithName(Class<T> type) { Map<String, T> answer = Collections.emptyMap(); for (Registry registry : registryList) { answer = registry.findByTypeWithName(type); if (!answer.isEmpty()) { break; } } return answer; }
public <T> Set<T> findByType(Class<T> type) { Set<T> answer = Collections.emptySet(); for (Registry registry : registryList) { answer = registry.findByType(type); if (!answer.isEmpty()) { break; } } return answer; }
public Registry getRegistry() { if (registry == null) { registry = createRegistry(); setRegistry(registry); } return registry; }
public void setRegistry(Registry registry) { // wrap the registry so we always do property placeholder lookups if (!(registry instanceof PropertyPlaceholderDelegateRegistry)) { registry = new PropertyPlaceholderDelegateRegistry(this, registry); } this.registry = registry; }
/** * Lazily create a default implementation */ protected Registry createRegistry() { JndiRegistry jndi = new JndiRegistry(); try { // getContext() will force setting up JNDI jndi.getContext(); return jndi; } catch (Throwable e) { log.debug("Cannot create javax.naming.InitialContext due " + e.getMessage() + ". Will fallback and use SimpleRegistry instead. This exception is ignored.", e); return new SimpleRegistry(); } }
public void loadDefaultRegistry() { addParameterMapping(Exchange.class, ExpressionBuilder.exchangeExpression()); addParameterMapping(Message.class, ExpressionBuilder.inMessageExpression()); addParameterMapping(Exception.class, ExpressionBuilder.exchangeExceptionExpression()); addParameterMapping(TypeConverter.class, ExpressionBuilder.typeConverterExpression()); addParameterMapping(Registry.class, ExpressionBuilder.registryExpression()); addParameterMapping(CamelContext.class, ExpressionBuilder.camelContextExpression()); }
public static ParameterMappingStrategy createParameterMappingStrategy(CamelContext camelContext) { // lookup in registry first if there is a user define strategy Registry registry = camelContext.getRegistry(); ParameterMappingStrategy answer = registry.lookupByNameAndType(BeanConstants.BEAN_PARAMETER_MAPPING_STRATEGY, ParameterMappingStrategy.class); if (answer == null) { // no then use the default one answer = new DefaultParameterMappingStrategy(); } return answer; }
private static long executePerformanceTest(Registry registry, final String simpleExpression) throws Exception { CamelContext ctx = new DefaultCamelContext(registry); ctx.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").loop(MESSAGE_LOOP_COUNT).setHeader("test").simple(simpleExpression).to("mock:plop"); } }); ctx.start(); Map<String, String> body = new HashMap<String, String>(); body.put("p", "q"); ProducerTemplate template = ctx.createProducerTemplate(); // Initial one, it's a dry start, we don't care about this one. template.sendBody("direct:start", body); // Measure the duration of the executions in nanoseconds long totalNsDuration = 0; for (int i = 0; i < TEST_EXECUTION_COUNT; i++) { long tick = System.nanoTime(); template.sendBody("direct:start", body); totalNsDuration += System.nanoTime() - tick; } ctx.stop(); // Return the average duration in milliseconds return totalNsDuration / TEST_EXECUTION_COUNT / 1000 / 1000; }
public String withRegistry(String body, Registry registry) { assertNotNull(body); assertNotNull(registry); assertNotNull(registry.lookupByName("foo")); assertEquals("Hello", body); return "Registry"; }
private ObjectMapper resolveObjectMapper(Registry registry) { Set<ObjectMapper> mappers = registry.findByType(ObjectMapper.class); if (mappers.size() == 1) { return mappers.iterator().next(); } return defaultMapper; }
@Override protected void initCustomRegistry(BlueprintCamelContext context) { Registry registry = getBeanForType(Registry.class); if (registry != null) { LOG.info("Using custom Registry: " + registry); context.setRegistry(registry); } }
private ObjectMapper resolveObjectMapper(Registry registry) { Set<XmlMapper> mappers = registry.findByType(XmlMapper.class); if (mappers.size() == 1) { return mappers.iterator().next(); } return defaultMapper; }
public static Registry wrapRegistry(CamelContext camelContext, Registry registry, BundleContext bundleContext) { ObjectHelper.notNull(bundleContext, "BundleContext"); LOG.debug("Setting up OSGi ServiceRegistry"); OsgiServiceRegistry osgiServiceRegistry = new OsgiServiceRegistry(bundleContext); // Need to clean up the OSGi service when camel context is closed. camelContext.addLifecycleStrategy(osgiServiceRegistry); CompositeRegistry compositeRegistry = new CompositeRegistry(); compositeRegistry.addRegistry(osgiServiceRegistry); compositeRegistry.addRegistry(registry); return compositeRegistry; }
public OsgiDefaultCamelContext(BundleContext bundleContext, Registry registry) { this.bundleContext = bundleContext; this.registry = registry; OsgiCamelContextHelper.osgiUpdate(this, bundleContext); // setup the application context classloader with the bundle classloader setApplicationContextClassLoader(new BundleDelegatingClassLoader(bundleContext.getBundle())); }
@Override protected Registry createRegistry() { if (registry != null) { return OsgiCamelContextHelper.wrapRegistry(this, registry, bundleContext); } else { return OsgiCamelContextHelper.wrapRegistry(this, super.createRegistry(), bundleContext); } }
protected void initCustomRegistry(SpringCamelContext context) { Registry registry = getBeanForType(Registry.class); if (registry != null) { LOG.info("Using custom Registry: " + registry); context.setRegistry(registry); } }
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { EjbEndpoint answer = new EjbEndpoint(uri, this); answer.setBeanName(remaining); // plugin registry to lookup in jndi for the EJBs Registry registry = new JndiRegistry(getContext()); // and register the bean as a holder on the endpoint BeanHolder holder = new EjbRegistryBean(registry, getCamelContext(), answer.getBeanName()); answer.setBeanHolder(holder); return answer; }
/** * creates a Spring LDAP endpoint * @param remaining name of the Spring LDAP template bean to be used for the LDAP operation * @param parameters key-value pairs to be set on @see org.apache.camel.component.springldap.SpringLdapEndpoint. * Currently supported keys are operation and scope. * 'operation' is defined in org.apache.camel.component.springldap.LdapOperation. * 'scope' must be one of "object", "onelevel", or "subtree". */ @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { CamelContext camelContext = getCamelContext(); Registry registry = camelContext.getRegistry(); LdapTemplate ldapTemplate = registry.lookupByNameAndType(remaining, LdapTemplate.class); Endpoint endpoint = new SpringLdapEndpoint(remaining, ldapTemplate); setProperties(endpoint, parameters); return endpoint; }
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { if (metricRegistry == null) { Registry camelRegistry = getCamelContext().getRegistry(); metricRegistry = getOrCreateMetricRegistry(camelRegistry, METRIC_REGISTRY_NAME); } String metricsName = getMetricsName(remaining); MetricsType metricsType = getMetricsType(remaining); LOG.debug("Metrics type: {}; name: {}", metricsType, metricsName); Endpoint endpoint = new MetricsEndpoint(uri, this, metricRegistry, metricsType, metricsName); setProperties(endpoint, parameters); return endpoint; }
MetricRegistry getOrCreateMetricRegistry(Registry camelRegistry, String registryName) { LOG.debug("Looking up MetricRegistry from Camel Registry for name \"{}\"", registryName); MetricRegistry result = getMetricRegistryFromCamelRegistry(camelRegistry, registryName); if (result == null) { LOG.debug("MetricRegistry not found from Camel Registry for name \"{}\"", registryName); LOG.info("Creating new default MetricRegistry"); result = createMetricRegistry(); } return result; }
MetricRegistry getMetricRegistryFromCamelRegistry(Registry camelRegistry, String registryName) { MetricRegistry registry = camelRegistry.lookupByNameAndType(registryName, MetricRegistry.class); if (registry != null) { return registry; } else { Set<MetricRegistry> registries = camelRegistry.findByType(MetricRegistry.class); if (registries.size() == 1) { return registries.iterator().next(); } } return null; }
@Override protected void doStart() throws Exception { if (metricsRegistry == null) { Registry camelRegistry = getCamelContext().getRegistry(); metricsRegistry = camelRegistry.lookupByNameAndType(MetricsComponent.METRIC_REGISTRY_NAME, MetricRegistry.class); // create a new metricsRegistry by default if (metricsRegistry == null) { metricsRegistry = new MetricRegistry(); } } if (useJmx) { ManagementAgent agent = getCamelContext().getManagementStrategy().getManagementAgent(); if (agent != null) { MBeanServer server = agent.getMBeanServer(); if (server != null) { reporter = JmxReporter.forRegistry(metricsRegistry).registerWith(server).inDomain(jmxDomain).build(); reporter.start(); } } else { throw new IllegalStateException("CamelContext has not enabled JMX"); } } // json mapper this.mapper = new ObjectMapper().registerModule(new MetricsModule(getRateUnit(), getDurationUnit(), false)); if (getRateUnit() == TimeUnit.SECONDS && getDurationUnit() == TimeUnit.SECONDS) { // they both use same units so reuse this.secondsMapper = this.mapper; } else { this.secondsMapper = new ObjectMapper().registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false)); } }