protected void doGetBuild(Exchange exchange, String operation) throws Exception {
    Build build = null;
    String buildName =
        exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILD_NAME, String.class);
    String namespaceName =
        exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
    if (ObjectHelper.isEmpty(buildName)) {
      LOG.error("Get a specific Build require specify a Build name");
      throw new IllegalArgumentException("Get a specific Build require specify a Build name");
    }
    if (ObjectHelper.isEmpty(namespaceName)) {
      LOG.error("Get a specific Build require specify a namespace name");
      throw new IllegalArgumentException("Get a specific Build require specify a namespace name");
    }
    build =
        getEndpoint()
            .getKubernetesClient()
            .adapt(OpenShiftClient.class)
            .builds()
            .inNamespace(namespaceName)
            .withName(buildName)
            .get();

    MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
    exchange.getOut().setBody(build);
  }
  private TriggerKey createTriggerKey(String uri, String remaining, QuartzEndpoint endpoint)
      throws Exception {
    // Parse uri for trigger name and group
    URI u = new URI(uri);
    String path = ObjectHelper.after(u.getPath(), "/");
    String host = u.getHost();

    // host can be null if the uri did contain invalid host characters such as an underscore
    if (host == null) {
      host = ObjectHelper.before(remaining, "/");
    }

    // Trigger group can be optional, if so set it to this context's unique name
    String name;
    String group;
    if (ObjectHelper.isNotEmpty(path) && ObjectHelper.isNotEmpty(host)) {
      group = host;
      name = path;
    } else {
      String camelContextName = getCamelContext().getManagementName();
      group = camelContextName == null ? "Camel" : "Camel_" + camelContextName;
      name = host;
    }

    if (prefixJobNameWithEndpointId) {
      name = endpoint.getId() + "_" + name;
    }

    return new TriggerKey(name, group);
  }
Example #3
0
  public static boolean setProperties(
      Object target,
      Map<String, Object> properties,
      String optionPrefix,
      boolean allowBuilderPattern)
      throws Exception {
    ObjectHelper.notNull(target, "target");
    ObjectHelper.notNull(properties, "properties");
    boolean rc = false;

    for (Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator();
        it.hasNext(); ) {
      Map.Entry<String, Object> entry = it.next();
      String name = entry.getKey().toString();
      if (name.startsWith(optionPrefix)) {
        Object value = properties.get(name);
        name = name.substring(optionPrefix.length());
        if (setProperty(target, name, value, allowBuilderPattern)) {
          it.remove();
          rc = true;
        }
      }
    }

    return rc;
  }
Example #4
0
  /**
   * Will inspect the target for properties.
   *
   * <p>Notice a property must have both a getter/setter method to be included.
   *
   * @param target the target bean
   * @param properties the map to fill in found properties
   * @param optionPrefix an optional prefix to append the property key
   * @param includeNull whether to include <tt>null</tt> values
   * @return <tt>true</tt> if any properties was found, <tt>false</tt> otherwise.
   */
  public static boolean getProperties(
      Object target, Map<String, Object> properties, String optionPrefix, boolean includeNull) {
    ObjectHelper.notNull(target, "target");
    ObjectHelper.notNull(properties, "properties");
    boolean rc = false;
    if (optionPrefix == null) {
      optionPrefix = "";
    }

    ClassInfo cache = cacheClass(target.getClass());

    for (MethodInfo info : cache.methods) {
      Method method = info.method;
      // we can only get properties if we have both a getter and a setter
      if (info.isGetter && info.hasGetterAndSetter) {
        String name = info.getterOrSetterShorthandName;
        try {
          // we may want to set options on classes that has package view visibility, so override the
          // accessible
          method.setAccessible(true);
          Object value = method.invoke(target);
          if (value != null || includeNull) {
            properties.put(optionPrefix + name, value);
            rc = true;
          }
        } catch (Exception e) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("Error invoking getter method " + method + ". This exception is ignored.", e);
          }
        }
      }
    }

    return rc;
  }
  protected void createJmxConnector(String host) throws IOException {
    ObjectHelper.notEmpty(serviceUrlPath, "serviceUrlPath");
    ObjectHelper.notNull(registryPort, "registryPort");

    try {
      registry = LocateRegistry.createRegistry(registryPort);
      LOG.debug("Created JMXConnector RMI registry on port {}", registryPort);
    } catch (RemoteException ex) {
      // The registry may had been created, we could get the registry instead
    }

    // must start with leading slash
    String path = serviceUrlPath.startsWith("/") ? serviceUrlPath : "/" + serviceUrlPath;
    // Create an RMI connector and start it
    final JMXServiceURL url;
    if (connectorPort > 0) {
      url =
          new JMXServiceURL(
              "service:jmx:rmi://"
                  + host
                  + ":"
                  + connectorPort
                  + "/jndi/rmi://"
                  + host
                  + ":"
                  + registryPort
                  + path);
    } else {
      url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + registryPort + path);
    }

    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

    // use async thread for starting the JMX Connector
    // (no need to use a thread pool or enlist in JMX as this thread is terminated when the JMX
    // connector has been started)
    String threadName =
        camelContext.getExecutorServiceManager().resolveThreadName("JMXConnector: " + url);
    Thread thread =
        getCamelContext()
            .getExecutorServiceManager()
            .newThread(
                threadName,
                new Runnable() {
                  public void run() {
                    try {
                      LOG.debug("Staring JMX Connector thread to listen at: {}", url);
                      cs.start();
                      LOG.info("JMX Connector thread started and listening at: {}", url);
                    } catch (IOException ioe) {
                      LOG.warn(
                          "Could not start JMXConnector thread at: "
                              + url
                              + ". JMX Connector not in use.",
                          ioe);
                    }
                  }
                });
    thread.start();
  }
Example #6
0
  @Override
  public Processor createProcessor(RouteContext routeContext) throws Exception {
    if (ObjectHelper.isEmpty(resourceUri) && ObjectHelper.isEmpty(resourceRef)) {
      throw new IllegalArgumentException(
          "Either uri or ref must be provided for resource endpoint");
    }

    // lookup endpoint
    Endpoint endpoint;
    if (resourceUri != null) {
      endpoint = routeContext.resolveEndpoint(resourceUri);
    } else {
      endpoint = routeContext.resolveEndpoint(null, resourceRef);
    }

    PollEnricher enricher;
    if (timeout != null) {
      enricher = new PollEnricher(null, endpoint.createPollingConsumer(), timeout);
    } else {
      // if no timeout then we should block, and there use a negative timeout
      enricher = new PollEnricher(null, endpoint.createPollingConsumer(), -1);
    }

    AggregationStrategy strategy = createAggregationStrategy(routeContext);
    if (strategy == null) {
      enricher.setDefaultAggregationStrategy();
    } else {
      enricher.setAggregationStrategy(strategy);
    }
    if (getAggregateOnException() != null) {
      enricher.setAggregateOnException(getAggregateOnException());
    }

    return enricher;
  }
  public RedeliveryErrorHandler(
      CamelContext camelContext,
      Processor output,
      CamelLogger logger,
      Processor redeliveryProcessor,
      RedeliveryPolicy redeliveryPolicy,
      Processor deadLetter,
      String deadLetterUri,
      boolean useOriginalMessagePolicy,
      Predicate retryWhile,
      String executorServiceRef) {

    ObjectHelper.notNull(camelContext, "CamelContext", this);
    ObjectHelper.notNull(redeliveryPolicy, "RedeliveryPolicy", this);

    this.camelContext = camelContext;
    this.redeliveryProcessor = redeliveryProcessor;
    this.deadLetter = deadLetter;
    this.output = output;
    this.outputAsync = AsyncProcessorTypeConverter.convert(output);
    this.redeliveryPolicy = redeliveryPolicy;
    this.logger = logger;
    this.deadLetterUri = deadLetterUri;
    this.useOriginalMessagePolicy = useOriginalMessagePolicy;
    this.retryWhilePolicy = retryWhile;
    this.executorServiceRef = executorServiceRef;
  }
Example #8
0
    /** Evaluate using classic parameter binding using the pre compute expression */
    private Object evaluateParameterBinding(
        Exchange exchange, Expression expression, int index, Class<?> parameterType) {
      Object answer = null;

      // use object first to avoid type conversion so we know if there is a value or not
      Object result = expression.evaluate(exchange, Object.class);
      if (result != null) {
        try {
          if (parameterType.isInstance(result)) {
            // optimize if the value is already the same type
            answer = result;
          } else {
            // we got a value now try to convert it to the expected type
            answer =
                exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterType, result);
          }
          if (LOG.isTraceEnabled()) {
            LOG.trace(
                "Parameter #{} evaluated as: {} type: ",
                new Object[] {index, answer, ObjectHelper.type(answer)});
          }
        } catch (NoTypeConversionAvailableException e) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                "Cannot convert from type: {} to type: {} for parameter #{}",
                new Object[] {ObjectHelper.type(result), parameterType, index});
          }
          throw new ParameterBindingException(e, method, index, parameterType, result);
        }
      } else {
        LOG.trace("Parameter #{} evaluated as null", index);
      }

      return answer;
    }
  /**
   * Creates the associated name of the done file based on the given file name.
   *
   * <p>This method should only be invoked if a done filename property has been set on this
   * endpoint.
   *
   * @param fileName the file name
   * @return name of the associated done file name
   */
  protected String createDoneFileName(String fileName) {
    String pattern = getDoneFileName();
    ObjectHelper.notEmpty(pattern, "doneFileName", pattern);

    // we only support ${file:name} or ${file:name.noext} as dynamic placeholders for done files
    String path = FileUtil.onlyPath(fileName);
    String onlyName = FileUtil.stripPath(fileName);

    pattern = pattern.replaceFirst("\\$\\{file:name\\}", onlyName);
    pattern = pattern.replaceFirst("\\$simple\\{file:name\\}", onlyName);
    pattern = pattern.replaceFirst("\\$\\{file:name.noext\\}", FileUtil.stripExt(onlyName));
    pattern = pattern.replaceFirst("\\$simple\\{file:name.noext\\}", FileUtil.stripExt(onlyName));

    // must be able to resolve all placeholders supported
    if (SimpleLanguage.hasStartToken(pattern)) {
      throw new ExpressionIllegalSyntaxException(
          fileName + ". Cannot resolve reminder: " + pattern);
    }

    String answer = pattern;
    if (ObjectHelper.isNotEmpty(path) && ObjectHelper.isNotEmpty(pattern)) {
      // done file must always be in same directory as the real file name
      answer = path + File.separator + pattern;
    }

    if (getConfiguration().needToNormalize()) {
      // must normalize path to cater for Windows and other OS
      answer = FileUtil.normalizePath(answer);
    }

    return answer;
  }
Example #10
0
  @Override
  protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
      throws Exception {
    URI url = new URI(uri);

    // must use copy as each endpoint can have different options
    MailConfiguration config = getConfiguration().copy();

    // only configure if we have a url with a known protocol
    config.configure(url);
    configureAdditionalJavaMailProperties(config, parameters);

    MailEndpoint endpoint = new MailEndpoint(uri, this, config);
    endpoint.setContentTypeResolver(contentTypeResolver);
    setProperties(endpoint.getConfiguration(), parameters);

    Map<String, Object> sstParams =
        IntrospectionSupport.extractProperties(parameters, "searchTerm.");
    if (!sstParams.isEmpty()) {
      // use SimpleSearchTerm as POJO to store the configuration and then convert that to the actual
      // SearchTerm
      SimpleSearchTerm sst = new SimpleSearchTerm();
      setProperties(sst, sstParams);
      SearchTerm st = MailConverters.toSearchTerm(sst, getCamelContext().getTypeConverter());
      endpoint.setSearchTerm(st);
    }

    // sanity check that we know the mail server
    ObjectHelper.notEmpty(config.getHost(), "host");
    ObjectHelper.notEmpty(config.getProtocol(), "protocol");

    return endpoint;
  }
Example #11
0
  private MethodInfo chooseMethodWithMatchingParameters(
      Exchange exchange, String parameters, Collection<MethodInfo> operationList)
      throws AmbiguousMethodCallException {
    // we have hardcoded parameters so need to match that with the given operations
    Iterator<?> it = ObjectHelper.createIterator(parameters);
    int count = 0;
    while (it.hasNext()) {
      it.next();
      count++;
    }

    List<MethodInfo> operations = new ArrayList<MethodInfo>();
    for (MethodInfo info : operationList) {
      if (info.getParameters().size() == count) {
        operations.add(info);
      }
    }

    if (operations.isEmpty()) {
      return null;
    } else if (operations.size() == 1) {
      return operations.get(0);
    }

    // okay we still got multiple operations, so need to match the best one
    List<MethodInfo> candidates = new ArrayList<MethodInfo>();
    for (MethodInfo info : operations) {
      it = ObjectHelper.createIterator(parameters);
      int index = 0;
      boolean matches = true;
      while (it.hasNext()) {
        String parameter = (String) it.next();
        Class<?> parameterType = BeanHelper.getValidParameterType(parameter);
        Class<?> expectedType = info.getParameters().get(index).getType();

        if (parameterType != null && expectedType != null) {
          if (!parameterType.isAssignableFrom(expectedType)) {
            matches = false;
            break;
          }
        }

        index++;
      }

      if (matches) {
        candidates.add(info);
      }
    }

    if (candidates.size() > 1) {
      MethodInfo answer = getSingleCovariantMethod(candidates);
      if (answer == null) {
        throw new AmbiguousMethodCallException(exchange, candidates);
      }
      return answer;
    }
    return candidates.size() == 1 ? candidates.get(0) : null;
  }
Example #12
0
  /**
   * Add a child that does not contain the required metadata to the this node. You need to specify
   * the plural form of the child (e.g. `Account` its `Accounts`).
   *
   * @param labelPlural plural form
   * @param child to add
   * @return the newly created node, used in builder fashion to add more child objects to it (on the
   *     next level)
   */
  public SObjectNode addChild(final String labelPlural, final AbstractSObjectBase child) {
    ObjectHelper.notNull(labelPlural, "labelPlural");
    ObjectHelper.notNull(child, "child");

    final SObjectNode node = new SObjectNode(referenceGenerator, typeOf(child), child);

    return addChild(labelPlural, node);
  }
Example #13
0
 public static Method getPropertyGetter(Class<?> type, String propertyName)
     throws NoSuchMethodException {
   if (isPropertyIsGetter(type, propertyName)) {
     return type.getMethod("is" + ObjectHelper.capitalize(propertyName));
   } else {
     return type.getMethod("get" + ObjectHelper.capitalize(propertyName));
   }
 }
Example #14
0
  /** Get parameters defined in @CsvRecord annotation */
  private void initCsvRecordParameters() {
    if (separator == null) {
      for (Class<?> cl : models) {

        // Get annotation @CsvRecord from the class
        CsvRecord record = cl.getAnnotation(CsvRecord.class);

        // Get annotation @Section from the class
        Section section = cl.getAnnotation(Section.class);

        if (record != null) {
          LOG.debug("Csv record: {}", record);

          // Get skipFirstLine parameter
          skipFirstLine = record.skipFirstLine();
          LOG.debug("Skip First Line parameter of the CSV: {}" + skipFirstLine);

          // Get generateHeaderColumnNames parameter
          generateHeaderColumnNames = record.generateHeaderColumns();
          LOG.debug(
              "Generate header column names parameter of the CSV: {}", generateHeaderColumnNames);

          // Get Separator parameter
          ObjectHelper.notNull(
              record.separator(), "No separator has been defined in the @Record annotation");
          separator = record.separator();
          LOG.debug("Separator defined for the CSV: {}", separator);

          // Get carriage return parameter
          crlf = record.crlf();
          LOG.debug("Carriage return defined for the CSV: {}", crlf);

          // Get isOrdered parameter
          messageOrdered = record.isOrdered();
          LOG.debug("Must CSV record be ordered: {}", messageOrdered);

          if (ObjectHelper.isNotEmpty(record.quote())) {
            quote = record.quote();
            LOG.debug("Quoting columns with: {}", quote);
          }

          quoting = record.quoting();
          LOG.debug("CSV will be quoted: {}", messageOrdered);

          autospanLine = record.autospanLine();
          LOG.debug("Autospan line in last record: {}", autospanLine);
        }

        if (section != null) {
          // Test if section number is not null
          ObjectHelper.notNull(section.number(), "No number has been defined for the section");

          // Get section number and add it to the sections
          sections.put(cl.getName(), section.number());
        }
      }
    }
  }
  /**
   * Copied from CamelBlueprintHelper since there it is also a private method.
   *
   * <p>Gets the bundle descriptors as {@link URL} resources.
   *
   * @param descriptors the bundle descriptors, can be separated by comma
   * @return the bundle descriptors.
   * @throws FileNotFoundException is thrown if a bundle descriptor cannot be found
   */
  private static Collection<URL> getBlueprintDescriptors(String descriptors)
      throws FileNotFoundException, MalformedURLException {
    List<URL> answer = new ArrayList<URL>();
    String descriptor = descriptors;
    if (descriptor != null) {
      // there may be more resources separated by comma
      Iterator<Object> it = ObjectHelper.createIterator(descriptor);
      while (it.hasNext()) {
        String s = (String) it.next();
        LOG.trace("Resource descriptor: {}", s);

        // remove leading / to be able to load resource from the classpath
        s = FileUtil.stripLeadingSeparator(s);

        // if there is wildcards for *.xml then we need to find the urls from the package
        if (s.endsWith("*.xml")) {
          String packageName = s.substring(0, s.length() - 5);
          // remove trailing / to be able to load resource from the classpath
          Enumeration<URL> urls = ObjectHelper.loadResourcesAsURL(packageName);
          while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            File dir = new File(url.getFile());
            if (dir.isDirectory()) {
              File[] files = dir.listFiles();
              if (files != null) {
                for (File file : files) {
                  if (file.isFile() && file.exists() && file.getName().endsWith(".xml")) {
                    String name = packageName + file.getName();
                    LOG.debug("Resolving resource: {}", name);
                    URL xmlUrl = ObjectHelper.loadResourceAsURL(name);
                    if (xmlUrl != null) {
                      answer.add(xmlUrl);
                    }
                  }
                }
              }
            }
          }
        } else {
          LOG.debug("Resolving resource: {}", s);
          URL url = ResourceHelper.resolveMandatoryResourceAsUrl(RESOLVER, s);
          if (url == null) {
            throw new FileNotFoundException("Resource " + s + " not found");
          }
          answer.add(url);
        }
      }
    } else {
      throw new IllegalArgumentException(
          "No bundle descriptor configured. Override getBlueprintDescriptor() or getBlueprintDescriptors() method");
    }

    if (answer.isEmpty()) {
      throw new IllegalArgumentException(
          "Cannot find any resources in classpath from descriptor " + descriptors);
    }
    return answer;
  }
Example #16
0
  /**
   * Add multiple described children with the metadata needed already present within them to the
   * this node..
   *
   * @param first first child to add
   * @param others any other children to add
   */
  public void addChildren(
      final AbstractDescribedSObjectBase first, final AbstractDescribedSObjectBase... others) {
    ObjectHelper.notNull(first, "first");
    ObjectHelper.notNull(others, "others");

    addChild(pluralOf(first), first);

    Arrays.stream(others).forEach(this::addChild);
  }
  @Override
  protected void doStart() throws Exception {
    super.doStart();

    // validate that if backoff multiplier is in use, the threshold values is set correclty
    if (backoffMultiplier > 0) {
      if (backoffIdleThreshold <= 0 && backoffErrorThreshold <= 0) {
        throw new IllegalArgumentException(
            "backoffIdleThreshold and/or backoffErrorThreshold must be configured to a positive value when using backoffMultiplier");
      }
      LOG.debug(
          "Using backoff[multiplier={}, idleThreshold={}, errorThreshold={}] on {}",
          new Object[] {
            backoffMultiplier, backoffIdleThreshold, backoffErrorThreshold, getEndpoint()
          });
    }

    if (scheduler == null) {
      scheduler = new DefaultScheduledPollConsumerScheduler();
    }
    scheduler.setCamelContext(getEndpoint().getCamelContext());
    scheduler.onInit(this);
    scheduler.scheduleTask(this);

    // configure scheduler with options from this consumer
    Map<String, Object> properties = new HashMap<String, Object>();
    IntrospectionSupport.getProperties(this, properties, null);
    IntrospectionSupport.setProperties(
        getEndpoint().getCamelContext().getTypeConverter(), scheduler, properties);
    if (schedulerProperties != null && !schedulerProperties.isEmpty()) {
      // need to use a copy in case the consumer is restarted so we keep the properties
      Map<String, Object> copy = new HashMap<String, Object>(schedulerProperties);
      IntrospectionSupport.setProperties(
          getEndpoint().getCamelContext().getTypeConverter(), scheduler, copy);
      if (copy.size() > 0) {
        throw new FailedToCreateConsumerException(
            getEndpoint(),
            "There are "
                + copy.size()
                + " scheduler parameters that couldn't be set on the endpoint."
                + " Check the uri if the parameters are spelt correctly and that they are properties of the endpoint."
                + " Unknown parameters=["
                + copy
                + "]");
      }
    }

    ObjectHelper.notNull(scheduler, "scheduler", this);
    ObjectHelper.notNull(pollStrategy, "pollStrategy", this);

    ServiceHelper.startService(scheduler);

    if (isStartScheduler()) {
      startScheduler();
    }
  }
  @Override
  public Source resolve(String href, String base) throws TransformerException {
    // supports the empty href
    if (ObjectHelper.isEmpty(href)) {
      href = location;
    }
    if (ObjectHelper.isEmpty(href)) {
      throw new TransformerException("include href is empty");
    }

    LOG.trace("Resolving URI with href: {} and base: {}", href, base);

    String scheme = ResourceHelper.getScheme(href);
    if (scheme != null) {
      // need to compact paths for file/classpath as it can be relative paths using .. to go
      // backwards
      if ("file:".equals(scheme)) {
        // compact path use file OS separator
        href = FileUtil.compactPath(href);
      } else if ("classpath:".equals(scheme)) {
        // for classpath always use /
        href = FileUtil.compactPath(href, '/');
      }
      LOG.debug("Resolving URI from {}: {}", scheme, href);

      InputStream is;
      try {
        is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, href);
      } catch (IOException e) {
        throw new TransformerException(e);
      }
      return new StreamSource(is);
    }

    // if href and location is the same, then its the initial resolve
    if (href.equals(location)) {
      String path = baseScheme + href;
      return resolve(path, base);
    }

    // okay then its relative to the starting location from the XSLT component
    String path = FileUtil.onlyPath(location);
    if (ObjectHelper.isEmpty(path)) {
      path = baseScheme + href;
      return resolve(path, base);
    } else {
      if (ResourceHelper.hasScheme(path)) {
        path = path + "/" + href;
      } else {
        path = baseScheme + path + "/" + href;
      }
      return resolve(path, base);
    }
  }
Example #19
0
  public static Object getProperty(Object target, String property)
      throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    ObjectHelper.notNull(target, "target");
    ObjectHelper.notNull(property, "property");

    property = property.substring(0, 1).toUpperCase(Locale.ENGLISH) + property.substring(1);

    Class<?> clazz = target.getClass();
    Method method = getPropertyGetter(clazz, property);
    return method.invoke(target);
  }
Example #20
0
  /**
   * Add a child that does not contain the required metadata to the this node. You need to specify
   * the plural form of the child (e.g. `Account` its `Accounts`).
   *
   * @param labelPlural plural form
   * @param first first child to add
   * @param others any other children to add
   */
  public void addChildren(
      final String labelPlural,
      final AbstractSObjectBase first,
      final AbstractSObjectBase... others) {
    ObjectHelper.notNull(labelPlural, "labelPlural");
    ObjectHelper.notNull(first, "first");
    ObjectHelper.notNull(others, "others");

    addChild(labelPlural, first);

    Arrays.stream(others).forEach(c -> addChild(labelPlural, c));
  }
Example #21
0
  public void register() throws Exception {
    ObjectHelper.notEmpty(alias, "alias", this);
    ObjectHelper.notEmpty(servletName, "servletName", this);

    HttpContext actualHttpContext =
        (httpContext == null) ? httpService.createDefaultHttpContext() : httpContext;
    final Dictionary<String, String> initParams = new Hashtable<String, String>();
    initParams.put("matchOnUriPrefix", matchOnUriPrefix ? "true" : "false");
    initParams.put("servlet-name", servletName);
    httpService.registerServlet(alias, servlet, initParams, actualHttpContext);
    alreadyRegistered = true;
  }
    @Override
    public void run() {
      ClientMixedOperation<
              ReplicationController,
              ReplicationControllerList,
              DoneableReplicationController,
              ClientRollableScallableResource<ReplicationController, DoneableReplicationController>>
          w = getEndpoint().getKubernetesClient().replicationControllers();
      if (ObjectHelper.isNotEmpty(getEndpoint().getKubernetesConfiguration().getNamespace())) {
        w.inNamespace(getEndpoint().getKubernetesConfiguration().getNamespace());
      }
      if (ObjectHelper.isNotEmpty(getEndpoint().getKubernetesConfiguration().getLabelKey())
          && ObjectHelper.isNotEmpty(getEndpoint().getKubernetesConfiguration().getLabelValue())) {
        w.withLabel(
            getEndpoint().getKubernetesConfiguration().getLabelKey(),
            getEndpoint().getKubernetesConfiguration().getLabelValue());
      }
      if (ObjectHelper.isNotEmpty(getEndpoint().getKubernetesConfiguration().getResourceName())) {
        w.withName(getEndpoint().getKubernetesConfiguration().getResourceName());
      }
      w.watch(
          new Watcher<ReplicationController>() {

            @Override
            public void eventReceived(
                io.fabric8.kubernetes.client.Watcher.Action action,
                ReplicationController resource) {
              ReplicationControllerEvent rce = new ReplicationControllerEvent(action, resource);
              Exchange exchange = getEndpoint().createExchange();
              exchange.getIn().setBody(rce.getReplicationController());
              exchange
                  .getIn()
                  .setHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION, rce.getAction());
              exchange
                  .getIn()
                  .setHeader(
                      KubernetesConstants.KUBERNETES_EVENT_TIMESTAMP, System.currentTimeMillis());
              try {
                processor.process(exchange);
              } catch (Exception e) {
                getExceptionHandler().handleException("Error during processing", exchange, e);
              }
            }

            @Override
            public void onClose(KubernetesClientException cause) {
              if (cause != null) {
                LOG.error(cause.getMessage(), cause);
              }
            }
          });
    }
Example #23
0
 protected static void addNamespace(Element element, Map<String, String> nsMap) {
   for (String ns : nsMap.keySet()) {
     // We should not override the namespace setting of the element
     if (XMLConstants.XMLNS_ATTRIBUTE.equals(ns)) {
       if (ObjectHelper.isEmpty(element.getAttribute(XMLConstants.XMLNS_ATTRIBUTE))) {
         element.setAttribute(ns, nsMap.get(ns));
       }
     } else {
       if (ObjectHelper.isEmpty(element.getAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + ns))) {
         element.setAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + ns, nsMap.get(ns));
       }
     }
   }
 }
 @Override
 protected void configureDataFormat(DataFormat dataFormat, CamelContext camelContext) {
   Boolean answer = ObjectHelper.toBoolean(getPrettyPrint());
   if (answer != null && !answer) {
     setProperty(camelContext, dataFormat, "prettyPrint", Boolean.FALSE);
   } else { // the default value is true
     setProperty(camelContext, dataFormat, "prettyPrint", Boolean.TRUE);
   }
   answer = ObjectHelper.toBoolean(getIgnoreJAXBElement());
   if (answer != null && !answer) {
     setProperty(camelContext, dataFormat, "ignoreJAXBElement", Boolean.FALSE);
   } else { // the default value is true
     setProperty(camelContext, dataFormat, "ignoreJAXBElement", Boolean.TRUE);
   }
   answer = ObjectHelper.toBoolean(getFilterNonXmlChars());
   if (answer != null && answer) {
     setProperty(camelContext, dataFormat, "filterNonXmlChars", Boolean.TRUE);
   } else { // the default value is false
     setProperty(camelContext, dataFormat, "filterNonXmlChars", Boolean.FALSE);
   }
   answer = ObjectHelper.toBoolean(getFragment());
   if (answer != null && answer) {
     setProperty(camelContext, dataFormat, "fragment", Boolean.TRUE);
   } else { // the default value is false
     setProperty(camelContext, dataFormat, "fragment", Boolean.FALSE);
   }
   if (partClass != null) {
     setProperty(camelContext, dataFormat, "partClass", partClass);
   }
   if (partNamespace != null) {
     setProperty(camelContext, dataFormat, "partNamespace", QName.valueOf(partNamespace));
   }
   if (encoding != null) {
     setProperty(camelContext, dataFormat, "encoding", encoding);
   }
   if (namespacePrefixRef != null) {
     setProperty(camelContext, dataFormat, "namespacePrefixRef", namespacePrefixRef);
   }
   setProperty(camelContext, dataFormat, "contextPath", contextPath);
   if (schema != null) {
     setProperty(camelContext, dataFormat, "schema", schema);
   }
   if (xmlStreamWriterWrapper != null) {
     setProperty(camelContext, dataFormat, "xmlStreamWriterWrapper", xmlStreamWriterWrapper);
   }
   if (schemaLocation != null) {
     setProperty(camelContext, dataFormat, "schemaLocation", schemaLocation);
   }
 }
  @Override
  public void populateCamelHeaders(
      HttpResponse response,
      Map<String, Object> headers,
      Exchange exchange,
      NettyHttpConfiguration configuration)
      throws Exception {
    LOG.trace("populateCamelHeaders: {}", response);

    headers.put(Exchange.HTTP_RESPONSE_CODE, response.getStatus().getCode());
    headers.put(Exchange.HTTP_RESPONSE_TEXT, response.getStatus().getReasonPhrase());

    for (String name : response.headers().names()) {
      // mapping the content-type
      if (name.toLowerCase().equals("content-type")) {
        name = Exchange.CONTENT_TYPE;
      }
      // add the headers one by one, and use the header filter strategy
      List<String> values = response.headers().getAll(name);
      Iterator<?> it = ObjectHelper.createIterator(values);
      while (it.hasNext()) {
        Object extracted = it.next();
        LOG.trace("HTTP-header: {}", extracted);
        if (headerFilterStrategy != null
            && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
          NettyHttpHelper.appendHeader(headers, name, extracted);
        }
      }
    }
  }
Example #26
0
 protected void outputRoutesToFile() throws IOException, JAXBException {
   if (ObjectHelper.isNotEmpty(getRoutesOutputFile())) {
     LOG.info("Generating routes as XML in the file named: " + getRoutesOutputFile());
     ModelFileGenerator generator = createModelFileGenerator();
     generator.marshalRoutesUsingJaxb(getRoutesOutputFile(), getRouteDefinitions());
   }
 }
  public void process(Exchange exchange) throws Exception {
    MongoDbOperation operation = endpoint.getOperation();
    Object header = exchange.getIn().getHeader(MongoDbConstants.OPERATION_HEADER);
    if (header != null) {
      LOG.debug("Overriding default operation with operation specified on header: {}", header);
      try {
        if (header instanceof MongoDbOperation) {
          operation = ObjectHelper.cast(MongoDbOperation.class, header);
        } else {
          // evaluate as a String
          operation =
              MongoDbOperation.valueOf(
                  exchange.getIn().getHeader(MongoDbConstants.OPERATION_HEADER, String.class));
        }
      } catch (Exception e) {
        throw new CamelMongoDbException(
            "Operation specified on header is not supported. Value: " + header, e);
      }
    }

    try {
      invokeOperation(operation, exchange);
    } catch (Exception e) {
      throw MongoDbComponent.wrapInCamelMongoDbException(e);
    }
  }
Example #28
0
  public static Set<Method> findSetterMethods(
      Class<?> clazz, String name, boolean allowBuilderPattern) {
    Set<Method> candidates = new LinkedHashSet<Method>();

    // Build the method name.
    name = "set" + ObjectHelper.capitalize(name);
    while (clazz != Object.class) {
      // Since Object.class.isInstance all the objects,
      // here we just make sure it will be add to the bottom of the set.
      Method objectSetMethod = null;
      Method[] methods = clazz.getMethods();
      for (Method method : methods) {
        if (method.getName().equals(name) && isSetter(method, allowBuilderPattern)) {
          Class<?> params[] = method.getParameterTypes();
          if (params[0].equals(Object.class)) {
            objectSetMethod = method;
          } else {
            candidates.add(method);
          }
        }
      }
      if (objectSetMethod != null) {
        candidates.add(objectSetMethod);
      }
      clazz = clazz.getSuperclass();
    }
    return candidates;
  }
  @Test
  public void testMetadataUpdaterBinary() throws Exception {
    context
        .getRouteDefinition("FcrepoSerializationBinaryUpdater")
        .adviceWith(
            context,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                replaceFromWith("direct:start");
                mockEndpointsAndSkip("*");
              }
            });
    context.start();

    getMockEndpoint("mock:direct:binary_file").expectedMessageCount(1);
    getMockEndpoint("mock:direct:binary_file").expectedHeaderReceived(Exchange.FILE_NAME, "foo");

    // send a file!
    final String body = IOUtils.toString(ObjectHelper.loadResourceAsStream("binary.rdf"), "UTF-8");
    final Map<String, Object> headers = ImmutableMap.of(BASE_URL, baseURL, IDENTIFIER, "foo");

    template.sendBodyAndHeaders(body, headers);

    assertMockEndpointsSatisfied();
  }
Example #30
0
  public static boolean hasProperties(Map<String, Object> properties, String optionPrefix) {
    ObjectHelper.notNull(properties, "properties");

    if (ObjectHelper.isNotEmpty(optionPrefix)) {
      for (Object o : properties.keySet()) {
        String name = (String) o;
        if (name.startsWith(optionPrefix)) {
          return true;
        }
      }
      // no parameters with this prefix
      return false;
    } else {
      return !properties.isEmpty();
    }
  }