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);
  }
Esempio n. 2
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;
  }
  @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);
    }
  }
Esempio n. 4
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
  public void process(Exchange exchange) throws Exception {
    String operation;

    if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getOperation())) {
      operation =
          exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_OPERATION, String.class);
    } else {
      operation = getEndpoint().getKubernetesConfiguration().getOperation();
    }

    switch (operation) {
      case KubernetesOperations.LIST_BUILD:
        doList(exchange, operation);
        break;

      case KubernetesOperations.LIST_BUILD_BY_LABELS_OPERATION:
        doListBuildByLabels(exchange, operation);
        break;

      case KubernetesOperations.GET_BUILD_OPERATION:
        doGetBuild(exchange, operation);
        break;

      default:
        throw new IllegalArgumentException("Unsupported operation " + operation);
    }
  }
Esempio n. 6
0
  @Override
  protected void doStart() throws Exception {

    if (isEndpointTransacted()) {
      throw new IllegalArgumentException(
          "InOut exchange pattern is incompatible with transacted=true as it cuases a deadlock. Please use transacted=false or InOnly exchange pattern.");
    }

    if (getConnectionResource() == null) {
      throw new IllegalArgumentException(
          String.format("ConnectionResource or ConnectionFactory must be configured for %s", this));
    }

    if (ObjectHelper.isEmpty(getNamedReplyTo())) {
      log.debug("No reply to destination is defined.  Using temporary destinations.");
    } else {
      log.debug("Using {} as the reply to destination.", getNamedReplyTo());
    }
    if (uuidGenerator == null) {
      // use the generator configured on the camel context
      uuidGenerator = getEndpoint().getCamelContext().getUuidGenerator();
    }
    if (consumers == null) {
      consumers =
          new GenericObjectPool<MessageConsumerResources>(new MessageConsumerResourcesFactory());
      consumers.setMaxActive(getConsumerCount());
      consumers.setMaxIdle(getConsumerCount());
      while (consumers.getNumIdle() < consumers.getMaxIdle()) {
        consumers.addObject();
      }
    }
    super.doStart();
  }
Esempio n. 7
0
  public DTRulesEndpoint(String uri, DTRulesComponent component, DTrulesConfiguration config) {
    super(uri, component);
    this.config = config;

    // the rule directory has to be set
    if (ObjectHelper.isEmpty(this.config.getDirectory())) {
      throw new IllegalArgumentException("Rule directory is missing.");
    }
  }
Esempio n. 8
0
  public void changeCurrentDirectory(String path) throws GenericFileOperationFailedException {
    LOG.trace("changeCurrentDirectory({})", path);
    if (ObjectHelper.isEmpty(path)) {
      return;
    }

    // must compact path so SFTP server can traverse correctly, make use of the '/'
    // separator because JSch expects this as the file separator even on Windows
    String before = path;
    char separatorChar = '/';
    path = FileUtil.compactPath(path, separatorChar);
    if (LOG.isTraceEnabled()) {
      LOG.trace(
          "Compacted path: {} -> {} using separator: {}",
          new Object[] {before, path, separatorChar});
    }

    // not stepwise should change directory in one operation
    if (!endpoint.getConfiguration().isStepwise()) {
      doChangeDirectory(path);
      return;
    }
    if (getCurrentDirectory().startsWith(path)) {
      // extract the path segment relative to the target path and make sure it keeps the preceding
      // '/' for the regex op
      String p = getCurrentDirectory().substring(path.length() - (path.endsWith("/") ? 1 : 0));
      if (p.length() == 0) {
        return;
      }
      // the first character must be '/' and hence removed
      path = UP_DIR_PATTERN.matcher(p).replaceAll("/..").substring(1);
    }

    // if it starts with the root path then a little special handling for that
    if (FileUtil.hasLeadingSeparator(path)) {
      // change to root path
      doChangeDirectory(path.substring(0, 1));
      path = path.substring(1);
    }

    // split into multiple dirs
    final String[] dirs = path.split("/|\\\\");

    if (dirs == null || dirs.length == 0) {
      // path was just a relative single path
      doChangeDirectory(path);
      return;
    }

    // there are multiple dirs so do this in chunks
    for (String dir : dirs) {
      doChangeDirectory(dir);
    }
  }
Esempio n. 9
0
 private void doChangeDirectory(String path) {
   if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
     return;
   }
   LOG.trace("Changing directory: {}", path);
   try {
     channel.cd(path);
   } catch (SftpException e) {
     throw new GenericFileOperationFailedException("Cannot change directory to: " + path, e);
   }
 }
Esempio n. 10
0
  /** Moves any existing file due fileExists=Move is in use. */
  private void doMoveExistingFile(String name, String targetName)
      throws GenericFileOperationFailedException {
    // need to evaluate using a dummy and simulate the file first, to have access to all the file
    // attributes
    // create a dummy exchange as Exchange is needed for expression evaluation
    // we support only the following 3 tokens.
    Exchange dummy = endpoint.createExchange();
    // we only support relative paths for the ftp component, so dont provide any parent
    String parent = null;
    String onlyName = FileUtil.stripPath(targetName);
    dummy.getIn().setHeader(Exchange.FILE_NAME, targetName);
    dummy.getIn().setHeader(Exchange.FILE_NAME_ONLY, onlyName);
    dummy.getIn().setHeader(Exchange.FILE_PARENT, parent);

    String to = endpoint.getMoveExisting().evaluate(dummy, String.class);
    // we only support relative paths for the ftp component, so strip any leading paths
    to = FileUtil.stripLeadingSeparator(to);
    // normalize accordingly to configuration
    to = endpoint.getConfiguration().normalizePath(to);
    if (ObjectHelper.isEmpty(to)) {
      throw new GenericFileOperationFailedException(
          "moveExisting evaluated as empty String, cannot move existing file: " + name);
    }

    // do we have a sub directory
    String dir = FileUtil.onlyPath(to);
    if (dir != null) {
      // ensure directory exists
      buildDirectory(dir, false);
    }

    // deal if there already exists a file
    if (existsFile(to)) {
      if (endpoint.isEagerDeleteTargetFile()) {
        LOG.trace("Deleting existing file: {}", to);
        deleteFile(to);
      } else {
        throw new GenericFileOperationFailedException(
            "Cannot moved existing file from: "
                + name
                + " to: "
                + to
                + " as there already exists a file: "
                + to);
      }
    }

    LOG.trace("Moving existing file: {} to: {}", name, to);
    if (!renameFile(targetName, to)) {
      throw new GenericFileOperationFailedException(
          "Cannot rename file from: " + name + " to: " + to);
    }
  }
Esempio n. 11
0
    @Override
    public MessageConsumerResources makeObject() throws Exception {
      MessageConsumerResources answer;
      Connection conn = getConnectionResource().borrowConnection();
      try {
        Session session;
        if (isEndpointTransacted()) {
          session = conn.createSession(true, Session.SESSION_TRANSACTED);
        } else {
          session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        }

        Destination replyToDestination;
        if (ObjectHelper.isEmpty(getNamedReplyTo())) {
          replyToDestination =
              getEndpoint()
                  .getDestinationCreationStrategy()
                  .createTemporaryDestination(session, isTopic());
        } else {
          replyToDestination =
              getEndpoint()
                  .getDestinationCreationStrategy()
                  .createDestination(session, getNamedReplyTo(), isTopic());
        }
        MessageConsumer messageConsumer =
            JmsObjectFactory.createMessageConsumer(
                session, replyToDestination, null, isTopic(), null, true);
        messageConsumer.setMessageListener(
            new MessageListener() {

              @Override
              public void onMessage(final Message message) {
                log.debug("Message Received in the Consumer Pool");
                log.debug("  Message : {}", message);
                try {
                  Exchanger<Object> exchanger = EXCHANGERS.get(message.getJMSCorrelationID());
                  exchanger.exchange(message, getResponseTimeOut(), TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                  log.error("Unable to exchange message: {}", message, e);
                }
              }
            });
        answer = new MessageConsumerResources(session, messageConsumer, replyToDestination);
      } catch (Exception e) {
        log.error("Unable to create the MessageConsumerResource: " + e.getLocalizedMessage());
        throw new CamelException(e);
      } finally {
        getConnectionResource().returnConnection(conn);
      }
      return answer;
    }
Esempio n. 12
0
  @Override
  protected void doStart() throws Exception {
    super.doStart();

    if (getPort() != 4567) {
      CamelSpark.port(getPort());
    } else {
      // if no explicit port configured, then use port from rest configuration
      RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true);
      int port = config.getPort();
      if (port > 0) {
        CamelSpark.port(port);
      }
    }

    String host = getIpAddress();
    if (host != null) {
      CamelSpark.ipAddress(host);
    } else {
      // if no explicit port configured, then use port from rest configuration
      RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true);
      host = config.getHost();
      if (ObjectHelper.isEmpty(host)) {
        if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
          host = "0.0.0.0";
        } else if (config.getRestHostNameResolver()
            == RestConfiguration.RestHostNameResolver.localHostName) {
          host = HostUtils.getLocalHostName();
        } else if (config.getRestHostNameResolver()
            == RestConfiguration.RestHostNameResolver.localIp) {
          host = HostUtils.getLocalIp();
        }
      }
      CamelSpark.ipAddress(host);
    }

    if (keystoreFile != null || truststoreFile != null) {
      CamelSpark.security(keystoreFile, keystorePassword, truststoreFile, truststorePassword);
    }

    // configure component options
    RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true);
    // configure additional options on spark configuration
    if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
      setProperties(sparkConfiguration, config.getComponentProperties());
    }
  }
Esempio n. 13
0
  /**
   * Gets the destination name which was configured from the endpoint uri.
   *
   * @return the destination name resolved from the endpoint uri
   */
  public String getEndpointConfiguredDestinationName() {
    String remainder = ObjectHelper.after(getEndpointKey(), "//");

    if (remainder != null && remainder.contains("@")) {
      remainder = remainder.substring(remainder.indexOf('@'));
    }

    if (remainder != null && remainder.contains("?")) {
      // remove parameters
      remainder = ObjectHelper.before(remainder, "?");
    }

    if (ObjectHelper.isEmpty(remainder)) {
      return remainder;
    }

    return remainder;
  }
Esempio n. 14
0
  @Override
  public void process(Exchange exchange) throws Exception {
    String q = query;
    String location = exchange.getIn().getHeader(WeatherConstants.WEATHER_LOCATION, String.class);
    if (location != null) {
      q = getEndpoint().getConfiguration().getQuery(location);
    }

    HttpClient httpClient = ((WeatherComponent) getEndpoint().getComponent()).getHttpClient();
    GetMethod method = new GetMethod(q);
    try {
      log.debug("Going to execute the Weather query {}", q);
      int statusCode = httpClient.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        throw new IllegalStateException(
            "Got the invalid http status value '"
                + method.getStatusLine()
                + "' as the result of the query '"
                + query
                + "'");
      }
      String weather =
          getEndpoint()
              .getCamelContext()
              .getTypeConverter()
              .mandatoryConvertTo(String.class, method.getResponseBodyAsStream());
      log.debug("Got back the Weather information {}", weather);

      if (ObjectHelper.isEmpty(weather)) {
        throw new IllegalStateException(
            "Got the unexpected value '" + weather + "' as the result of the query '" + q + "'");
      }

      String header = getEndpoint().getConfiguration().getHeaderName();
      if (header != null) {
        exchange.getIn().setHeader(header, weather);
      } else {
        exchange.getIn().setBody(weather);
      }
      exchange.getIn().setHeader(WeatherConstants.WEATHER_QUERY, q);
    } finally {
      method.releaseConnection();
    }
  }
Esempio n. 15
0
  /**
   * Extracts the parameter value.
   *
   * <p>This implementation supports HTTP multi value parameters which is based on the syntax of
   * <tt>[value1, value2, value3]</tt> by returning a {@link List} containing the values.
   *
   * <p>If the value is not a HTTP mulit value the value is returned as is.
   *
   * @param value the parameter value
   * @return the extracted parameter value, see more details in javadoc.
   */
  public static Object extractHttpParameterValue(String value) {
    if (value == null || ObjectHelper.isEmpty(value)) {
      return value;
    }

    // trim value before checking for multiple parameters
    String trimmed = value.trim();

    if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
      // remove the [ ] markers
      trimmed = trimmed.substring(1, trimmed.length() - 1);
      List<String> list = new ArrayList<String>();
      String[] values = trimmed.split(",");
      for (String s : values) {
        list.add(s.trim());
      }
      return list;
    }

    return value;
  }
Esempio n. 16
0
  private void validateOptions(char role) throws IllegalArgumentException {
    // make our best effort to validate, options with defaults are checked against their defaults,
    // which is not always a guarantee that
    // they haven't been explicitly set, but it is enough
    if (role == 'P') {
      if (!ObjectHelper.isEmpty(consumerType)
          || persistentTailTracking
          || !ObjectHelper.isEmpty(tailTrackDb)
          || !ObjectHelper.isEmpty(tailTrackCollection)
          || !ObjectHelper.isEmpty(tailTrackField)
          || cursorRegenerationDelay != 1000L) {
        throw new IllegalArgumentException(
            "consumerType, tailTracking, cursorRegenerationDelay options cannot appear on a producer endpoint");
      }
    } else if (role == 'C') {
      if (!ObjectHelper.isEmpty(operation)
          || !ObjectHelper.isEmpty(writeConcern)
          || writeConcernRef != null
          || readPreference != null
          || dynamicity
          || invokeGetLastError) {
        throw new IllegalArgumentException(
            "operation, writeConcern, writeConcernRef, readPreference, dynamicity, invokeGetLastError "
                + "options cannot appear on a consumer endpoint");
      }

      if (consumerType == MongoDbConsumerType.tailable) {
        if (tailTrackIncreasingField == null) {
          throw new IllegalArgumentException(
              "tailTrackIncreasingField option must be set for tailable cursor MongoDB consumer endpoint");
        }
        if (persistentTailTracking && (ObjectHelper.isEmpty(persistentId))) {
          throw new IllegalArgumentException(
              "persistentId is compulsory for persistent tail tracking");
        }
      }

    } else {
      throw new IllegalArgumentException("Unknown endpoint role");
    }
  }
Esempio n. 17
0
 protected void doListBuildByLabels(Exchange exchange, String operation) throws Exception {
   BuildList buildList = null;
   Map<String, String> labels =
       exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILDS_LABELS, Map.class);
   String namespaceName =
       exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
   if (!ObjectHelper.isEmpty(namespaceName)) {
     ClientNonNamespaceOperation<
             Build,
             BuildList,
             DoneableBuild,
             ClientBuildResource<Build, DoneableBuild, String, LogWatch>>
         builds =
             getEndpoint()
                 .getKubernetesClient()
                 .adapt(OpenShiftClient.class)
                 .builds()
                 .inNamespace(namespaceName);
     for (Map.Entry<String, String> entry : labels.entrySet()) {
       builds.withLabel(entry.getKey(), entry.getValue());
     }
     buildList = builds.list();
   } else {
     ClientMixedOperation<
             Build,
             BuildList,
             DoneableBuild,
             ClientBuildResource<Build, DoneableBuild, String, LogWatch>>
         builds = getEndpoint().getKubernetesClient().adapt(OpenShiftClient.class).builds();
     for (Map.Entry<String, String> entry : labels.entrySet()) {
       builds.withLabel(entry.getKey(), entry.getValue());
     }
     buildList = builds.list();
   }
   MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
   exchange.getOut().setBody(buildList.getItems());
 }
Esempio n. 18
0
 public Parser createDelimitedParser(Exchange exchange)
     throws InvalidPayloadException, IOException {
   Reader bodyReader = exchange.getIn().getMandatoryBody(Reader.class);
   if (ObjectHelper.isEmpty(getResourceUri())) {
     return getParserFactory().newDelimitedParser(bodyReader, delimiter, textQualifier);
   } else {
     InputStream is =
         ResourceHelper.resolveMandatoryResourceAsInputStream(
             getCamelContext().getClassResolver(), resourceUri);
     InputStreamReader reader = new InputStreamReader(is, IOHelper.getCharsetName(exchange));
     Parser parser =
         getParserFactory()
             .newDelimitedParser(reader, bodyReader, delimiter, textQualifier, ignoreFirstRecord);
     if (isAllowShortLines()) {
       parser.setHandlingShortLines(true);
       parser.setIgnoreParseWarnings(true);
     }
     if (isIgnoreExtraColumns()) {
       parser.setIgnoreExtraColumns(true);
       parser.setIgnoreParseWarnings(true);
     }
     return parser;
   }
 }
Esempio n. 19
0
  public List<ChannelSftp.LsEntry> listFiles(String path)
      throws GenericFileOperationFailedException {
    LOG.trace("listFiles({})", path);
    if (ObjectHelper.isEmpty(path)) {
      // list current directory if file path is not given
      path = ".";
    }

    try {
      final List<ChannelSftp.LsEntry> list = new ArrayList<ChannelSftp.LsEntry>();

      @SuppressWarnings("rawtypes")
      Vector files = channel.ls(path);
      // can return either null or an empty list depending on FTP servers
      if (files != null) {
        for (Object file : files) {
          list.add((ChannelSftp.LsEntry) file);
        }
      }
      return list;
    } catch (SftpException e) {
      throw new GenericFileOperationFailedException("Cannot list directory: " + path, e);
    }
  }
Esempio n. 20
0
  public void updateRouteFromXml(String xml) throws Exception {
    // convert to model from xml
    RouteDefinition def = ModelHelper.createModelFromXml(xml, RouteDefinition.class);
    if (def == null) {
      return;
    }

    // if the xml does not contain the route-id then we fix this by adding the actual route id
    // this may be needed if the route-id was auto-generated, as the intend is to update this route
    // and not add a new route, adding a new route, use the MBean operation on ManagedCamelContext
    // instead.
    if (ObjectHelper.isEmpty(def.getId())) {
      def.setId(getRouteId());
    } else if (!def.getId().equals(getRouteId())) {
      throw new IllegalArgumentException(
          "Cannot update route from XML as routeIds does not match. routeId: "
              + getRouteId()
              + ", routeId from XML: "
              + def.getId());
    }

    // add will remove existing route first
    context.addRouteDefinition(def);
  }
  @Override
  public Producer createProducer() throws Exception {
    RestApiProcessorFactory factory = null;

    RestConfiguration config = getCamelContext().getRestConfiguration(componentName, true);

    // lookup in registry
    Set<RestApiProcessorFactory> factories =
        getCamelContext().getRegistry().findByType(RestApiProcessorFactory.class);
    if (factories != null && factories.size() == 1) {
      factory = factories.iterator().next();
    }

    // lookup on classpath using factory finder to automatic find it (just add camel-swagger-java to
    // classpath etc)
    if (factory == null) {
      String name = apiComponentName != null ? apiComponentName : config.getApiComponent();
      if (name == null) {
        name = DEFAULT_API_COMPONENT_NAME;
      }
      try {
        FactoryFinder finder = getCamelContext().getFactoryFinder(RESOURCE_PATH);
        Object instance = finder.newInstance(name);
        if (instance instanceof RestApiProcessorFactory) {
          factory = (RestApiProcessorFactory) instance;
        }
      } catch (NoFactoryAvailableException e) {
        // ignore
      }
    }

    if (factory != null) {

      // if no explicit port/host configured, then use port from rest configuration
      String host = "";
      int port = 80;

      if (config.getHost() != null) {
        host = config.getHost();
      }
      int num = config.getPort();
      if (num > 0) {
        port = num;
      }

      // if no explicit hostname set then resolve the hostname
      if (ObjectHelper.isEmpty(host)) {
        if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
          host = "0.0.0.0";
        } else if (config.getRestHostNameResolver()
            == RestConfiguration.RestHostNameResolver.localHostName) {
          host = HostUtils.getLocalHostName();
        } else if (config.getRestHostNameResolver()
            == RestConfiguration.RestHostNameResolver.localIp) {
          host = HostUtils.getLocalIp();
        }

        // no host was configured so calculate a host to use
        // there should be no schema in the host (but only port)
        String targetHost = host + (port != 80 ? ":" + port : "");
        getParameters().put("host", targetHost);
      }

      // the base path should start with a leading slash
      String path = getPath();
      if (path != null && !path.startsWith("/")) {
        path = "/" + path;
      }

      // whether listing of the context id's is enabled or not
      boolean contextIdListing = config.isApiContextListing();

      Processor processor =
          factory.createApiProcessor(
              getCamelContext(),
              path,
              getContextIdPattern(),
              contextIdListing,
              config,
              getParameters());
      return new RestApiProducer(this, processor);
    } else {
      throw new IllegalStateException(
          "Cannot find RestApiProcessorFactory in Registry or classpath (such as the camel-swagger-java component)");
    }
  }
Esempio n. 22
0
  /**
   * Processes any custom {@link org.apache.camel.component.http.UrlRewrite}.
   *
   * @param exchange the exchange
   * @param url the url
   * @param endpoint the http endpoint
   * @param producer the producer
   * @return the rewritten url, or <tt>null</tt> to use original url
   * @throws Exception is thrown if any error during rewriting url
   */
  public static String urlRewrite(
      Exchange exchange, String url, HttpEndpoint endpoint, Producer producer) throws Exception {
    String answer = null;

    String relativeUrl;
    if (endpoint.getUrlRewrite() != null) {
      // we should use the relative path if possible
      String baseUrl;
      relativeUrl = endpoint.getHttpUri().toASCIIString();
      if (url.startsWith(relativeUrl)) {
        baseUrl = url.substring(0, relativeUrl.length());
        relativeUrl = url.substring(relativeUrl.length());
      } else {
        baseUrl = null;
        relativeUrl = url;
      }
      // mark it as null if its empty
      if (ObjectHelper.isEmpty(relativeUrl)) {
        relativeUrl = null;
      }

      String newUrl;
      if (endpoint.getUrlRewrite() instanceof HttpServletUrlRewrite) {
        // its servlet based, so we need the servlet request
        HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);
        if (request == null) {
          HttpMessage msg = exchange.getIn(HttpMessage.class);
          if (msg != null) {
            request = msg.getRequest();
          }
        }
        if (request == null) {
          throw new IllegalArgumentException(
              "UrlRewrite "
                  + endpoint.getUrlRewrite()
                  + " requires the message body to be a"
                  + "HttpServletRequest instance, but was: "
                  + ObjectHelper.className(exchange.getIn().getBody()));
        }
        // we need to adapt the context-path to be the path from the endpoint, if it came from a
        // http based endpoint
        // as eg camel-jetty have hardcoded context-path as / for all its servlets/endpoints
        // we have the actual context-path stored as a header with the key CamelServletContextPath
        String contextPath = exchange.getIn().getHeader("CamelServletContextPath", String.class);
        request = new UrlRewriteHttpServletRequestAdapter(request, contextPath);
        newUrl =
            ((HttpServletUrlRewrite) endpoint.getUrlRewrite())
                .rewrite(url, relativeUrl, producer, request);
      } else {
        newUrl = endpoint.getUrlRewrite().rewrite(url, relativeUrl, producer);
      }

      if (ObjectHelper.isNotEmpty(newUrl) && newUrl != url) {
        // we got a new url back, that can either be a new absolute url
        // or a new relative url
        if (newUrl.startsWith("http:") || newUrl.startsWith("https:")) {
          answer = newUrl;
        } else if (baseUrl != null) {
          // avoid double // when adding the urls
          if (baseUrl.endsWith("/") && newUrl.startsWith("/")) {
            answer = baseUrl + newUrl.substring(1);
          } else {
            answer = baseUrl + newUrl;
          }
        } else {
          // use the new url as is
          answer = newUrl;
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Using url rewrite to rewrite from url {} to {} -> {}",
              new Object[] {relativeUrl != null ? relativeUrl : url, newUrl, answer});
        }
      }
    }

    return answer;
  }
  @Override
  public List<String> completeEndpointPath(
      ComponentConfiguration configuration, String completionText) {
    final List<String> result = new ArrayList<String>();

    final Set<String> apiNames = collection.getApiNames();
    boolean useDefaultName = apiNames.size() == 1 && apiNames.contains("");

    // check if there is an API name present
    completionText = ObjectHelper.isEmpty(completionText) ? "" : completionText;
    final int prefixEnd = completionText.indexOf('/');
    final int pathEnd = completionText.lastIndexOf('?');

    // empty or incomplete API prefix, and no options, add API names or method names if
    // useDefaultName
    final Map<E, ? extends ApiMethodHelper<? extends ApiMethod>> apiHelpers =
        collection.getApiHelpers();
    if (prefixEnd == -1 && pathEnd == -1) {

      if (useDefaultName) {

        // complete method names for default API
        final Set<Class<? extends ApiMethod>> apiMethods = collection.getApiMethods().keySet();
        final Class<? extends ApiMethod> apiMethod = apiMethods.iterator().next();
        final ApiMethodHelper<? extends ApiMethod> helper = apiHelpers.values().iterator().next();
        getCompletedMethods(result, completionText, apiMethod, helper);
      } else {

        // complete API names
        for (String name : apiNames) {
          if (!name.isEmpty() || name.startsWith(completionText)) {
            result.add(name);
          }
        }
      }

      // path with complete API name prefix, but no options
    } else if (prefixEnd != -1 && pathEnd == -1) {

      // complete method names for specified API
      final E apiName = getApiNameOrNull(completionText.substring(0, prefixEnd));
      if (apiName != null) {
        final ApiMethodHelper<? extends ApiMethod> helper = apiHelpers.get(apiName);
        completionText = completionText.substring(prefixEnd + 1);
        for (Map.Entry<Class<? extends ApiMethod>, E> entry :
            collection.getApiMethods().entrySet()) {
          if (entry.getValue().equals(apiName)) {
            getCompletedMethods(result, completionText, entry.getKey(), helper);
            break;
          }
        }
      }

      // complete options
    } else {

      // get last option text
      final int lastParam = completionText.lastIndexOf('&');
      String optionText;
      if (lastParam != -1) {
        optionText = completionText.substring(lastParam + 1);
      } else {
        optionText = completionText.substring(pathEnd);
      }

      String methodName = null;
      ApiMethodHelper<? extends ApiMethod> helper = null;
      if (useDefaultName) {

        // get default endpoint configuration and helper
        methodName = completionText.substring(0, pathEnd);
        helper = apiHelpers.values().iterator().next();
      } else {

        // get API name and method name, if they exist
        final String[] pathElements = completionText.substring(0, pathEnd).split("/");
        if (pathElements.length == 2) {
          final E apiName = getApiNameOrNull(pathElements[0]);
          methodName = pathElements[1];
          helper = collection.getHelper(apiName);
        }
      }
      if (helper != null && !ObjectHelper.isEmpty(methodName)) {
        // get other options from configuration
        Set<String> existingOptions = configuration.getParameters().keySet();
        // get all method options
        try {
          final List<Object> arguments = helper.getArguments(methodName);
          final int nArgs = arguments.size();
          final Set<String> options = new HashSet<String>();
          for (int i = 1; i < nArgs; i += 2) {
            options.add((String) arguments.get(i));
          }
          options.removeAll(existingOptions);

          // return matching options
          for (String option : options) {
            if (option.startsWith(optionText)) {
              result.add(option);
            }
          }
        } catch (IllegalArgumentException ignore) {
          // thrown from getArguments() when no matching methods,
          // return an empty result
        }
      }
    }

    return result;
  }
Esempio n. 24
0
  /**
   * @param cxfMessage
   * @param camelMessage
   * @param exchange provides context for filtering
   */
  protected void propagateHeadersFromCxfToCamel(
      Message cxfMessage, org.apache.camel.Message camelMessage, Exchange exchange) {
    Map<String, List<String>> cxfHeaders =
        CastUtils.cast((Map<?, ?>) cxfMessage.get(Message.PROTOCOL_HEADERS));
    Map<String, Object> camelHeaders = camelMessage.getHeaders();
    camelHeaders.put(CxfConstants.CAMEL_CXF_MESSAGE, cxfMessage);

    // Copy the http header to CAMEL as we do in camel-cxfrs
    CxfUtils.copyHttpHeadersFromCxfToCamel(cxfMessage, camelMessage);

    if (cxfHeaders != null) {
      for (Map.Entry<String, List<String>> entry : cxfHeaders.entrySet()) {
        if (!headerFilterStrategy.applyFilterToExternalHeaders(
            entry.getKey(), entry.getValue(), exchange)) {
          // We need to filter the content type with multi-part,
          // as the multi-part stream is already consumed by AttachmentInInterceptor,
          // it will cause some trouble when route this message to another CXF endpoint.

          if ("Content-Type".compareToIgnoreCase(entry.getKey()) == 0
              && entry.getValue().get(0) != null
              && entry.getValue().get(0).startsWith("multipart/related")) {
            // We need to keep the Content-Type if the data format is RAW message
            DataFormat dataFormat =
                exchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);
            if (dataFormat.equals(DataFormat.RAW)) {
              camelHeaders.put(entry.getKey(), getContentTypeString(entry.getValue()));
            } else {
              String contentType = replaceMultiPartContentType(entry.getValue().get(0));
              LOG.trace("Find the multi-part Conent-Type, and replace it with {}", contentType);
              camelHeaders.put(entry.getKey(), contentType);
            }
          } else {
            LOG.trace(
                "Populate header from CXF header={} value={}", entry.getKey(), entry.getValue());
            List<String> values = entry.getValue();
            Object evalue;
            if (values.size() > 1) {
              if (exchange.getProperty(
                  CxfConstants.CAMEL_CXF_PROTOCOL_HEADERS_MERGED, Boolean.FALSE, Boolean.class)) {
                StringBuilder sb = new StringBuilder();
                for (Iterator<String> it = values.iterator(); it.hasNext(); ) {
                  sb.append(it.next());
                  if (it.hasNext()) {
                    sb.append(',').append(' ');
                  }
                }
                evalue = sb.toString();
              } else {
                evalue = values;
              }
            } else {
              evalue = values.get(0);
            }
            camelHeaders.put(entry.getKey(), evalue);
          }
        }
      }
    }

    // propagate SOAP/protocol header list
    String key = Header.HEADER_LIST;
    Object value = cxfMessage.get(key);
    if (value != null) {
      if (!headerFilterStrategy.applyFilterToExternalHeaders(key, value, exchange)) {
        camelHeaders.put(key, value);
        LOG.trace("Populate header from CXF header={} value={}", key, value);
      } else {
        ((List<?>) value).clear();
      }
    }

    // propagate the SOAPAction header
    String soapAction = (String) camelHeaders.get(SoapBindingConstants.SOAP_ACTION);
    // Remove SOAPAction from the protocol header, as it will not be overrided
    if (ObjectHelper.isEmpty(soapAction) || "\"\"".equals(soapAction)) {
      camelHeaders.remove(SoapBindingConstants.SOAP_ACTION);
    }
    soapAction = (String) cxfMessage.get(SoapBindingConstants.SOAP_ACTION);
    if (soapAction != null) {
      if (!headerFilterStrategy.applyFilterToExternalHeaders(
          SoapBindingConstants.SOAP_ACTION, soapAction, exchange)) {
        camelHeaders.put(SoapBindingConstants.SOAP_ACTION, soapAction);
        LOG.trace(
            "Populate header from CXF header={} value={}",
            SoapBindingConstants.SOAP_ACTION,
            soapAction);
      }
    }
  }
  private Metadata parseCamelContextNode(Element element, ParserContext context) {
    // Find the id, generate one if needed
    String contextId = element.getAttribute("id");
    boolean implicitId = false;

    // lets avoid folks having to explicitly give an ID to a camel context
    if (ObjectHelper.isEmpty(contextId)) {
      // if no explicit id was set then use a default auto generated name
      CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy();
      contextId = strategy.getName();
      element.setAttribute("id", contextId);
      implicitId = true;
    }

    // now lets parse the routes with JAXB
    Binder<Node> binder;
    try {
      binder = getJaxbContext().createBinder();
    } catch (JAXBException e) {
      throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e);
    }
    Object value = parseUsingJaxb(element, context, binder);
    if (!(value instanceof CamelContextFactoryBean)) {
      throw new ComponentDefinitionException(
          "Expected an instance of " + CamelContextFactoryBean.class);
    }

    CamelContextFactoryBean ccfb = (CamelContextFactoryBean) value;
    ccfb.setImplicitId(implicitId);

    MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class);
    factory.setId(".camelBlueprint.passThrough." + contextId);
    factory.setObject(new PassThroughCallable<Object>(value));

    MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class);
    factory2.setId(".camelBlueprint.factory." + contextId);
    factory2.setFactoryComponent(factory);
    factory2.setFactoryMethod("call");
    factory2.setInitMethod("afterPropertiesSet");
    factory2.setDestroyMethod("destroy");
    factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
    factory2.addProperty("bundleContext", createRef(context, "blueprintBundleContext"));
    context.getComponentDefinitionRegistry().registerComponentDefinition(factory2);

    MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class);
    ctx.setId(contextId);
    ctx.setRuntimeClass(BlueprintCamelContext.class);
    ctx.setFactoryComponent(factory2);
    ctx.setFactoryMethod("getContext");
    ctx.setInitMethod("init");
    ctx.setDestroyMethod("destroy");

    // Register objects
    registerBeans(context, contextId, ccfb.getEndpoints());
    registerBeans(context, contextId, ccfb.getThreadPools());
    registerBeans(context, contextId, ccfb.getBeans());

    // Register processors
    MutablePassThroughMetadata beanProcessorFactory =
        context.createMetadata(MutablePassThroughMetadata.class);
    beanProcessorFactory.setId(".camelBlueprint.processor.bean.passThrough." + contextId);
    beanProcessorFactory.setObject(new PassThroughCallable<Object>(new CamelInjector(contextId)));

    MutableBeanMetadata beanProcessor = context.createMetadata(MutableBeanMetadata.class);
    beanProcessor.setId(".camelBlueprint.processor.bean." + contextId);
    beanProcessor.setRuntimeClass(CamelInjector.class);
    beanProcessor.setFactoryComponent(beanProcessorFactory);
    beanProcessor.setFactoryMethod("call");
    beanProcessor.setProcessor(true);
    beanProcessor.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
    context.getComponentDefinitionRegistry().registerComponentDefinition(beanProcessor);

    MutablePassThroughMetadata regProcessorFactory =
        context.createMetadata(MutablePassThroughMetadata.class);
    regProcessorFactory.setId(".camelBlueprint.processor.registry.passThrough." + contextId);
    regProcessorFactory.setObject(
        new PassThroughCallable<Object>(new CamelDependenciesFinder(contextId, context)));

    MutableBeanMetadata regProcessor = context.createMetadata(MutableBeanMetadata.class);
    regProcessor.setId(".camelBlueprint.processor.registry." + contextId);
    regProcessor.setRuntimeClass(CamelDependenciesFinder.class);
    regProcessor.setFactoryComponent(regProcessorFactory);
    regProcessor.setFactoryMethod("call");
    regProcessor.setProcessor(true);
    regProcessor.addDependsOn(".camelBlueprint.processor.bean." + contextId);
    regProcessor.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
    context.getComponentDefinitionRegistry().registerComponentDefinition(regProcessor);
    return ctx;
  }
Esempio n. 26
0
  private boolean matchMethod(Method method, String methodName) {
    if (methodName == null) {
      return true;
    }

    if (methodName.contains("(") && !methodName.endsWith(")")) {
      throw new IllegalArgumentException(
          "Name must have both starting and ending parenthesis, was: " + methodName);
    }

    // do not use qualifier for name matching
    String name = methodName;
    if (name.contains("(")) {
      name = ObjectHelper.before(name, "(");
    }

    // must match name
    if (name != null && !name.equals(method.getName())) {
      return false;
    }

    // is it a method with no parameters
    boolean noParameters = methodName.endsWith("()");
    if (noParameters) {
      return method.getParameterTypes().length == 0;
    }

    // match qualifier types which is used to select among overloaded methods
    String types = ObjectHelper.between(methodName, "(", ")");
    if (ObjectHelper.isNotEmpty(types)) {
      // we must qualify based on types to match method
      String[] parameters = StringQuoteHelper.splitSafeQuote(types, ',');
      Iterator<?> it = ObjectHelper.createIterator(parameters);
      for (int i = 0; i < method.getParameterTypes().length; i++) {
        if (it.hasNext()) {
          Class<?> parameterType = method.getParameterTypes()[i];

          String qualifyType = (String) it.next();
          if (ObjectHelper.isEmpty(qualifyType)) {
            continue;
          }
          // trim the type
          qualifyType = qualifyType.trim();

          if ("*".equals(qualifyType)) {
            // * is a wildcard so we accept and match that parameter type
            continue;
          }

          if (BeanHelper.isValidParameterValue(qualifyType)) {
            // its a parameter value, so continue to next parameter
            // as we should only check for FQN/type parameters
            continue;
          }

          // if qualify type indeed is a class, then it must be assignable with the parameter type
          Boolean assignable =
              BeanHelper.isAssignableToExpectedType(
                  getCamelContext().getClassResolver(), qualifyType, parameterType);
          // the method will return null if the qualifyType is not a class
          if (assignable != null && !assignable) {
            return false;
          }

        } else {
          // there method has more parameters than was specified in the method name qualifiers
          return false;
        }
      }

      // if the method has no more types then we can only regard it as matched
      // if there are no more qualifiers
      if (it.hasNext()) {
        return false;
      }
    }

    // the method matched
    return true;
  }
Esempio n. 27
0
    @Override
    protected void doParse(
        Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
      renameNamespaceRecursive(element);
      super.doParse(element, parserContext, builder);

      String contextId = element.getAttribute("id");
      boolean implicitId = false;

      // lets avoid folks having to explicitly give an ID to a camel context
      if (ObjectHelper.isEmpty(contextId)) {
        // if no explicit id was set then use a default auto generated name
        CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy();
        contextId = strategy.getName();
        element.setAttributeNS(null, "id", contextId);
        implicitId = true;
      }

      // now lets parse the routes with JAXB
      Binder<Node> binder;
      try {
        binder = getJaxbContext().createBinder();
      } catch (JAXBException e) {
        throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
      }
      Object value = parseUsingJaxb(element, parserContext, binder);

      if (value instanceof CamelContextFactoryBean) {
        // set the property value with the JAXB parsed value
        CamelContextFactoryBean factoryBean = (CamelContextFactoryBean) value;
        builder.addPropertyValue("id", contextId);
        builder.addPropertyValue("implicitId", implicitId);
        builder.addPropertyValue("routes", factoryBean.getRoutes());
        builder.addPropertyValue("intercepts", factoryBean.getIntercepts());
        builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms());
        builder.addPropertyValue(
            "interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints());
        builder.addPropertyValue("dataFormats", factoryBean.getDataFormats());
        builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions());
        builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions());
        builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
        builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs());
        builder.addPropertyValue("properties", factoryBean.getProperties());
        builder.addPropertyValue("packageScan", factoryBean.getPackageScan());
        builder.addPropertyValue("contextScan", factoryBean.getContextScan());
        if (factoryBean.getPackages().length > 0) {
          builder.addPropertyValue("packages", factoryBean.getPackages());
        }
        builder.addPropertyValue(
            "camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder());
        builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent());
        builder.addPropertyValue(
            "camelStreamCachingStrategy", factoryBean.getCamelStreamCachingStrategy());
        builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles());
        // add any depends-on
        addDependsOn(factoryBean, builder);
      }

      NodeList list = element.getChildNodes();
      int size = list.getLength();
      for (int i = 0; i < size; i++) {
        Node child = list.item(i);
        if (child instanceof Element) {
          Element childElement = (Element) child;
          String localName = child.getLocalName();
          if (localName.equals("endpoint")) {
            registerEndpoint(childElement, parserContext, contextId);
          } else if (localName.equals("routeBuilder")) {
            addDependsOnToRouteBuilder(childElement, parserContext, contextId);
          } else {
            BeanDefinitionParser parser = parserMap.get(localName);
            if (parser != null) {
              BeanDefinition definition = parser.parse(childElement, parserContext);
              String id = childElement.getAttribute("id");
              if (ObjectHelper.isNotEmpty(id)) {
                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
                // set the templates with the camel context
                if (localName.equals("template")
                    || localName.equals("consumerTemplate")
                    || localName.equals("proxy")
                    || localName.equals("export")) {
                  // set the camel context
                  definition
                      .getPropertyValues()
                      .addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
                }
              }
            }
          }
        }
      }

      // register as endpoint defined indirectly in the routes by from/to types having id explicit
      // set
      registerEndpointsWithIdsDefinedInFromOrToTypes(element, parserContext, contextId, binder);

      // register templates if not already defined
      registerTemplates(element, parserContext, contextId);

      // lets inject the namespaces into any namespace aware POJOs
      injectNamespaces(element, binder);

      // inject bean post processor so we can support @Produce etc.
      // no bean processor element so lets create it by our self
      injectBeanPostProcessor(element, parserContext, contextId, builder);
    }