/** * Store a notification of the application state and hour * * @param context of the Camel app */ @Override public void onContextStop(CamelContext context) { log.debug("Stopped " + context.getName()); InstanceState instanceState = new InstanceState(); instanceState.setName(context.getName()); instanceState.setState(State.Stopped); instanceState.setTimestamp(DateTime.now().toString()); repository.save(instanceState); }
@Override protected Object doExecute() throws Exception { CamelContext camel = camelController.getCamelContext(context); if (camel == null) { System.err.println("CamelContext " + context + " not found."); return null; } BacklogTracer backlogTracer = BacklogTracer.getBacklogTracer(camel); if (backlogTracer == null) { backlogTracer = (BacklogTracer) camel.getDefaultBacklogTracer(); } backlogTracer.setEnabled(true); if (backlogSize != null) { backlogTracer.setBacklogSize(backlogSize); } if (removeOnDump != null) { backlogTracer.setRemoveOnDump(removeOnDump); } backlogTracer.setTracePattern(pattern); backlogTracer.setTraceFilter(filter); System.out.println( "BacklogTracer started on " + camel.getName() + " with size: " + backlogTracer.getBacklogSize()); return null; }
private boolean addRouteToContext( Bean<?> routeBean, Bean<?> contextBean, BeanManager manager, AfterDeploymentValidation adv) { try { CamelContext context = getReference(manager, CamelContext.class, contextBean); try { Object route = getReference(manager, Object.class, routeBean); if (route instanceof RoutesBuilder) { context.addRoutes((RoutesBuilder) route); } else if (route instanceof RouteContainer) { context.addRouteDefinitions(((RouteContainer) route).getRoutes()); } else { throw new IllegalArgumentException( "Invalid routes type [" + routeBean.getBeanClass().getName() + "], " + "must be either of type RoutesBuilder or RouteContainer!"); } return true; } catch (Exception cause) { adv.addDeploymentProblem( new InjectionException( "Error adding routes of type [" + routeBean.getBeanClass().getName() + "] " + "to Camel context [" + context.getName() + "]", cause)); } } catch (Exception exception) { adv.addDeploymentProblem(exception); } return false; }
@Override public List<Map<String, String>> getCamelContexts() throws Exception { List<Map<String, String>> answer = new ArrayList<Map<String, String>>(); List<CamelContext> camelContexts = getLocalCamelContexts(); for (CamelContext camelContext : camelContexts) { Map<String, String> row = new LinkedHashMap<String, String>(); row.put("name", camelContext.getName()); row.put("state", camelContext.getStatus().name()); row.put("uptime", camelContext.getUptime()); if (camelContext.getManagedCamelContext() != null) { row.put("exchangesTotal", "" + camelContext.getManagedCamelContext().getExchangesTotal()); row.put( "exchangesInflight", "" + camelContext.getManagedCamelContext().getExchangesInflight()); row.put("exchangesFailed", "" + camelContext.getManagedCamelContext().getExchangesFailed()); } else { row.put("exchangesTotal", "0"); row.put("exchangesInflight", "0"); row.put("exchangesFailed", "0"); } answer.add(row); } return answer; }
private static Map<String, Integer> computeColumnWidths( final Iterable<CamelContext> camelContexts) throws Exception { if (camelContexts == null) { throw new IllegalArgumentException( "Unable to determine column widths from null Iterable<CamelContext>"); } else { int maxNameLen = 0; int maxStatusLen = 0; int maxUptimeLen = 0; for (final CamelContext camelContext : camelContexts) { final String name = camelContext.getName(); maxNameLen = java.lang.Math.max(maxNameLen, name == null ? 0 : name.length()); final String status = camelContext.getStatus().toString(); maxStatusLen = java.lang.Math.max(maxStatusLen, status == null ? 0 : status.length()); final String uptime = camelContext.getUptime(); maxUptimeLen = java.lang.Math.max(maxUptimeLen, uptime == null ? 0 : uptime.length()); } final Map<String, Integer> retval = new Hashtable<String, Integer>(3); retval.put(NAME_COLUMN_LABEL, maxNameLen); retval.put(STATUS_COLUMN_LABEL, maxStatusLen); retval.put(UPTIME_COLUMN_LABEL, maxUptimeLen); return retval; } }
@Override public Object execute(CamelController camelController, PrintStream out, PrintStream err) throws Exception { final List<CamelContext> camelContexts = camelController.getCamelContexts(); final Map<String, Integer> columnWidths = computeColumnWidths(camelContexts); final String headerFormat = buildFormatString(columnWidths, true); final String rowFormat = buildFormatString(columnWidths, false); if (camelContexts.size() > 0) { out.println( String.format( headerFormat, CONTEXT_COLUMN_LABEL, STATUS_COLUMN_LABEL, UPTIME_COLUMN_LABEL)); out.println(String.format(headerFormat, "-------", "------", "------")); for (final CamelContext camelContext : camelContexts) { out.println( String.format( rowFormat, camelContext.getName(), camelContext.getStatus(), camelContext.getUptime())); } } return null; }
private void afterDeploymentValidation( @Observes AfterDeploymentValidation adv, BeanManager manager) { Collection<CamelContext> contexts = new ArrayList<>(); for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) { contexts.add(getReference(manager, CamelContext.class, context)); } // Add type converters to Camel contexts CdiTypeConverterLoader loader = new CdiTypeConverterLoader(); for (Class<?> converter : converters) { for (CamelContext context : contexts) { loader.loadConverterMethods(context.getTypeConverterRegistry(), converter); } } // Add routes to Camel contexts boolean deploymentException = false; Set<Bean<?>> routes = new HashSet<>(manager.getBeans(RoutesBuilder.class, ANY)); routes.addAll(manager.getBeans(RouteContainer.class, ANY)); for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) { for (Bean<?> route : routes) { Set<Annotation> qualifiers = new HashSet<>(context.getQualifiers()); qualifiers.retainAll(route.getQualifiers()); if (qualifiers.size() > 1) { deploymentException |= !addRouteToContext(route, context, manager, adv); } } } // Let's return to avoid starting misconfigured contexts if (deploymentException) { return; } // Trigger eager beans instantiation (calling toString is necessary to force // the initialization of normal-scoped beans). // FIXME: This does not work with OpenWebBeans for bean whose bean type is an // interface as the Object methods does not get forwarded to the bean instances! eagerBeans.forEach(type -> getReferencesByType(manager, type.getJavaClass(), ANY).toString()); manager .getBeans(Object.class, ANY, STARTUP) .stream() .forEach(bean -> getReference(manager, bean.getBeanClass(), bean).toString()); // Start Camel contexts for (CamelContext context : contexts) { if (ServiceStatus.Started.equals(context.getStatus())) { continue; } logger.info("Camel CDI is starting Camel context [{}]", context.getName()); try { context.start(); } catch (Exception exception) { adv.addDeploymentProblem(exception); } } // Clean-up Stream.of(converters, camelBeans, eagerBeans, cdiBeans).forEach(Set::clear); Stream.of(producerBeans, producerQualifiers).forEach(Map::clear); }
/** Does the given context match this camel context */ private boolean matchContext(String context) { if (ObjectHelper.isNotEmpty(context)) { if (!camelContext.getName().equals(context)) { return false; } } return true; }
/** * Adds a set of routing/configuration rules to the host {@link CamelContext} using the supplied * {@link RouteLoader}. * * @param loader The loader for the routes you wish to load. */ public void load(final RouteLoader loader) { notNull(loader, "Route loader cannot be null."); try { log.debug("Adding routes to context {}.", hostContext.getName()); hostContext.addRoutes(loader.load()); } catch (Exception e) { throw new LifecycleException(e.getLocalizedMessage(), e); } }
private static void manageCamelContext(Container container, CamelContext context) { try { container.manage(context); } catch (Throwable t) { LOG.warn( "Error during manage CamelContext " + context.getName() + ". This exception is ignored.", t); } }
/** * Activates the control channel, which will from now on behave in accordance with the routes you * set up in your bootstrap script(s). * * <p>See {@link ControlChannel#waitShutdown} and {@link ControlChannel#sendShutdownSignal()} for * instructions on shutting down an activated channel. */ public void activate() { try { log.info("Activating control channel."); final CamelContext context = getContext(); log.info("Configuring trace interceptor for {}.", context.getName()); TraceBuilder builder = new TraceBuilder(getConfig(), tracer); context.addInterceptStrategy(builder.build()); log.debug("Starting underlying camel context."); context.start(); } catch (Exception e) { throw new LifecycleException(e.getLocalizedMessage(), e); } }
protected Object executeLocal( LocalCamelController camelController, PrintStream out, PrintStream err) throws Exception { CamelContext camelContext = camelController.getLocalCamelContext(context); if (camelContext == null) { err.println("Camel context " + context + " not found."); return null; } // Setting thread context classloader to the bundle classloader to enable legacy code that // relies on it ClassLoader oldClassloader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(camelContext.getApplicationContextClassLoader()); try { return performContextCommand(camelController, camelContext.getName(), out, err); } finally { Thread.currentThread().setContextClassLoader(oldClassloader); } }
protected Object doExecute() throws Exception { final List<CamelContext> camelContexts = camelController.getCamelContexts(); final Map<String, Integer> columnWidths = computeColumnWidths(camelContexts); final String headerFormat = buildFormatString(columnWidths, true); final String rowFormat = buildFormatString(columnWidths, false); final PrintStream out = System.out; if (camelContexts.size() > 0) { out.println( String.format(headerFormat, NAME_COLUMN_LABEL, STATUS_COLUMN_LABEL, UPTIME_COLUMN_LABEL)); for (final CamelContext camelContext : camelContexts) { out.println( String.format( rowFormat, camelContext.getName(), camelContext.getStatus(), camelContext.getUptime())); } } return null; }
@Test public void shouldUseCamelContextFromXml() { assertNotNull(camelContext); assertEquals("xmlCamelContext", camelContext.getName()); }
public Camel(CamelContext camelContext, String version) { setName(camelContext.getName()); setVersion(version); }
public void clear(CamelContext context) { clearForContext(context.getName()); }
public void disable(CamelContext context) { disableForContext(context.getName()); }
public void enable(CamelContext context) { enableForContext(context.getName()); }
@Override public String toString() { return "TransformerRegistry for " + context.getName() + ", capacity: " + getMaxCacheSize(); }
public Camel(CamelContext camelContext) { setName(camelContext.getName()); }
public void onContextStart(CamelContext context) throws VetoCamelContextStartException { Object mc = getManagementObjectStrategy().getManagedObjectForCamelContext(context); String name = context.getName(); String managementName = context.getManagementNameStrategy().getName(); try { boolean done = false; while (!done) { ObjectName on = getManagementStrategy() .getManagementNamingStrategy() .getObjectNameForCamelContext(managementName, name); boolean exists = getManagementStrategy().isManaged(mc, on); if (!exists) { done = true; } else { // okay there exists already a CamelContext with this name, we can try to fix it by // finding a free name boolean fixed = false; // if we use the default name strategy we can find a free name to use String newName = findFreeName(mc, context.getManagementNameStrategy(), name); if (newName != null) { // use this as the fixed name fixed = true; done = true; managementName = newName; } // we could not fix it so veto starting camel if (!fixed) { throw new VetoCamelContextStartException( "CamelContext (" + context.getName() + ") with ObjectName[" + on + "] is already registered." + " Make sure to use unique names on CamelContext when using multiple CamelContexts in the same MBeanServer.", context); } else { LOG.warn( "This CamelContext(" + context.getName() + ") will be registered using the name: " + managementName + " due to clash with an existing name already registered in MBeanServer."); } } } } catch (VetoCamelContextStartException e) { // rethrow veto throw e; } catch (Exception e) { // must rethrow to allow CamelContext fallback to non JMX agent to allow // Camel to continue to run throw ObjectHelper.wrapRuntimeCamelException(e); } // set the name we are going to use if (context instanceof DefaultCamelContext) { ((DefaultCamelContext) context).setManagementName(managementName); } try { manageObject(mc); } catch (Exception e) { // must rethrow to allow CamelContext fallback to non JMX agent to allow // Camel to continue to run throw ObjectHelper.wrapRuntimeCamelException(e); } // yes we made it and are initialized initialized = true; if (mc instanceof ManagedCamelContext) { camelContextMBean = (ManagedCamelContext) mc; } // register any pre registered now that we are initialized enlistPreRegisteredServices(); }
public String getCamelId() { return context.getName(); }
/** * Creates a {@link org.apache.camel.spi.RestConfiguration} instance based on the definition * * @param context the camel context * @return the configuration * @throws Exception is thrown if error creating the configuration */ public RestConfiguration asRestConfiguration(CamelContext context) throws Exception { RestConfiguration answer = new RestConfiguration(); if (component != null) { answer.setComponent(CamelContextHelper.parseText(context, component)); } if (apiComponent != null) { answer.setApiComponent(CamelContextHelper.parseText(context, apiComponent)); } if (scheme != null) { answer.setScheme(CamelContextHelper.parseText(context, scheme)); } if (host != null) { answer.setHost(CamelContextHelper.parseText(context, host)); } if (port != null) { answer.setPort(CamelContextHelper.parseInteger(context, port)); } if (apiContextPath != null) { answer.setApiContextPath(CamelContextHelper.parseText(context, apiContextPath)); } if (apiContextRouteId != null) { answer.setApiContextRouteId(CamelContextHelper.parseText(context, apiContextRouteId)); } if (apiContextIdPattern != null) { // special to allow #name# to refer to itself if ("#name#".equals(apiComponent)) { answer.setApiContextIdPattern(context.getName()); } else { answer.setApiContextIdPattern(CamelContextHelper.parseText(context, apiContextIdPattern)); } } if (apiContextListing != null) { answer.setApiContextListing(apiContextListing); } if (contextPath != null) { answer.setContextPath(CamelContextHelper.parseText(context, contextPath)); } if (hostNameResolver != null) { answer.setRestHostNameResolver(hostNameResolver.name()); } if (bindingMode != null) { answer.setBindingMode(bindingMode.name()); } if (skipBindingOnErrorCode != null) { answer.setSkipBindingOnErrorCode(skipBindingOnErrorCode); } if (enableCORS != null) { answer.setEnableCORS(enableCORS); } if (jsonDataFormat != null) { answer.setJsonDataFormat(jsonDataFormat); } if (xmlDataFormat != null) { answer.setXmlDataFormat(xmlDataFormat); } if (!componentProperties.isEmpty()) { Map<String, Object> props = new HashMap<String, Object>(); for (RestPropertyDefinition prop : componentProperties) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setComponentProperties(props); } if (!endpointProperties.isEmpty()) { Map<String, Object> props = new HashMap<String, Object>(); for (RestPropertyDefinition prop : endpointProperties) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setEndpointProperties(props); } if (!consumerProperties.isEmpty()) { Map<String, Object> props = new HashMap<String, Object>(); for (RestPropertyDefinition prop : consumerProperties) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setConsumerProperties(props); } if (!dataFormatProperties.isEmpty()) { Map<String, Object> props = new HashMap<String, Object>(); for (RestPropertyDefinition prop : dataFormatProperties) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setDataFormatProperties(props); } if (!apiProperties.isEmpty()) { Map<String, Object> props = new HashMap<String, Object>(); for (RestPropertyDefinition prop : apiProperties) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setApiProperties(props); } if (!corsHeaders.isEmpty()) { Map<String, String> props = new HashMap<String, String>(); for (RestPropertyDefinition prop : corsHeaders) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setCorsHeaders(props); } return answer; }