public DefaultTransformerRegistry(CamelContext context) {
   // do not stop on eviction, as the endpoint may still be in use
   super(
       CamelContextHelper.getMaximumEndpointCacheSize(context),
       CamelContextHelper.getMaximumEndpointCacheSize(context),
       false);
   // static map to hold endpoints we do not want to be evicted
   this.staticMap = new ConcurrentHashMap<TransformerKey, Transformer>();
   this.context = context;
 }
Exemplo n.º 2
0
  public TabularData listEips() throws Exception {
    try {
      // find all EIPs
      Map<String, Properties> eips = context.findEips();

      TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.listEipsTabularType());

      // gather EIP detail for each eip
      for (Map.Entry<String, Properties> entry : eips.entrySet()) {
        String name = entry.getKey();
        String title = (String) entry.getValue().get("title");
        String description = (String) entry.getValue().get("description");
        String label = (String) entry.getValue().get("label");
        String type = (String) entry.getValue().get("class");
        String status = CamelContextHelper.isEipInUse(context, name) ? "in use" : "on classpath";
        CompositeType ct = CamelOpenMBeanTypes.listEipsCompositeType();
        CompositeData data =
            new CompositeDataSupport(
                ct,
                new String[] {"name", "title", "description", "label", "status", "type"},
                new Object[] {name, title, description, label, status, type});
        answer.put(data);
      }
      return answer;
    } catch (Exception e) {
      throw ObjectHelper.wrapRuntimeCamelException(e);
    }
  }
Exemplo n.º 3
0
 /** Populates a {@link MapMessage} from a {@link Map} instance. */
 protected void populateMapMessage(MapMessage message, Map<?, ?> map, CamelContext context)
     throws JMSException {
   for (Entry<?, ?> entry : map.entrySet()) {
     String keyString = CamelContextHelper.convertTo(context, String.class, entry.getKey());
     if (keyString != null) {
       message.setObject(keyString, entry.getValue());
     }
   }
 }
  /**
   * Determines if redelivery is enabled by checking if any of the redelivery policy settings may
   * allow redeliveries.
   *
   * @return <tt>true</tt> if redelivery is possible, <tt>false</tt> otherwise
   * @throws Exception can be thrown
   */
  private boolean determineIfRedeliveryIsEnabled() throws Exception {
    // determine if redeliver is enabled either on error handler
    if (getRedeliveryPolicy().getMaximumRedeliveries() != 0) {
      // must check for != 0 as (-1 means redeliver forever)
      return true;
    }
    if (retryWhilePolicy != null) {
      return true;
    }

    // or on the exception policies
    if (!exceptionPolicies.isEmpty()) {
      // walk them to see if any of them have a maximum redeliveries > 0 or retry until set
      for (OnExceptionDefinition def : exceptionPolicies.values()) {

        if (def.getRedeliveryPolicy() != null) {
          String ref = def.getRedeliveryPolicyRef();
          if (ref != null) {
            // lookup in registry if ref provided
            RedeliveryPolicy policy =
                CamelContextHelper.mandatoryLookup(camelContext, ref, RedeliveryPolicy.class);
            if (policy.getMaximumRedeliveries() != 0) {
              // must check for != 0 as (-1 means redeliver forever)
              return true;
            }
          } else {
            Integer max =
                CamelContextHelper.parseInteger(
                    camelContext, def.getRedeliveryPolicy().getMaximumRedeliveries());
            if (max != null && max != 0) {
              // must check for != 0 as (-1 means redeliver forever)
              return true;
            }
          }
        }

        if (def.getRetryWhilePolicy() != null || def.getRetryWhile() != null) {
          return true;
        }
      }
    }

    return false;
  }
Exemplo n.º 5
0
  @Override
  protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
      throws Exception {
    EventBus resolvedEventBus = eventBus;
    if (resolvedEventBus == null) {
      resolvedEventBus =
          CamelContextHelper.mandatoryLookup(getCamelContext(), remaining, EventBus.class);
    }

    return new GuavaEventBusEndpoint(uri, this, resolvedEventBus, listenerInterface);
  }
  protected void configureScheduledPollConsumerProperties(
      Map<String, Object> options, Map<String, Object> consumerProperties) {
    // special for scheduled poll consumers as we want to allow end users to configure its options
    // from the URI parameters without the consumer. prefix
    Map<String, Object> schedulerProperties =
        IntrospectionSupport.extractProperties(options, "scheduler.");
    if (schedulerProperties != null && !schedulerProperties.isEmpty()) {
      setSchedulerProperties(schedulerProperties);
    }

    if (scheduler == null && schedulerName != null) {
      if ("none".equals(schedulerName)) {
        // no cron scheduler in use
        scheduler = null;
      } else if ("spring".equals(schedulerName)) {
        // special for scheduler if its "spring" or "quartz2"
        try {
          Class<? extends ScheduledPollConsumerScheduler> clazz =
              getCamelContext()
                  .getClassResolver()
                  .resolveMandatoryClass(SPRING_SCHEDULER, ScheduledPollConsumerScheduler.class);
          setScheduler(getCamelContext().getInjector().newInstance(clazz));
        } catch (ClassNotFoundException e) {
          throw new IllegalArgumentException(
              "Cannot load "
                  + SPRING_SCHEDULER
                  + " from classpath. Make sure camel-spring.jar is on the classpath.",
              e);
        }
      } else if ("quartz2".equals(schedulerName)) {
        // special for scheduler if its "spring" or "quartz2"
        try {
          Class<? extends ScheduledPollConsumerScheduler> clazz =
              getCamelContext()
                  .getClassResolver()
                  .resolveMandatoryClass(QUARTZ_2_SCHEDULER, ScheduledPollConsumerScheduler.class);
          setScheduler(getCamelContext().getInjector().newInstance(clazz));
        } catch (ClassNotFoundException e) {
          throw new IllegalArgumentException(
              "Cannot load "
                  + QUARTZ_2_SCHEDULER
                  + " from classpath. Make sure camel-quarz2.jar is on the classpath.",
              e);
        }
      } else {
        // must refer to a custom scheduler by the given name
        setScheduler(
            CamelContextHelper.mandatoryLookup(
                getCamelContext(), schedulerName, ScheduledPollConsumerScheduler.class));
      }
    }
  }
Exemplo n.º 7
0
  @Override
  protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
      throws Exception {

    CamelContext camelContext = getCamelContext();
    int idx = remaining.indexOf(":");
    if (idx <= 0) {
      throw new IllegalArgumentException(BAD_FORMAT_MESSAGE);
    }
    String bindingName = remaining.substring(0, idx);
    String delegateURI = remaining.substring(idx + 1);
    if (delegateURI.isEmpty()) {
      throw new IllegalArgumentException(BAD_FORMAT_MESSAGE);
    }
    Binding binding = CamelContextHelper.mandatoryLookup(camelContext, bindingName, Binding.class);
    Endpoint delegate = getMandatoryEndpoint(camelContext, delegateURI);
    return new BindingEndpoint(uri, this, binding, delegate);
  }
 /**
  * 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 (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 (bindingMode != null) {
     answer.setBindingMode(bindingMode.name());
   }
   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);
   }
   return answer;
 }
Exemplo n.º 9
0
  @Override
  public Processor createProcessor(RouteContext routeContext) throws Exception {
    BeanProcessor answer;
    Class<?> clazz = bean != null ? bean.getClass() : null;
    BeanHolder beanHolder;

    if (ObjectHelper.isNotEmpty(ref)) {
      if (cache != null && cache) {
        // cache the registry lookup which avoids repeat lookup in the registry
        beanHolder = new RegistryBean(routeContext.getCamelContext(), ref).createCacheHolder();
      } else {
        beanHolder = new RegistryBean(routeContext.getCamelContext(), ref);
      }
      // bean holder will check if the bean exists
      bean = beanHolder.getBean();
      answer = new BeanProcessor(beanHolder);
    } else {
      if (bean == null) {

        if (beanType == null && beanClass == null) {
          throw new IllegalArgumentException("bean, ref or beanType must be provided");
        }

        // the clazz is either from beanType or beanClass
        if (beanType != null) {
          try {
            clazz =
                routeContext.getCamelContext().getClassResolver().resolveMandatoryClass(beanType);
          } catch (ClassNotFoundException e) {
            throw ObjectHelper.wrapRuntimeCamelException(e);
          }
        } else {
          clazz = beanClass;
        }

        // create a bean if there is a default public no-arg constructor
        if (ObjectHelper.hasDefaultPublicNoArgConstructor(clazz)) {
          bean = CamelContextHelper.newInstance(routeContext.getCamelContext(), clazz);
          ObjectHelper.notNull(bean, "bean", this);
        }
      }

      // validate the bean type is not from java so you by mistake think its a reference
      // to a bean name but the String is being invoke instead
      if (bean instanceof String) {
        throw new IllegalArgumentException(
            "The bean instance is a java.lang.String type: "
                + bean
                + ". We suppose you want to refer to a bean instance by its id instead. Please use beanRef.");
      }

      // the holder should either be bean or type based
      beanHolder =
          bean != null
              ? new ConstantBeanHolder(bean, routeContext.getCamelContext())
              : new ConstantTypeBeanHolder(clazz, routeContext.getCamelContext());
      answer = new BeanProcessor(beanHolder);
    }

    // check for method exists
    if (method != null) {
      answer.setMethod(method);

      // check there is a method with the given name, and leverage BeanInfo for that
      BeanInfo beanInfo = beanHolder.getBeanInfo();
      if (bean != null) {
        // there is a bean instance, so check for any methods
        if (!beanInfo.hasMethod(method)) {
          throw ObjectHelper.wrapRuntimeCamelException(
              new MethodNotFoundException(null, bean, method));
        }
      } else if (clazz != null) {
        // there is no bean instance, so check for static methods only
        if (!beanInfo.hasStaticMethod(method)) {
          throw ObjectHelper.wrapRuntimeCamelException(
              new MethodNotFoundException(null, clazz, method, true));
        }
      }
    }

    return answer;
  }
Exemplo n.º 10
0
  @SuppressWarnings("deprecation")
  public MethodInfo(
      CamelContext camelContext,
      Class<?> type,
      Method method,
      List<ParameterInfo> parameters,
      List<ParameterInfo> bodyParameters,
      boolean hasCustomAnnotation,
      boolean hasHandlerAnnotation) {
    this.camelContext = camelContext;
    this.type = type;
    this.method = method;
    this.parameters = parameters;
    this.bodyParameters = bodyParameters;
    this.hasCustomAnnotation = hasCustomAnnotation;
    this.hasHandlerAnnotation = hasHandlerAnnotation;
    this.parametersExpression = createParametersExpression();

    Map<Class<?>, Annotation> collectedMethodAnnotation = collectMethodAnnotations(type, method);

    Pattern oneway = findOneWayAnnotation(method);
    if (oneway != null) {
      pattern = oneway.value();
    }

    org.apache.camel.RoutingSlip routingSlipAnnotation =
        (org.apache.camel.RoutingSlip)
            collectedMethodAnnotation.get(org.apache.camel.RoutingSlip.class);
    if (routingSlipAnnotation != null && matchContext(routingSlipAnnotation.context())) {
      routingSlip = new RoutingSlip(camelContext);
      routingSlip.setDelimiter(routingSlipAnnotation.delimiter());
      routingSlip.setIgnoreInvalidEndpoints(routingSlipAnnotation.ignoreInvalidEndpoints());
      // add created routingSlip as a service so we have its lifecycle managed
      try {
        camelContext.addService(routingSlip);
      } catch (Exception e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
      }
    }

    org.apache.camel.DynamicRouter dynamicRouterAnnotation =
        (org.apache.camel.DynamicRouter)
            collectedMethodAnnotation.get(org.apache.camel.DynamicRouter.class);
    if (dynamicRouterAnnotation != null && matchContext(dynamicRouterAnnotation.context())) {
      dynamicRouter = new DynamicRouter(camelContext);
      dynamicRouter.setDelimiter(dynamicRouterAnnotation.delimiter());
      dynamicRouter.setIgnoreInvalidEndpoints(dynamicRouterAnnotation.ignoreInvalidEndpoints());
      // add created dynamicRouter as a service so we have its lifecycle managed
      try {
        camelContext.addService(dynamicRouter);
      } catch (Exception e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
      }
    }

    org.apache.camel.RecipientList recipientListAnnotation =
        (org.apache.camel.RecipientList)
            collectedMethodAnnotation.get(org.apache.camel.RecipientList.class);
    if (recipientListAnnotation != null && matchContext(recipientListAnnotation.context())) {
      recipientList = new RecipientList(camelContext, recipientListAnnotation.delimiter());
      recipientList.setStopOnException(recipientListAnnotation.stopOnException());
      recipientList.setIgnoreInvalidEndpoints(recipientListAnnotation.ignoreInvalidEndpoints());
      recipientList.setParallelProcessing(recipientListAnnotation.parallelProcessing());
      recipientList.setParallelAggregate(recipientListAnnotation.parallelAggregate());
      recipientList.setStreaming(recipientListAnnotation.streaming());
      recipientList.setTimeout(recipientListAnnotation.timeout());
      recipientList.setShareUnitOfWork(recipientListAnnotation.shareUnitOfWork());

      if (ObjectHelper.isNotEmpty(recipientListAnnotation.executorServiceRef())) {
        ExecutorService executor =
            camelContext
                .getExecutorServiceManager()
                .newDefaultThreadPool(this, recipientListAnnotation.executorServiceRef());
        recipientList.setExecutorService(executor);
      }

      if (recipientListAnnotation.parallelProcessing()
          && recipientList.getExecutorService() == null) {
        // we are running in parallel so we need a thread pool
        ExecutorService executor =
            camelContext.getExecutorServiceManager().newDefaultThreadPool(this, "@RecipientList");
        recipientList.setExecutorService(executor);
      }

      if (ObjectHelper.isNotEmpty(recipientListAnnotation.strategyRef())) {
        AggregationStrategy strategy =
            CamelContextHelper.mandatoryLookup(
                camelContext, recipientListAnnotation.strategyRef(), AggregationStrategy.class);
        recipientList.setAggregationStrategy(strategy);
      }

      if (ObjectHelper.isNotEmpty(recipientListAnnotation.onPrepareRef())) {
        Processor onPrepare =
            CamelContextHelper.mandatoryLookup(
                camelContext, recipientListAnnotation.onPrepareRef(), Processor.class);
        recipientList.setOnPrepare(onPrepare);
      }

      // add created recipientList as a service so we have its lifecycle managed
      try {
        camelContext.addService(recipientList);
      } catch (Exception e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
      }
    }
  }
Exemplo n.º 11
0
 /**
  * Looks up a mandatory endpoint for a given name.
  *
  * <p>Derived classes could use this name as a logical name and look it up on some registry.
  *
  * <p>The default implementation will do a mandatory look up the name in the {@link
  * org.apache.camel.spi.Registry}.
  *
  * @throws org.apache.camel.NoSuchBeanException if not found in the {@link
  *     org.apache.camel.spi.Registry}
  */
 protected Endpoint lookupEndpoint(String name, Map<String, Object> parameters) {
   return CamelContextHelper.mandatoryLookup(getCamelContext(), name, Endpoint.class);
 }
Exemplo n.º 12
0
 @Override
 public <T> T mandatoryLookup(String name, Class<T> type) {
   return CamelContextHelper.mandatoryLookup(getCamelContext(), name, type);
 }
 /**
  * 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;
 }