@Test public void testXmlDSL() throws Exception { CamelContext camelContext = new DefaultCamelContext(); // This is normally done by the Spring implemented registry, we keep it simple here... TamayaPropertiesComponent props = new TamayaPropertiesComponent(); props.setTamayaOverrides(true); camelContext.addComponent("properties", props); // Read routes from XML DSL InputStream is = getClass().getResourceAsStream("/META-INF/routes.xml"); RoutesDefinition routes = camelContext.loadRoutesDefinition(is); for(RouteDefinition def: routes.getRoutes()) { camelContext.addRouteDefinition(def); } camelContext.start(); Greeter greeter = new ProxyBuilder(camelContext).endpoint("direct:hello1").build(Greeter.class); assertEquals("Good Bye from Apache Tamaya!", greeter.greet()); greeter = new ProxyBuilder(camelContext).endpoint("direct:hello2").build(Greeter.class); assertEquals("Good Bye from Apache Tamaya!", greeter.greet()); greeter = new ProxyBuilder(camelContext).endpoint("direct:hello3").build(Greeter.class); assertEquals("Good Bye from Apache Tamaya!", greeter.greet()); }
public void addOrUpdateRoutesFromXml(String xml, boolean urlDecode) throws Exception { // decode String as it may have been encoded, from its xml source if (urlDecode) { xml = URLDecoder.decode(xml, "UTF-8"); } InputStream is = context.getTypeConverter().mandatoryConvertTo(InputStream.class, xml); RoutesDefinition def = context.loadRoutesDefinition(is); if (def == null) { return; } try { // add will remove existing route first context.addRouteDefinitions(def.getRoutes()); } catch (Exception e) { // log the error as warn as the management api may be invoked remotely over JMX which does not propagate such exception String msg = "Error updating routes from xml: " + xml + " due: " + e.getMessage(); LOG.warn(msg, e); throw e; } }
/** * Returns the root element to be marshalled as XML * * @return */ public Object marshalRootElement() { if (justRoutes) { RoutesDefinition routes = new RoutesDefinition(); routes.setRoutes(contextElement.getRoutes()); return routes; } else { return contextElement; } }
@Override public void configure() throws Exception { from("file://" + xmlRouteDir + "?noop=true&idempotent=true&delay=5000&include=.*\\.xml") .routeId(this.context.getName() + "-xmlDropInRoute") .description("Consumes Spring xml routes from the routes/xml/" + this.context.getName() + " directory") .process( exchange -> { try (InputStream is = exchange.getIn().getBody(InputStream.class)) { RoutesDefinition routes = context.loadRoutesDefinition(is); context.addRouteDefinitions(routes.getRoutes()); } } ); }
public static RoutesDefinition getRoutesDefinition(String name, String modifier, Map<String,String> attributes) { RoutesDefinitionRuleSet rdrs = getRoutesDefinitionRuleSet(name, modifier, attributes); if (rdrs == null) return null; else return rdrs.getRoutesDefinition(); }
public RoutesDefinitionRuleSet(RoutesDefinition routes, Asset ruleSet) { this.routesDefinition = routes; this.ruleSet = ruleSet; for (RouteDefinition routeDef : routesDefinition.getRoutes()) { routeIds.add(routeDef.getId()); } }
/** * Returns the latest version whose attributes match the custom attribute * criteria specified via "CustomAttributes". * Override to apply additional or non-standard conditions. * @param version */ protected RoutesDefinition getRoutesDefinition(String name, String version) throws AdapterException { String modifier = ""; Map<String,String> params = getHandlerParameters(); if (params != null) { for (String paramName : params.keySet()) { if (modifier.length() == 0) modifier += "?"; else modifier += "&"; modifier += paramName + "=" + params.get(paramName); } } Map<String,String> customAttrs = null; String customAttrString = getAttributeValue(CUSTOM_ATTRIBUTES); if (!StringHelper.isEmpty(customAttrString)) { customAttrs = StringHelper.parseMap(customAttrString); } RoutesDefinitionRuleSet rdrs; if (version == null) rdrs = CamelRouteCache.getRoutesDefinitionRuleSet(name, modifier, customAttrs); else rdrs = CamelRouteCache.getRoutesDefinitionRuleSet(new AssetVersionSpec(name, version), modifier, customAttrs); if (rdrs == null) { throw new AdapterException("Unable to load Camel route: " + name + modifier); } else { super.logdebug("Using RoutesDefinition: " + rdrs.getRuleSet().getLabel()); return rdrs.getRoutesDefinition(); } }
@Test public void testLoadRouteFromXml() throws Exception { assertNotNull("Existing foo route should be there", context.getRoute("foo")); assertEquals(1, context.getRoutes().size()); // test that existing route works MockEndpoint foo = getMockEndpoint("mock:foo"); foo.expectedBodiesReceived("Hello World"); template.sendBody("direct:foo", "Hello World"); foo.assertIsSatisfied(); // load bar route from classpath using JAXB JAXBContext jaxb = new DefaultModelJAXBContextFactory().newJAXBContext(); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); Resource rs = new ClassPathResource("org/apache/camel/itest/jaxb/BarRoute.xml"); Object value = unmarshaller.unmarshal(rs.getInputStream()); // it should be a RoutesDefinition (we can have multiple routes in the same XML file) RoutesDefinition routes = (RoutesDefinition) value; assertNotNull("Should load routes from XML", routes); assertEquals(1, routes.getRoutes().size()); // add the routes to existing CamelContext context.addRouteDefinitions(routes.getRoutes()); assertNotNull("Loaded bar route should be there", context.getRoute("bar")); assertEquals(2, context.getRoutes().size()); // test that loaded route works MockEndpoint bar = getMockEndpoint("mock:bar"); bar.expectedBodiesReceived("Bye World"); template.sendBody("direct:bar", "Bye World"); bar.assertIsSatisfied(); }
@Override public void start(BundleContext bundleContext) throws Exception { try { this.bundleContext = bundleContext; log.debug("Initializing bundle {}.", bundleContext.getBundle().getBundleId()); camelContext = createCamelContext(); camelContext.addRoutes(this); ConfigurationAdmin configurationAdmin = requiredService(ConfigurationAdmin.class); Configuration camelKuraConfig = configurationAdmin.getConfiguration(camelXmlRoutesPid()); if (camelKuraConfig != null && camelKuraConfig.getProperties() != null) { Object routePropertyValue = camelKuraConfig.getProperties().get(camelXmlRoutesProperty()); if (routePropertyValue != null) { InputStream routesXml = new ByteArrayInputStream(routePropertyValue.toString().getBytes()); RoutesDefinition loadedRoutes = camelContext.loadRoutesDefinition(routesXml); camelContext.addRouteDefinitions(loadedRoutes.getRoutes()); } } beforeStart(camelContext); log.debug("About to start Camel Kura router: {}", getClass().getName()); camelContext.start(); producerTemplate = camelContext.createProducerTemplate(); consumerTemplate = camelContext.createConsumerTemplate(); log.debug("Bundle {} started.", bundleContext.getBundle().getBundleId()); } catch (Throwable e) { String errorMessage = "Problem when starting Kura module " + getClass().getName() + ":"; log.warn(errorMessage, e); // Print error to the Kura console. System.err.println(errorMessage); e.printStackTrace(); throw e; } }
private SyntheticBean<?> routesDefinitionBean(RoutesDefinition definition, URL url) { return new SyntheticBean<>(manager, // TODO: should be @Named if the id is set new SyntheticAnnotated(RoutesDefinition.class, manager.createAnnotatedType(RoutesDefinition.class).getTypeClosure(), ANY, DEFAULT), RoutesDefinition.class, new SyntheticInjectionTarget<>(() -> definition), bean -> "imported routes definition " + (hasId(definition) ? "[" + definition.getId() + "] " : "") + "from resource [" + url + "]"); }
private void loadXmlRoutes(ApplicationContext applicationContext, CamelContext camelContext, String directory) throws Exception { LOG.info("Loading additional Camel XML routes from: {}", directory); try { Resource[] xmlRoutes = applicationContext.getResources(directory); for (Resource xmlRoute : xmlRoutes) { LOG.debug("Found XML route: {}", xmlRoute); RoutesDefinition xmlDefinition = camelContext.loadRoutesDefinition(xmlRoute.getInputStream()); camelContext.addRouteDefinitions(xmlDefinition.getRoutes()); } } catch (FileNotFoundException e) { LOG.debug("No XML routes found in {}. Skipping XML routes detection.", directory); } }
/** * Loads a set of route definitions from an XML file. * * @param xmlPath * path to the file containing one or more route definitions * @param camelContext * CamelContext * @param propertyResolver * The property Resolver * @return list of route definitions */ public static List<RouteDefinition> loadRoute(String xmlPath, SwitchYardCamelContext camelContext, PropertyResolver propertyResolver) { List<RouteDefinition> routes = null; try { Object obj = CamelModelFactory.createCamelModelObjectFromXML(xmlPath); // Look for top-level element - camelContext, routes or route if (obj instanceof CamelContextFactoryBean) { routes = processCamelContextElement((CamelContextFactoryBean)obj, camelContext); } else if (obj instanceof RoutesDefinition) { routes = ((RoutesDefinition)obj).getRoutes(); } else if (obj instanceof RouteDefinition) { routes = new ArrayList<RouteDefinition>(1); routes.add((RouteDefinition)obj); } // If we couldn't find a route definition, throw an error if (routes == null) { CamelComponentMessages.MESSAGES.noRoutesFoundInXMLFile(xmlPath); } return routes; } catch (Exception e) { throw new SwitchYardException(e); } }
public static RoutesDefinition getRoutesDefinition(String name) { return getRoutesDefinition(name, null, null); }
public static RoutesDefinition getRoutesDefinition(String name, String modifier) { return getRoutesDefinition(name, modifier, null); }
@Override protected Object invoke(Object pConnection, Object request) throws AdapterException, ConnectionException { try { String routeDefAttr = getAttributeValueSmart(ROUTE_DEF); String routeDefVer = getAttributeValueSmart(ROUTE_DEF_VER); if (routeDefAttr == null) throw new AdapterException("Missing attribute: " + ROUTE_DEF); RoutesDefinition routesDef = getRoutesDefinition(routeDefAttr, routeDefVer); RouteDefinition routeDef = null; if (routesDef.getRoutes().size() == 0) { throw new AdapterException("No routes found in " + routesDef); } if (routesDef.getRoutes().size() > 1) { String routeId = getAttributeValueSmart(ROUTE_ID); if (routeId == null) throw new AdapterException(ROUTE_ID + " attribute required when route definition contains more than one route"); for (RouteDefinition route : routesDef.getRoutes()) { if (routeId.equals(route.getId())) routeDef = route; } if (routeDef == null) throw new AdapterException("Cannot find route ID=" + routeId + " in route definition asset '" + ROUTE_DEF + "'."); } else { routeDef = routesDef.getRoutes().get(0); } Map<String,Object> headers = getHeaders(); if (headers == null) headers = new HashMap<String,Object>(); headers.put("routeId", routeDef.getId()); WorkflowHandler handler = getWorkflowHandler(routeDefAttr); if (handler == null) throw new EventException("No workflow handler for: " + routeDefAttr + ". Make sure that the mdw-camel bundle is started"); return handler.invoke(request, headers); } catch (Exception ex) { logger.severeException(ex.getMessage(), ex); throw new AdapterException(-1, ex.getMessage(), ex); } }
@Override public String dumpRoutesAsXml(boolean resolvePlaceholders) throws Exception { List<RouteDefinition> routes = context.getRouteDefinitions(); if (routes.isEmpty()) { return null; } // use a routes definition to dump the routes RoutesDefinition def = new RoutesDefinition(); def.setRoutes(routes); String xml = ModelHelper.dumpModelAsXml(context, def); // if resolving placeholders we parse the xml, and resolve the property placeholders during parsing if (resolvePlaceholders) { final AtomicBoolean changed = new AtomicBoolean(); InputStream is = new ByteArrayInputStream(xml.getBytes()); Document dom = XmlLineNumberParser.parseXml(is, new XmlLineNumberParser.XmlTextTransformer() { @Override public String transform(String text) { try { String after = getContext().resolvePropertyPlaceholders(text); if (!changed.get()) { changed.set(!text.equals(after)); } return after; } catch (Exception e) { // ignore return text; } } }); // okay there were some property placeholder replaced so re-create the model if (changed.get()) { xml = context.getTypeConverter().mandatoryConvertTo(String.class, dom); RoutesDefinition copy = ModelHelper.createModelFromXml(context, xml, RoutesDefinition.class); xml = ModelHelper.dumpModelAsXml(context, copy); } } return xml; }
public void setRouteCollection(RoutesDefinition routeCollection) { this.routeCollection = routeCollection; }
public RoutesDefinition getRouteCollection() { return this.routeCollection; }
/** * Loads the routes from the given XML content */ public static RoutesDefinition loadRoutesFromXML(ModelCamelContext camelContext, String xml) throws JAXBException { return ModelHelper.createModelFromXml(camelContext, xml, RoutesDefinition.class); }
/** * Loads the routes from the classpath */ public static RoutesDefinition loadRoutesFromClasspath(ModelCamelContext camelContext, String uri) throws JAXBException { InputStream stream = ObjectHelper.loadResourceAsStream(uri); ObjectHelper.notNull(stream, "Could not find resource '" + uri + "' on the ClassLoader"); return ModelHelper.createModelFromXml(camelContext, stream, RoutesDefinition.class); }
/** * Loads the routes from a {@link URL} */ public static RoutesDefinition loadRoutesFromURL(ModelCamelContext camelContext, URL url) throws JAXBException, IOException { ObjectHelper.notNull(url, "url"); return ModelHelper.createModelFromXml(camelContext, url.openStream(), RoutesDefinition.class); }
/** * Loads the routes from a {@link URL} */ public static RoutesDefinition loadRoutesFromURL(ModelCamelContext camelContext, String url) throws IOException, JAXBException { return loadRoutesFromURL(camelContext, new URL(url)); }
/** * Loads the routes from a {@link File} */ public static RoutesDefinition loadRoutesFromFile(ModelCamelContext camelContext, File file) throws JAXBException, FileNotFoundException { ObjectHelper.notNull(file, "file"); return ModelHelper.createModelFromXml(camelContext, new FileInputStream(file), RoutesDefinition.class); }
/** * Loads the routes from a {@link File} */ public static RoutesDefinition loadRoutesFromFile(ModelCamelContext camelContext, String fileName) throws JAXBException, FileNotFoundException { return loadRoutesFromFile(camelContext, new File(fileName)); }
@Produces private RoutesDefinition routes(CamelContext context) throws Exception { try (InputStream routes = getClass().getResourceAsStream("/camel-context-routes.xml")) { return ModelHelper.createModelFromXml(context, routes, RoutesDefinition.class); } }
@Override @Deprecated public RoutesDefinition loadRoutesDefinition(InputStream is) throws Exception { return context.loadRoutesDefinition(is); }
/** * Configures the routes * * @param context the Camel context * @return the routes configured * @throws Exception can be thrown during configuration */ public RoutesDefinition configureRoutes(ModelCamelContext context) throws Exception { setContext(context); checkInitialized(); routeCollection.setCamelContext(context); return routeCollection; }
/** * Loads a collection of route definitions from the given {@link java.io.InputStream}. * * @param is input stream with the route(s) definition to add * @throws Exception if the route definitions could not be loaded for whatever reason * @return the route definitions */ RoutesDefinition loadRoutesDefinition(InputStream is) throws Exception;
public RoutesDefinition getRoutesDefinition() { return routesDefinition; }