@PostConstruct public void start() throws Exception { camel = new DefaultCamelContext(); camel.start(); final Component component = camel.getComponent(getConnectorAction(), true, false); if (component == null) { log.error("Component {} does not exist", getConnectorAction()); } else { verifier = component.getExtension(verifierExtensionClass).orElse(null); if (verifier == null) { log.warn("Component {} does not support verifier extension", getConnectorAction()); } } }
private ComponentVerifierExtension getComponentVerifierExtension(CamelContext context, String scheme) { if (verifierExtension == null) { synchronized (this) { if (verifierExtension == null) { Component component = context.getComponent(scheme, true, false); if (component == null) { log.error("Component {} does not exist", scheme); } else { verifierExtension = component.getExtension(verifierExtensionClass).orElse(null); if (verifierExtension == null) { log.warn("Component {} does not support verifier extension", scheme); } } } } } return verifierExtension; }
@Test public void shouldPassSpecificationToRestSwaggerComponent() throws Exception { final Component component = camelContext.getComponent("swagger-operation"); assertThat(component).isNotNull(); final String specification = IOUtils.toString(SwaggerConnectorComponentTest.class.getResource("/petstore.json"), StandardCharsets.UTF_8); IntrospectionSupport.setProperties(component, new HashMap<>(Collections.singletonMap("specification", specification))); final Endpoint endpoint = component.createEndpoint("swagger-operation://?operationId=addPet"); assertThat(endpoint).isNotNull(); final Optional<RestSwaggerEndpoint> maybeRestSwagger = camelContext.getEndpoints().stream() .filter(RestSwaggerEndpoint.class::isInstance).map(RestSwaggerEndpoint.class::cast).findFirst(); assertThat(maybeRestSwagger).hasValueSatisfying(restSwagger -> { assertThat(restSwagger.getSpecificationUri()).isNotNull(); assertThat(restSwagger.getOperationId()).isEqualTo("addPet"); }); }
public void ping() throws Exception { // need to create Camel CamelContext camel = new DefaultCamelContext(); // get the connector to use Component mention = camel.getComponent("salesforce-upsert-contact-connector"); Optional<ComponentVerifierExtension> ext = mention.getExtension(ComponentVerifierExtension.class); // the connector must support ping check if its verifiable if (ext.isPresent()) { ComponentVerifierExtension verifier = ext.get(); Map<String, Object> parameters = loadParameters(); ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters); System.out.println("============================================="); System.out.println(""); System.out.println("Ping check result: " + result.getStatus()); System.out.println(""); System.out.println("============================================="); } else { System.out.println("Component does not support ping check"); } }
public void ping() throws Exception { // need to create Camel CamelContext camel = new DefaultCamelContext(); // get the connector to use Component mention = camel.getComponent("twitter-mention-connector"); Optional<ComponentVerifierExtension> ext = mention.getExtension(ComponentVerifierExtension.class); // the connector must support ping check if its verifiable if (ext.isPresent()) { ComponentVerifierExtension verifier = ext.get(); Map<String, Object> parameters = loadParameters(); ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters); System.out.println("============================================="); System.out.println(""); System.out.println("Ping check result: " + result.getStatus()); System.out.println(""); System.out.println("============================================="); } else { System.out.println("Component does not support ping check"); } }
public void ping() throws Exception { // need to create Camel CamelContext camel = new DefaultCamelContext(); // get the connector to use Component get = camel.getComponent("http-get-connector"); Optional<ComponentVerifierExtension> ext = get.getExtension(ComponentVerifierExtension.class); // the connector must support ping check if its verifiable if (ext.isPresent()) { ComponentVerifierExtension verifier = ext.get(); Map<String, Object> parameters = loadParameters(); ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters); System.out.println("============================================="); System.out.println(""); System.out.println("Ping check result: " + result.getStatus()); System.out.println(""); System.out.println("============================================="); } else { System.out.println("Component does not support ping check"); } }
protected Component getComponent(String name, CamelContext context) throws Exception { LOG.trace("Finding Component: {}", name); try { ServiceReference<?>[] refs = bundleContext.getServiceReferences(ComponentResolver.class.getName(), "(component=" + name + ")"); if (refs != null) { for (ServiceReference<?> ref : refs) { Object service = bundleContext.getService(ref); if (ComponentResolver.class.isAssignableFrom(service.getClass())) { ComponentResolver resolver = (ComponentResolver) service; return resolver.resolveComponent(name, context); } } } return null; } catch (InvalidSyntaxException e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }
private static boolean isPropertyPlaceholder(CamelContext context, Object value) { if (context != null) { Component component = context.hasComponent("properties"); if (component != null) { PropertiesComponent pc; try { pc = context.getTypeConverter().mandatoryConvertTo(PropertiesComponent.class, component); } catch (Exception e) { return false; } if (value.toString().contains(pc.getPrefixToken()) && value.toString().contains(pc.getSuffixToken())) { return true; } } } return false; }
@Test public void testGuice() throws Exception { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, GuiceInitialContextFactory.class.getName()); env.put(Injectors.MODULE_CLASS_NAMES, MyModule.class.getName()); InitialContext context = new InitialContext(env); Injector injector = (Injector) context.lookup(Injector.class.getName()); assertNotNull("Found injector", injector); Object value = context.lookup("foo"); assertNotNull("Should have found a value for foo!", value); CamelContext camelContext = injector.getInstance(CamelContext.class); Component component = camelContext.getComponent("foo"); assertThat(component, is(MockComponent.class)); Endpoint endpoint = camelContext.getEndpoint("foo:cheese"); assertThat(endpoint, is(MockEndpoint.class)); }
public Component removeComponent(String componentName) { synchronized (components) { Component oldComponent = components.remove(componentName); if (oldComponent != null) { try { stopServices(oldComponent); } catch (Exception e) { log.warn("Error stopping component " + oldComponent + ". This exception will be ignored.", e); } for (LifecycleStrategy strategy : lifecycleStrategies) { strategy.onComponentRemove(componentName, oldComponent); } } // keep reference to properties component up to date if (oldComponent != null && "properties".equals(componentName)) { propertiesComponent = null; } return oldComponent; } }
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { String splitURI[] = ObjectHelper.splitOnCharacter(remaining, ":", 2); if (splitURI[1] != null) { String contextId = splitURI[0]; String localEndpoint = splitURI[1]; Component component = getCamelContext().getComponent(contextId); if (component != null) { LOG.debug("Attempting to create local endpoint: {} inside the component: {}", localEndpoint, component); Endpoint endpoint = component.createEndpoint(localEndpoint); if (endpoint == null) { // throw the exception tell we cannot find an then endpoint from the given context throw new ResolveEndpointFailedException("Cannot create a endpoint with uri" + localEndpoint + " for the CamelContext Component " + contextId); } else { ContextEndpoint answer = new ContextEndpoint(uri, this, endpoint); answer.setContextId(contextId); answer.setLocalEndpointUrl(localEndpoint); return answer; } } else { throw new ResolveEndpointFailedException("Cannot create the camel context component for context " + contextId); } } else { // the uri is wrong throw new ResolveEndpointFailedException("The uri " + remaining + "from camel context component is wrong"); } }
@Override protected void doStart() throws Exception { Optional<Component> component = createNewBaseComponent(); if (component.isPresent()) { componentSchemeAlias = Optional.of(componentScheme + "-" + componentId); if (!catalog.findComponentNames().contains(componentSchemeAlias)) { catalog.addComponent( componentSchemeAlias.get(), definition.getComponent().getJavaType(), catalog.componentJSonSchema(componentScheme) ); } LOGGER.info("Register component: {} (type: {}) with scheme: {} and alias: {}", this.componentId, component.get().getClass().getName(), this.componentScheme, this.componentSchemeAlias.get() ); // remove old component if present so getCamelContext().removeComponent(this.componentSchemeAlias.get()); // ensure component is started and stopped when Camel shutdown getCamelContext().addService(component, true, true); getCamelContext().addComponent(this.componentSchemeAlias.get(), component.get()); } else { this.componentSchemeAlias = Optional.empty(); } LOGGER.debug("Starting connector: {}", componentId); super.doStart(); }
@Override public ImmutableMap<String, Component> components() { MailComponent mailComponent = new MailComponent(); return ImmutableMap.of( "smtp", mailComponent, "smtps", mailComponent, "freemarker", new FreemarkerComponent() ); }
@Override public ImmutableMap<String, Component> components() { return ImmutableMap.of( "freemarker", new FreemarkerComponent(), "ovhSms", new OvhSmsComponent() ); }
public ArdulinkEndpoint(String uri, Component ardulinkComponent, EndpointConfig config) throws IOException { super(uri, ardulinkComponent); this.config = config; this.link = createLink(); for (Pin pin : config.getPins()) { this.link.startListening(pin); } }
public void onComponentRemove(String name, Component component) { // the agent hasn't been started if (!initialized) { return; } try { Object mc = getManagementObjectStrategy().getManagedObjectForComponent(camelContext, component, name); unmanageObject(mc); } catch (Exception e) { LOG.warn("Could not unregister Component MBean", e); } }
@Test public void testConfiguration() throws Exception { Component component = context().getComponent(componentName); ComponentConfiguration configuration = component.createComponentConfiguration(); SortedMap<String, ParameterConfiguration> parameterConfigurationMap = configuration.getParameterConfigurationMap(); if (verbose) { Set<Map.Entry<String, ParameterConfiguration>> entries = parameterConfigurationMap.entrySet(); for (Map.Entry<String, ParameterConfiguration> entry : entries) { String name = entry.getKey(); ParameterConfiguration config = entry.getValue(); LOG.info("Has name: {} with type {}", name, config.getParameterType().getName()); } } assertParameterConfig(configuration, "format", PayloadFormat.class); assertParameterConfig(configuration, "sObjectName", String.class); assertParameterConfig(configuration, "sObjectFields", String.class); assertParameterConfig(configuration, "updateTopic", boolean.class); configuration.setParameter("format", PayloadFormat.XML); configuration.setParameter("sObjectName", "Merchandise__c"); configuration.setParameter("sObjectFields", "Description__c,Total_Inventory__c"); configuration.setParameter("updateTopic", false); // operation name is base uri configuration.setBaseUri("getSObject"); SalesforceEndpoint endpoint = assertIsInstanceOf(SalesforceEndpoint.class, configuration.createEndpoint()); final SalesforceEndpointConfig endpointConfig = endpoint.getConfiguration(); assertEquals("endpoint.format", PayloadFormat.XML, endpointConfig.getFormat()); assertEquals("endpoint.sObjectName", "Merchandise__c", endpointConfig.getSObjectName()); assertEquals("endpoint.sObjectFields", "Description__c,Total_Inventory__c", endpointConfig.getSObjectFields()); assertEquals("endpoint.updateTopic", false, endpointConfig.isUpdateTopic()); }
public List<String> completeEndpointPath(String componentName, Map<String, Object> endpointParameters, String completionText) throws Exception { if (completionText == null) { completionText = ""; } Component component = context.getComponent(componentName, false); if (component != null) { ComponentConfiguration configuration = component.createComponentConfiguration(); configuration.setParameters(endpointParameters); return configuration.completeEndpointPath(completionText); } else { return new ArrayList<String>(); } }
public String componentParameterJsonSchema(String componentName) throws Exception { // favor using pre generated schema if component has that String json = context.getComponentParameterJsonSchema(componentName); if (json == null) { // okay this requires having the component on the classpath and being instantiated Component component = context.getComponent(componentName); if (component != null) { ComponentConfiguration configuration = component.createComponentConfiguration(); json = configuration.createParameterJsonSchema(); } } return json; }
public AbstractApiEndpoint(String endpointUri, Component component, E apiName, String methodName, ApiMethodHelper<? extends ApiMethod> methodHelper, T endpointConfiguration) { super(endpointUri, component); this.apiName = apiName; this.methodName = methodName; this.methodHelper = methodHelper; this.configuration = endpointConfiguration; }
public void testAutoCreateComponentsOff() { DefaultCamelContext ctx = new DefaultCamelContext(); ctx.disableJMX(); ctx.setAutoCreateComponents(false); Component component = ctx.getComponent("bean"); assertNull(component); }
public Component getComponent(String name, boolean autoCreateComponents, boolean autoStart) { // synchronize the look up and auto create so that 2 threads can't // concurrently auto create the same component. synchronized (components) { Component component = components.get(name); if (component == null && autoCreateComponents) { try { if (log.isDebugEnabled()) { log.debug("Using ComponentResolver: {} to resolve component with name: {}", getComponentResolver(), name); } component = getComponentResolver().resolveComponent(name, this); if (component != null) { addComponent(name, component); if (autoStart && (isStarted() || isStarting())) { // If the component is looked up after the context is started, lets start it up. if (component instanceof Service) { startService((Service)component); } } } } catch (Exception e) { throw new RuntimeCamelException("Cannot auto create component: " + name, e); } } log.trace("getComponent({}) -> {}", name, component); return component; } }
public <T extends Component> T getComponent(String name, Class<T> componentType) { Component component = getComponent(name); if (componentType.isInstance(component)) { return componentType.cast(component); } else { String message; if (component == null) { message = "Did not find component given by the name: " + name; } else { message = "Found component of type: " + component.getClass() + " instead of expected: " + componentType; } throw new IllegalArgumentException(message); } }
public Component resolveComponent(String name) { Component answer = hasComponent(name); if (answer == null) { try { answer = getComponentResolver().resolveComponent(name, this); } catch (Exception e) { throw new RuntimeCamelException("Cannot resolve component: " + name, e); } } return answer; }
public String getComponentDocumentation(String componentName) throws IOException { // use the component factory finder to find the package name of the component class, which is the location // where the documentation exists as well FactoryFinder finder = getFactoryFinder(DefaultComponentResolver.RESOURCE_PATH); try { Class<?> clazz = finder.findClass(componentName); if (clazz == null) { // fallback and find existing component Component existing = hasComponent(componentName); if (existing != null) { clazz = existing.getClass(); } else { return null; } } String packageName = clazz.getPackage().getName(); packageName = packageName.replace('.', '/'); String path = packageName + "/" + componentName + ".html"; ClassResolver resolver = getClassResolver(); InputStream inputStream = resolver.loadResourceAsStream(path); log.debug("Loading component documentation for: {} using class resolver: {} -> {}", new Object[]{componentName, resolver, inputStream}); if (inputStream != null) { try { return IOHelper.loadText(inputStream); } finally { IOHelper.close(inputStream); } } // special for ActiveMQ as it is really just JMS if ("ActiveMQComponent".equals(clazz.getSimpleName())) { return getComponentDocumentation("jms"); } else { return null; } } catch (ClassNotFoundException e) { return null; } }
public String getComponentParameterJsonSchema(String componentName) throws IOException { // use the component factory finder to find the package name of the component class, which is the location // where the documentation exists as well FactoryFinder finder = getFactoryFinder(DefaultComponentResolver.RESOURCE_PATH); try { Class<?> clazz = finder.findClass(componentName); if (clazz == null) { // fallback and find existing component Component existing = hasComponent(componentName); if (existing != null) { clazz = existing.getClass(); } else { return null; } } String packageName = clazz.getPackage().getName(); packageName = packageName.replace('.', '/'); String path = packageName + "/" + componentName + ".json"; ClassResolver resolver = getClassResolver(); InputStream inputStream = resolver.loadResourceAsStream(path); log.debug("Loading component JSON Schema for: {} using class resolver: {} -> {}", new Object[]{componentName, resolver, inputStream}); if (inputStream != null) { try { return IOHelper.loadText(inputStream); } finally { IOHelper.close(inputStream); } } // special for ActiveMQ as it is really just JMS if ("ActiveMQComponent".equals(clazz.getSimpleName())) { return getComponentParameterJsonSchema("jms"); } else { return null; } } catch (ClassNotFoundException e) { return null; } }
/** * Checks whether directory used in ftp/ftps/sftp endpoint URI is relative. * Absolute path will be converted to relative path and a WARN will be printed. * @see <a href="http://camel.apache.org/ftp2.html">FTP/SFTP/FTPS Component</a> * @param ftpComponent * @param configuration */ public static void ensureRelativeFtpDirectory(Component ftpComponent, RemoteFileConfiguration configuration) { if (FileUtil.hasLeadingSeparator(configuration.getDirectoryName())) { String relativePath = FileUtil.stripLeadingSeparator(configuration.getDirectoryName()); LOG.warn(String.format("%s doesn't support absolute paths, \"%s\" will be converted to \"%s\". " + "After Camel 2.16, absolute paths will be invalid.", ftpComponent.getClass().getSimpleName(), configuration.getDirectoryName(), relativePath)); configuration.setDirectory(relativePath); configuration.setDirectoryName(relativePath); } }
public SjmsBatchEndpoint(String endpointUri, Component component, String remaining) { super(endpointUri, component); DestinationNameParser parser = new DestinationNameParser(); if (parser.isTopic(remaining)) { throw new IllegalArgumentException("Only batch consumption from queues is supported. For topics you " + "should use a regular JMS consumer with an aggregator."); } this.destinationName = parser.getShortName(remaining); }
private void bindToRegistry(JndiRegistry jndi) throws Exception { Component comp = new DirectComponent(); comp.setCamelContext(context); Endpoint slow = comp.createEndpoint("direct:somename"); Consumer consumer = slow.createConsumer(new Processor() { public void process(Exchange exchange) throws Exception { template.send("mock:result", exchange); } }); consumer.start(); // bind our endpoint to the registry for ref to lookup jndi.bind("foo", slow); }
public JsonEndpoint(String endpointUri, Component component) { super(endpointUri, component); }
/** * Create the endpoint instance which either happens with a new base component * which has been pre-configured for this connector or we fallback and use * the default component in the camel context */ private Optional<Component> createNewBaseComponent() throws Exception { final String componentClass = definition.getComponent().getJavaType(); final CamelContext context = getCamelContext(); if (componentClass != null) { // configure component with extra options if (!options.isEmpty()) { // Get the list of options from the connector catalog that // are configured to target the endpoint Collection<String> endpointOptions = definition.getEndpointProperties().keySet(); // Check if any of the option applies to the component, if not // there's no need to create a dedicated component. Collection<Map.Entry<String, Object>> entries = options.entrySet().stream() .filter(e -> !endpointOptions.contains(e.getKey())) .collect(Collectors.toList()); if (!entries.isEmpty()) { // create a new instance of this base component final Class<Component> type = context.getClassResolver().resolveClass(componentClass, Component.class); final Component component = context.getInjector().newInstance(type); component.setCamelContext(context); for (Map.Entry<String, Object> entry : entries) { String key = entry.getKey(); Object val = entry.getValue(); LOGGER.debug("Using component option: {}={}", key, val); if (val instanceof String) { val = getCamelContext().resolvePropertyPlaceholders((String) val); } IntrospectionSupport.setProperty(context, component, key, val); } return Optional.of(component); } } } return Optional.empty(); }
public void ping() throws Exception { // need to create Camel CamelContext camel = new DefaultCamelContext(); camel.start(); // get the connector to use Component sqlstored = camel.getComponent("sql-stored-connector"); // the connector must support ping check if its verifiable Optional<SqlStoredConnectorVerifierExtension> vce = sqlstored.getExtension(SqlStoredConnectorVerifierExtension.class); if (vce.isPresent()) { ComponentVerifierExtension verifier = vce.get(); Map<String, Object> parameters = loadParameters(); ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.PARAMETERS, parameters); System.out.println("============================================="); System.out.println(""); System.out.println("Parameters check result: " + result.getStatus()); if (result.getStatus().equals(Result.Status.ERROR)) { System.out.println(result.getErrors()); } System.out.println(""); System.out.println("============================================="); ComponentVerifierExtension.Result result2 = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters); System.out.println("============================================="); System.out.println(""); System.out.println("Ping check result: " + result2.getStatus()); if (result2.getStatus().equals(Result.Status.ERROR)) { System.out.println(result2.getErrors()); } System.out.println(""); System.out.println("============================================="); } else { System.out.println("Component does not support ping check"); } camel.stop(); }
public PLC4XEndpoint(String endpointUri, Component component) { super(endpointUri, component); plcDriverManager = new PlcDriverManager(); }
public SpongeEndpoint(String endpointUri, Component component, Engine engine, String action, Boolean managed) { super(endpointUri, component); this.engine = engine; this.action = action; this.managed = managed != null ? managed : DEFAULT_MANAGED; }
protected OrientDBEndpoint(String endpointUri,Component component,String remaining, Map<String, Object> parameters ) { super(endpointUri,component); this.sqlQuery = remaining; this.parameters = parameters; }
protected OrientDBEndpoint(String endpointUri, Component component) { super(endpointUri,component); }
public MiloServerEndpoint(final String uri, final String itemId, final CamelNamespace namespace, final Component component) { super(uri, component); this.itemId = itemId; this.namespace = namespace; }
default ImmutableMap<String, Component> components() { return ImmutableMap.of(); }
public LuceneEndpoint(String endpointUri, Component component) { super(endpointUri, component); }