private void removeUrlFromCamelRoutes(ApplicationOptions options) throws Exception { String servicePath = options.getContextPath(); String toUri = null; if (options.isRequiresSSL()) { toUri = "https://" + InetAddress.getLocalHost().getHostAddress() + ":" + options.getHttpsPort() + options.getContextPath() + "?bridgeEndpoint=true&throwExceptionOnFailure=false&matchOnUriPrefix=true"; } else { toUri = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + options.getPort() + options.getContextPath() + "?bridgeEndpoint=true&throwExceptionOnFailure=false&matchOnUriPrefix=true"; } final InputStream in = com.beyondj.gateway.support.JsonRuleBaseBuilder.newRuleBase().rule(servicePath, toUri).inputStream(); ModelCamelContext modelCamelContext = (ModelCamelContext) camelContext; RouteDefinition routeDefinition = modelCamelContext.getRouteDefinition(GatewayRouter.GATEWAY_ROUTE_ID); if (routeDefinition == null) { int port = Integer.valueOf( config.getProperty(SYSTEM_GATEWAY_ROUTE_PORT)); camelContext.addRoutes(new GatewayRouter(coreMetricsService, scalingDataService, port)); } LoadBalancerDefinition loadBalancerDefinition = getLoadBalancerDefinition(options); Map<String, HttpProxyRule> rules = JsonRuleBaseReader.parseJson(loadBalancerDefinition, in); gatewayRulesService.removeGatewayRules(rules); }
void advice(@Observes CamelContextStartingEvent event, @Uri("mock:messages") MockEndpoint messages, ModelCamelContext context) throws Exception { messages.expectedMessageCount(2); messages.expectedBodiesReceived("Hello", "Bye"); verifier.messages = messages; context.getRouteDefinition("route") .adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() { weaveAddLast().to("mock:messages"); } }); }
@SuppressWarnings("deprecation") protected void checkInitialized() throws Exception { if (initialized.compareAndSet(false, true)) { // Set the CamelContext ErrorHandler here ModelCamelContext camelContext = getContext(); if (camelContext.getErrorHandlerBuilder() != null) { setErrorHandlerBuilder(camelContext.getErrorHandlerBuilder()); } configure(); // mark all route definitions as custom prepared because // a route builder prepares the route definitions correctly already for (RouteDefinition route : getRouteCollection().getRoutes()) { route.markPrepared(); } } }
protected static ErrorHandlerFactory lookupErrorHandlerBuilder(ModelCamelContext camelContext) { @SuppressWarnings("deprecation") ErrorHandlerFactory answer = camelContext.getErrorHandlerBuilder(); if (answer instanceof ErrorHandlerBuilderRef) { ErrorHandlerBuilderRef other = (ErrorHandlerBuilderRef) answer; String otherRef = other.getRef(); if (isErrorHandlerBuilderConfigured(otherRef)) { answer = camelContext.getRegistry().lookupByNameAndType(otherRef, ErrorHandlerBuilder.class); if (answer == null) { throw new IllegalArgumentException("ErrorHandlerBuilder with id " + otherRef + " not found in registry."); } } } return answer; }
protected void assertValidContext(CamelContext context) { assertNotNull("No context found!", context); List<RouteDefinition> routes = ((ModelCamelContext)context).getRouteDefinitions(); LOG.debug("Found routes: " + routes); assertEquals("One Route should be found", 1, routes.size()); for (RouteDefinition route : routes) { List<FromDefinition> inputs = route.getInputs(); assertEquals("Number of inputs", 1, inputs.size()); FromDefinition fromType = inputs.get(0); assertEquals("from URI", "seda:test.a", fromType.getUri()); List<?> outputs = route.getOutputs(); assertEquals("Number of outputs", 1, outputs.size()); } }
@Before public void setUpMocking() throws Exception { ModelCamelContext modelCamelContext = (ModelCamelContext)camelContext; modelCamelContext.getRouteDefinition("mainRoute").adviceWith(modelCamelContext, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints(); } }); modelCamelContext.getRouteDefinition("standardXMLRoute").adviceWith(modelCamelContext, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints(); } }); modelCamelContext.getRouteDefinition("t5XMLRoute").adviceWith(modelCamelContext, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints(); } }); camelContext.start(); }
/** * @return Decimal format from EDI configuration */ private DecimalFormat getDecimalFormatForConfiguration() { final DecimalFormat decimalFormat = (DecimalFormat)NumberFormat.getInstance(); final ModelCamelContext context = getContext(); decimalFormat.setMaximumFractionDigits(Integer.valueOf(Util.resolvePropertyPlaceholders(context, "edi.decimalformat.maximumFractionDigits"))); final boolean isGroupingUsed = Boolean.valueOf(Util.resolvePropertyPlaceholders(context, "edi.decimalformat.isGroupingUsed")); decimalFormat.setGroupingUsed(isGroupingUsed); final DecimalFormatSymbols decimalFormatSymbols = decimalFormat.getDecimalFormatSymbols(); if (isGroupingUsed) { final char groupingSeparator = Util.resolvePropertyPlaceholders(context, "edi.decimalformat.symbol.groupingSeparator").charAt(0); decimalFormatSymbols.setGroupingSeparator(groupingSeparator); } final char decimalSeparator = Util.resolvePropertyPlaceholders(context, "edi.decimalformat.symbol.decimalSeparator").charAt(0); decimalFormatSymbols.setDecimalSeparator(decimalSeparator); decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols); // though it seems redundant, it won't be set otherwise for some reason... return decimalFormat; }
protected void createContextWithGivenRoute(RouteBuilder route, int timeWork) throws Exception, InterruptedException { SimpleRegistry registry = new SimpleRegistry(); ModelCamelContext context = new DefaultCamelContext(registry); Tracer tracer = new Tracer(); tracer.setLogName("MyTracerLog"); tracer.getDefaultTraceFormatter().setShowProperties(false); tracer.getDefaultTraceFormatter().setShowHeaders(false); tracer.getDefaultTraceFormatter().setShowBody(true); context.addInterceptStrategy(tracer); context.addRoutes(route); context.addComponent("activeMq", activeMq); this.camelContext = context; this.ct = context.createConsumerTemplate(); this.pt = context.createProducerTemplate(); context.start(); context.setTracing(false); Thread.sleep(timeWork); context.stop(); }
public static void main(String... args) throws Exception { // 这是camel上下文对象,整个路由的驱动全靠它了。 ModelCamelContext camelContext = new DefaultCamelContext(); // 启动route camelContext.start(); // 将我们编排的一个完整消息路由过程,加入到上下文中 camelContext.addRoutes(new ApacheCamelExample()); /* * ========================== * 为什么我们先启动一个Camel服务 * 再使用addRoutes添加编排好的路由呢? * 这是为了告诉各位读者,Apache Camel支持 动态加载/卸载编排 的路由 * 这很重要,因为后续设计的Broker需要依赖这种能力 * ========================== */ // 通用没有具体业务意义的代码,只是为了保证主线程不退出 synchronized (ApacheCamelExample.class) { ApacheCamelExample.class.wait(); } }
public void copyRoutesToElement(CamelContext context, CamelContextFactoryBean contextElement) { if (context instanceof ModelCamelContext) { copyRoutesToElement(((ModelCamelContext) context).getRouteDefinitions(), contextElement); } else { LOG.error("Invalid camel context! ({})", context.getClass().getName()); } }
private void addUrlToCamelRoutes(ApplicationOptions options) throws Exception { if(options.getDeploymentType() == DeploymentType.SERVLET_CONTAINER) { String servicePath = options.getContextPath(); String toUri = null; if (options.isRequiresSSL()) { toUri = "https://" + InetAddress.getLocalHost().getHostAddress() + ":" + options.getHttpsPort() + options.getContextPath() + "?bridgeEndpoint=true&throwExceptionOnFailure=false&matchOnUriPrefix=true"; } else { toUri = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + options.getPort() + options.getContextPath() + "?bridgeEndpoint=true&throwExceptionOnFailure=false&matchOnUriPrefix=true"; } final InputStream in = com.beyondj.gateway.support.JsonRuleBaseBuilder.newRuleBase().rule(servicePath, toUri).inputStream(); ModelCamelContext modelCamelContext = (ModelCamelContext) camelContext; RouteDefinition routeDefinition = modelCamelContext.getRouteDefinition(GatewayRouter.GATEWAY_ROUTE_ID); if (routeDefinition == null) { int port = Integer.valueOf( config.getProperty(SYSTEM_GATEWAY_ROUTE_PORT)); camelContext.addRoutes(new GatewayRouter(coreMetricsService, scalingDataService, port)); } LoadBalancerDefinition loadBalancerDefinition = getLoadBalancerDefinition(options); Map<String, HttpProxyRule> rules = JsonRuleBaseReader.parseJson(loadBalancerDefinition, in); LOG.debug("ADDING GatewayRule {}", rules); gatewayRulesService.updateGatewayRules(rules); options.setFullUrl(toUri); StartUpValidationMessage startUpValidationMessage = new StartUpValidationMessage(); startUpValidationMessage.setApplicationOptions(options); startUpValidationMessage.setProxyRules(rules); ActorRef postSystemLaunchActor = systemSingletonService.getPostSystemLaunchActor(); postSystemLaunchActor.tell(startUpValidationMessage, getSelf()); } }
/** * Verify the binary can be retrieved from Fedora. The request should <em>not</em> be intercepted. * * @throws Exception if unexpected things go wrong */ @Test public void testRetrieveLargeBinaryFromFedora() throws Exception { // Record 'true' if the intercepting route is triggered final AtomicBoolean intercepted = new AtomicBoolean(false); ctx.getRouteDefinition(INTERCEPT_ROUTE_ID).adviceWith((ModelCamelContext) ctx, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveAddFirst().process((ex) -> intercepted.set(true)); } }); final long expectedSize = (2 * 1024 * 1024) + 1; final long actualSize; final String actualDigest; try (FcrepoResponse r = client.get(binaryResource).perform(); DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) { actualSize = drain(body); actualDigest = asHex(body.getMessageDigest().digest()); } // The resource can be retrieved intact assertEquals(expectedSize, actualSize); assertEquals(binaryResourceSha, actualDigest); // And the request was not proxied by API-X assertFalse(String.format("Unexpected interception of a Fedora resource URI %s by route %s", binaryResource.toString(), INTERCEPT_ROUTE_ID), intercepted.get()); }
/** * Verify the binary can be retrieved through the API-X proxy. The request should be intercepted and proxied by * API-X. * * @throws Exception if unexpected things go wrong */ @Test public void testRetrieveLargeBinaryFromApix() throws Exception { // Record 'true' if the intercepting route is triggered final AtomicBoolean intercepted = new AtomicBoolean(false); ctx.getRouteDefinition(INTERCEPT_ROUTE_ID).adviceWith((ModelCamelContext) ctx, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveAddFirst().process((ex) -> intercepted.set(true)); } }); final long expectedSize = (2 * 1024 * 1024) + 1; final long actualSize; final String actualDigest; final URI proxiedResource = proxied(binaryResource); try (FcrepoResponse r = KarafIT.attempt(30, () -> client.get(proxiedResource).perform()); DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) { actualSize = drain(body); actualDigest = asHex(body.getMessageDigest().digest()); } // The request _was_ proxied by API-X assertTrue(String.format("Expected the retrieval of %s to be proxied by API-X, route id %s", proxiedResource, INTERCEPT_ROUTE_ID), intercepted.get()); // And resource can be retrieved intact assertEquals(expectedSize, actualSize); assertEquals(binaryResourceSha, actualDigest); }
static void advice(@Observes CamelContextStartingEvent event, ModelCamelContext context) throws Exception { // Add a mock endpoint to the end of the route context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() { weaveAddLast().to("mock:outbound"); } }); }
void pipeMatrixStream(@Observes CamelContextStartingEvent event, ModelCamelContext context) throws Exception { context.getRouteDefinition("matrix") .adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() { weaveAddLast().to("mock:matrix"); } }); }
public List<RouteDefinition> getRouteDefinitions() { List<RouteDefinition> answer = new ArrayList<RouteDefinition>(); for (CamelContext camelContext : camelContexts) { answer.addAll(((ModelCamelContext)camelContext).getRouteDefinitions()); } return answer; }
public Object getManagedObjectForRoute(CamelContext context, Route route) { ManagedRoute mr; if (route.supportsSuspension()) { mr = new ManagedSuspendableRoute((ModelCamelContext)context, route); } else { mr = new ManagedRoute((ModelCamelContext)context, route); } mr.init(context.getManagementStrategy()); return mr; }
public ModelCamelContext getContext() { ModelCamelContext context = super.getContext(); if (context == null) { context = createContainer(); setContext(context); } return context; }
public void addRoutesToCamelContext(CamelContext context) throws Exception { // must configure routes before rests configureRoutes((ModelCamelContext) context); configureRests((ModelCamelContext) context); // but populate rests before routes, as we want to turn rests into routes populateRests(); populateRoutes(); }
protected void populateRoutes() throws Exception { ModelCamelContext camelContext = getContext(); if (camelContext == null) { throw new IllegalArgumentException("CamelContext has not been injected!"); } getRouteCollection().setCamelContext(camelContext); camelContext.addRouteDefinitions(getRouteCollection().getRoutes()); }
public void testAdapt() throws Exception { ModelCamelContext mcc = context.adapt(ModelCamelContext.class); assertNotNull(mcc); assertSame(context, mcc); assertEquals("foo", mcc.getRouteDefinitions().get(0).getId()); }
@SuppressWarnings("unchecked") private CamelContext startRouteWithPolicy(String policyBeanName) throws Exception { CamelContext context = new DefaultCamelContext(); List<RouteDefinition> routes = (List<RouteDefinition>)applicationContext.getBean("testRouteContext"); RoutePolicy policy = applicationContext.getBean(policyBeanName, RoutePolicy.class); assertTrue(getTestType() == TestType.SIMPLE ? policy instanceof SimpleScheduledRoutePolicy : policy instanceof CronScheduledRoutePolicy); routes.get(0).routePolicy(policy); ((ModelCamelContext)context).addRouteDefinitions(routes); context.start(); return context; }
@Override protected CamelContext createCamelContext() throws Exception { CamelContext answer = null; Long timeout = getCamelContextCreationTimeout(); if (timeout == null) { answer = CamelBlueprintHelper.getOsgiService(bundleContext, CamelContext.class); } else if (timeout >= 0) { answer = CamelBlueprintHelper.getOsgiService(bundleContext, CamelContext.class, timeout); } else { throw new IllegalArgumentException("getCamelContextCreationTimeout cannot return a negative value."); } // must override context so we use the correct one in testing context = (ModelCamelContext) answer; return answer; }
@Test @InSequence(1) public void adviseCamelContext(ModelCamelContext context) throws Exception { context.getRouteDefinition("route").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() { interceptSendToEndpoint("{{to}}").skipSendToOriginalEndpoint().to("mock:outbound"); } }); context.startAllRoutes(); }
@Override protected void setUp() throws Exception { super.setUp(); if (context != null) { context.stop(); } applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/spring/config/scan/componentScan.xml"); context = applicationContext.getBean("camelScan", ModelCamelContext.class); template = context.createProducerTemplate(); }
@Override protected void setUp() throws Exception { super.setUp(); applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/spring/config/scan/componentScanWithPackages.xml"); context = applicationContext.getBean("camelContext", ModelCamelContext.class); template = context.createProducerTemplate(); }
@Override protected CamelContext createCamelContext() throws Exception { final CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.name=FcrepoSolrIndexerTest)", 10000); context = (ModelCamelContext)ctx; return ctx; }
public static void main(String[] args) throws Exception { // 这是camel上下文对象,整个路由的驱动全靠它了 ModelCamelContext camelContext = new DefaultCamelContext(); // 启动route camelContext.start(); // 首先将两个完整有效的路由注册到Camel服务中 camelContext.addRoutes(new DirectRouterExample().new DirectRouteA()); camelContext.addRoutes(new DirectRouterExample().new DirectRouteB()); // 通用没有具体业务意义的代码,只是为了保证主线程不退出 synchronized (DirectRouterExample.class) { DirectRouterExample.class.wait(); } }
public List<RouteDefinition> listRoutes() { List<RouteDefinition> ret = new ArrayList<RouteDefinition>(); ModelCamelContext mctx = (ModelCamelContext) cb.getCamelContext(); for (RouteDefinition r : mctx.getRouteDefinitions()) { ret.add(r); } return ret; }
/** * Creates new message splitter. * * @param messageService the message service * @param camelCtx the Camel context * @param splitterCallback the callback for getting split messages */ public MessageSplitterImpl(MessageService messageService, ModelCamelContext camelCtx, MessageSplitterCallback splitterCallback) { Assert.notNull(messageService, "the messageService must not be null"); Assert.notNull(camelCtx, "the camelCtx must not be null"); Assert.notNull(splitterCallback, "the splitterCallback must not be null"); this.camelCtx = camelCtx; this.messageService = messageService; this.splitterCallback = splitterCallback; this.executor = camelCtx.getExecutorServiceManager().newThreadPool(this, "MessageSplitter", 1, 3); }
@Before public void before() throws Exception { ModelCamelContext context = (ModelCamelContext)camelContext; context.getRouteDefinition("myRouteWithin").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith("direct:start"); weaveByToString("To[direct:test]").replace().to("mock:result"); } }); context.start(); }
@Override public void configure() throws Exception { ThreadPoolProfile customThreadPoolProfile = new ThreadPoolProfileBuilder("customThreadPoolProfile").poolSize(5).maxQueueSize(100).build(); ModelCamelContext context = getContext(); context.getExecutorServiceManager().registerThreadPoolProfile(customThreadPoolProfile); from("direct:in") .log("Received ${body}:${threadName}") .threads().executorServiceRef("customThreadPoolProfile") .log("Processing ${body}:${threadName}") .transform(simple("${threadName}")) .to("mock:out"); }
public CamelContext createContext(Collection<RouteDefinition> routes) throws Exception { ModelCamelContext context = new DefaultCamelContext(); context.addRouteDefinitions(routes); return context; }
public ModelCamelContext getCamelContext() { return camelContext; }
public void setCamelContext(ModelCamelContext camelContext) { this.camelContext = camelContext; }
public Object getManagedObjectForCamelContext(CamelContext context) { ManagedCamelContext mc = new ManagedCamelContext((ModelCamelContext)context); mc.init(context.getManagementStrategy()); return mc; }