@Test
  public void testHeaderAndTrailer() throws Exception {
    results.expectedMessageCount(1);
    results.message(0).body().isInstanceOf(List.class);
    results.message(0).header("camelFlatpackCounter").isEqualTo(6);

    results.assertIsSatisfied();

    List<Map<String, String>> data =
        CastUtils.cast(results.getExchanges().get(0).getIn().getBody(List.class));

    // assert header
    Map<String, String> header = data.get(0);
    assertEquals("HBT", header.get("INDICATOR"));
    assertEquals("20080817", header.get("DATE"));

    // assert body
    int counter = 0;
    for (Map<String, String> row : data.subList(1, 5)) {
      assertEquals("FIRSTNAME", expectedFirstName[counter], row.get("FIRSTNAME"));
      LOG.info("Result: " + counter + " = " + row);
      counter++;
    }

    // assert trailer
    Map<String, String> trailer = data.get(5);
    assertEquals("FBT", trailer.get("INDICATOR"));
    assertEquals("SUCCESS", trailer.get("STATUS"));
  }
Exemplo n.º 2
0
 @Override
 public void configureProperties(Map<String, Object> options) {
   super.configureProperties(options);
   Map<String, Object> emProperties = IntrospectionSupport.extractProperties(options, "emf.");
   if (emProperties != null) {
     setEntityManagerProperties(CastUtils.cast(emProperties));
   }
 }
Exemplo n.º 3
0
 /**
  * Removes the associated {@link org.apache.camel.processor.aggregate.AggregationStrategy} from
  * the {@link Exchange} which must be done after use.
  *
  * @param exchange the current exchange
  */
 protected void removeAggregationStrategyFromExchange(Exchange exchange) {
   Map<?, ?> property = exchange.getProperty(Exchange.AGGREGATION_STRATEGY, Map.class);
   Map<Object, AggregationStrategy> map = CastUtils.cast(property);
   if (map == null) {
     return;
   }
   // remove the strategy using this processor as the key
   map.remove(this);
 }
Exemplo n.º 4
0
  private Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact)
      throws MojoExecutionException {

    Set<Artifact> executableDependencies;
    try {
      MavenProject executableProject =
          this.projectBuilder.buildFromRepository(
              executablePomArtifact, this.remoteRepositories, this.localRepository);

      // get all of the dependencies for the executable project
      List<Artifact> dependencies = CastUtils.cast(executableProject.getDependencies());

      // make Artifacts of all the dependencies
      Set<Artifact> dependencyArtifacts =
          CastUtils.cast(
              MavenMetadataSource.createArtifacts(
                  this.artifactFactory, dependencies, null, null, null));

      // not forgetting the Artifact of the project itself
      dependencyArtifacts.add(executableProject.getArtifact());

      // resolve all dependencies transitively to obtain a comprehensive
      // list of assemblies
      ArtifactResolutionResult result =
          artifactResolver.resolveTransitively(
              dependencyArtifacts,
              executablePomArtifact,
              Collections.EMPTY_MAP,
              this.localRepository,
              this.remoteRepositories,
              metadataSource,
              null,
              Collections.EMPTY_LIST);
      executableDependencies = CastUtils.cast(result.getArtifacts());

    } catch (Exception ex) {
      throw new MojoExecutionException(
          "Encountered problems resolving dependencies of the executable "
              + "in preparation for its execution.",
          ex);
    }

    return executableDependencies;
  }
Exemplo n.º 5
0
  /**
   * Create a parent context that initializes a {@link
   * org.apache.camel.spi.PackageScanClassResolver} to exclude a set of given classes from being
   * resolved. Typically this is used at test time to exclude certain routes, which might otherwise
   * be just noisy, from being discovered and initialized.
   *
   * <p>To use this filtering mechanism it is necessary to provide the {@link ApplicationContext}
   * returned from here as the parent context to your test context e.g.
   *
   * <pre>
   * protected AbstractXmlApplicationContext createApplicationContext() {
   *     return new ClassPathXmlApplicationContext(new String[] {&quot;test-context.xml&quot;}, getRouteExcludingApplicationContext());
   * }
   * </pre>
   *
   * This will, in turn, call the template methods <code>excludedRoutes</code> and <code>
   * excludedRoute</code> to determine the classes to be excluded from scanning.
   *
   * @return ApplicationContext a parent {@link ApplicationContext} configured to exclude certain
   *     classes from package scanning
   */
  protected ApplicationContext getRouteExcludingApplicationContext() {
    GenericApplicationContext routeExcludingContext = new GenericApplicationContext();
    routeExcludingContext.registerBeanDefinition(
        "excludingResolver", new RootBeanDefinition(ExcludingPackageScanClassResolver.class));
    routeExcludingContext.refresh();

    ExcludingPackageScanClassResolver excludingResolver =
        (ExcludingPackageScanClassResolver) routeExcludingContext.getBean("excludingResolver");
    List<Class<?>> excluded = CastUtils.cast(Arrays.asList(excludeRoutes()));
    excludingResolver.setExcludedClasses(new HashSet<Class<?>>(excluded));

    return routeExcludingContext;
  }
Exemplo n.º 6
0
  private Expression createParameterUnmarshalExpressionForAnnotation(
      Class<?> clazz, Method method, Class<?> parameterType, Annotation annotation) {
    if (annotation instanceof AttachmentObjects) {
      return ExpressionBuilder.attachmentObjectsExpression();
    } else if (annotation instanceof Attachments) {
      return ExpressionBuilder.attachmentsExpression();
    } else if (annotation instanceof Property) {
      Property propertyAnnotation = (Property) annotation;
      return ExpressionBuilder.exchangePropertyExpression(propertyAnnotation.value());
    } else if (annotation instanceof ExchangeProperty) {
      ExchangeProperty propertyAnnotation = (ExchangeProperty) annotation;
      return ExpressionBuilder.exchangePropertyExpression(propertyAnnotation.value());
    } else if (annotation instanceof Properties) {
      return ExpressionBuilder.propertiesExpression();
    } else if (annotation instanceof Header) {
      Header headerAnnotation = (Header) annotation;
      return ExpressionBuilder.headerExpression(headerAnnotation.value());
    } else if (annotation instanceof Headers) {
      return ExpressionBuilder.headersExpression();
    } else if (annotation instanceof OutHeaders) {
      return ExpressionBuilder.outHeadersExpression();
    } else if (annotation instanceof ExchangeException) {
      return ExpressionBuilder.exchangeExceptionExpression(
          CastUtils.cast(parameterType, Exception.class));
    } else {
      LanguageAnnotation languageAnnotation =
          annotation.annotationType().getAnnotation(LanguageAnnotation.class);
      if (languageAnnotation != null) {
        Class<?> type = languageAnnotation.factory();
        Object object = camelContext.getInjector().newInstance(type);
        if (object instanceof AnnotationExpressionFactory) {
          AnnotationExpressionFactory expressionFactory = (AnnotationExpressionFactory) object;
          return expressionFactory.createExpression(
              camelContext, annotation, languageAnnotation, parameterType);
        } else {
          LOG.warn(
              "Ignoring bad annotation: "
                  + languageAnnotation
                  + "on method: "
                  + method
                  + " which declares a factory: "
                  + type.getName()
                  + " which does not implement "
                  + AnnotationExpressionFactory.class.getName());
        }
      }
    }

    return null;
  }
Exemplo n.º 7
0
 /**
  * Sets the given {@link org.apache.camel.processor.aggregate.AggregationStrategy} on the {@link
  * Exchange}.
  *
  * @param exchange the exchange
  * @param aggregationStrategy the strategy
  */
 protected void setAggregationStrategyOnExchange(
     Exchange exchange, AggregationStrategy aggregationStrategy) {
   Map<?, ?> property = exchange.getProperty(Exchange.AGGREGATION_STRATEGY, Map.class);
   Map<Object, AggregationStrategy> map = CastUtils.cast(property);
   if (map == null) {
     map = new ConcurrentHashMap<Object, AggregationStrategy>();
   } else {
     // it is not safe to use the map directly as the exchange doesn't have the deep copy of it's
     // properties
     // we just create a new copy if we need to change the map
     map = new ConcurrentHashMap<Object, AggregationStrategy>(map);
   }
   // store the strategy using this processor as the key
   // (so we can store multiple strategies on the same exchange)
   map.put(this, aggregationStrategy);
   exchange.setProperty(Exchange.AGGREGATION_STRATEGY, map);
 }
Exemplo n.º 8
0
  protected AggregationStrategy getAggregationStrategy(Exchange exchange) {
    AggregationStrategy answer = null;

    // prefer to use per Exchange aggregation strategy over a global strategy
    if (exchange != null) {
      Map<?, ?> property = exchange.getProperty(Exchange.AGGREGATION_STRATEGY, Map.class);
      Map<Object, AggregationStrategy> map = CastUtils.cast(property);
      if (map != null) {
        answer = map.get(this);
      }
    }
    if (answer == null) {
      // fallback to global strategy
      answer = getAggregationStrategy();
    }
    return answer;
  }
Exemplo n.º 9
0
  @Override
  protected int poll() throws Exception {
    GetRecordsRequest req =
        new GetRecordsRequest()
            .withShardIterator(getShardItertor())
            .withLimit(getEndpoint().getMaxResultsPerRequest());
    GetRecordsResult result = getClient().getRecords(req);

    Queue<Exchange> exchanges = createExchanges(result.getRecords());
    int processedExchangeCount = processBatch(CastUtils.cast(exchanges));

    // May cache the last successful sequence number, and pass it to the
    // getRecords request. That way, on the next poll, we start from where
    // we left off, however, I don't know what happens to subsequent
    // exchanges when an earlier echangee fails.

    currentShardIterator = result.getNextShardIterator();

    return processedExchangeCount;
  }
Exemplo n.º 10
0
  /**
   * Add any relevant project dependencies to the classpath. Takes includeProjectDependencies into
   * consideration.
   *
   * @param path classpath of {@link java.net.URL} objects
   * @throws MojoExecutionException
   */
  private void addRelevantProjectDependenciesToClasspath(Set<URL> path)
      throws MojoExecutionException {
    if (this.includeProjectDependencies) {
      try {
        getLog().debug("Project Dependencies will be included.");

        URL mainClasses = new File(project.getBuild().getOutputDirectory()).toURI().toURL();
        getLog().debug("Adding to classpath : " + mainClasses);
        path.add(mainClasses);

        Set<Artifact> dependencies = CastUtils.cast(project.getArtifacts());

        // system scope dependencies are not returned by maven 2.0. See
        // MEXEC-17
        dependencies.addAll(getAllNonTestScopedDependencies());

        Iterator<Artifact> iter = dependencies.iterator();
        while (iter.hasNext()) {
          Artifact classPathElement = iter.next();
          getLog()
              .debug(
                  "Adding project dependency artifact: "
                      + classPathElement.getArtifactId()
                      + " to classpath");
          File file = classPathElement.getFile();
          if (file != null) {
            path.add(file.toURI().toURL());
          }
        }

      } catch (MalformedURLException e) {
        throw new MojoExecutionException("Error during setting up classpath", e);
      }
    } else {
      getLog().debug("Project Dependencies will be excluded.");
    }
  }
Exemplo n.º 11
0
  @Override
  protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;
    pendingExchanges = 0;

    String fileName = getConfiguration().getFileName();
    String bucketName = getConfiguration().getBucketName();
    Queue<Exchange> exchanges = null;

    if (fileName != null) {
      LOG.trace("Getting object in bucket [{}] with file name [{}]...", bucketName, fileName);

      S3Object s3Object = getAmazonS3Client().getObject(new GetObjectRequest(bucketName, fileName));
      exchanges = createExchanges(s3Object);
    } else {
      LOG.trace("Queueing objects in bucket [{}]...", bucketName);

      ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
      listObjectsRequest.setBucketName(bucketName);
      listObjectsRequest.setPrefix(getConfiguration().getPrefix());
      listObjectsRequest.setMaxKeys(maxMessagesPerPoll);

      ObjectListing listObjects = getAmazonS3Client().listObjects(listObjectsRequest);

      if (LOG.isTraceEnabled()) {
        LOG.trace(
            "Found {} objects in bucket [{}]...",
            listObjects.getObjectSummaries().size(),
            bucketName);
      }

      exchanges = createExchanges(listObjects.getObjectSummaries());
    }
    return processBatch(CastUtils.cast(exchanges));
  }