org.apache.camel.Exchange Java Examples

The following examples show how to use org.apache.camel.Exchange. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CamelUserProvisioningManager.java    From syncope with Apache License 2.0 14 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Pair<String, List<PropagationStatus>> reactivate(
        final StatusR statusR, final boolean nullPriorityAsync, final String updater, final String context) {

    PollingConsumer pollingConsumer = getConsumer("direct:statusPort");

    Map<String, Object> props = new HashMap<>();
    props.put("key", statusR.getKey());
    props.put("statusR", statusR);
    props.put("nullPriorityAsync", nullPriorityAsync);
    props.put("updater", updater);
    props.put("context", context);

    if (statusR.isOnSyncope()) {
        sendMessage("direct:reactivateUser", statusR.getKey(), props);
    } else {
        UserWorkflowResult<String> updated =
                new UserWorkflowResult<>(statusR.getKey(), null, null, statusR.getType().name().toLowerCase());
        sendMessage("direct:userStatusPropagation", updated, props);
    }

    Exchange exchange = pollingConsumer.receive();

    if (exchange.getProperty(Exchange.EXCEPTION_CAUGHT) != null) {
        throw (RuntimeException) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
    }

    return exchange.getIn().getBody(Pair.class);
}
 
Example #2
Source File: FlipRoutePolicy.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
@Override
public void onExchangeDone(Route route, Exchange exchange) {
    // decide which route to stop and start
    // basically we should flip the two routes
    String stop = route.getId().equals(name1) ? name1 : name2;
    String start = route.getId().equals(name1) ? name2 : name1;

    CamelContext context = exchange.getContext();
    try {
        // force stopping this route while we are routing an Exchange
        // requires two steps:
        // 1) unregister from the inflight registry
        // 2) stop the route
        context.getInflightRepository().remove(exchange);
        context.stopRoute(stop);
        // then we can start the other route
        context.startRoute(start);
    } catch (Exception e) {
        // let the exception handle handle it, which is often just to log it
        getExceptionHandler().handleException("Error flipping routes", e);
    }
}
 
Example #3
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
/**
 * Strategy to create the unit of work to be used for the sub route
 *
 * @param routeContext the route context
 * @param processor    the processor
 * @param exchange     the exchange
 * @return the unit of work processor
 */
protected Processor createUnitOfWorkProcessor(RouteContext routeContext, Processor processor, Exchange exchange) {
    String routeId = routeContext != null ? routeContext.getRoute().idOrCreate(routeContext.getCamelContext().getNodeIdFactory()) : null;
    CamelInternalProcessor internal = new CamelInternalProcessor(processor);

    // and wrap it in a unit of work so the UoW is on the top, so the entire route will be in the same UoW
    UnitOfWork parent = exchange.getProperty(Exchange.PARENT_UNIT_OF_WORK, UnitOfWork.class);
    if (parent != null) {
        internal.addAdvice(new CamelInternalProcessor.ChildUnitOfWorkProcessorAdvice(routeId, parent));
    } else {
        internal.addAdvice(new CamelInternalProcessor.UnitOfWorkProcessorAdvice(routeId));
    }

    // and then in route context so we can keep track which route this is at runtime
    if (routeContext != null) {
        internal.addAdvice(new CamelInternalProcessor.RouteContextAdvice(routeContext));
    }
    return internal;
}
 
Example #4
Source File: AhcWSSIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncWssRoute() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("ahc-wss:" + WEBSOCKET_ENDPOINT);
            from("ahc-wss:" + WEBSOCKET_ENDPOINT).to("seda:end");
        }
    });

    WsComponent wsComponent = (WsComponent) camelctx.getComponent("ahc-wss");
    wsComponent.setSslContextParameters(defineSSLContextClientParameters());

    PollingConsumer consumer = camelctx.getEndpoint("seda:end").createPollingConsumer();
    consumer.start();

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        producer.sendBody("direct:start", "Kermit");

        Exchange exchange = consumer.receive(1000);
        Assert.assertEquals("Hello Kermit", exchange.getIn().getBody(String.class));

    } finally {
        camelctx.close();
    }
}
 
Example #5
Source File: CafeApiTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetInvalid() throws Exception {
    final int size = getMenuService().getMenuItems().size();

    try {
        // TODO: report camel-undertow not throwing exception on failure
        String out = fluentTemplate().to("netty4-http:http://localhost:" + port1 + "/cafe/menu/items/" + (size + 1))
                .withHeader(Exchange.HTTP_METHOD, "GET")
                .request(String.class);
    } catch (Exception e) {
        // Expect Exception to be thrown since we're requesting an item that does not exist
        //System.out.println("Exception Message = " + e.getMessage());
        return;
    }

    fail("Expected call to fail with exception thrown");
}
 
Example #6
Source File: CustomContextTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "process/custom.bpmn20.xml" })
public void testRunProcess() throws Exception {
  CamelContext ctx = applicationContext.getBean(CamelContext.class);
  ProducerTemplate tpl = ctx.createProducerTemplate();
  service1.expectedBodiesReceived("ala");

  Exchange exchange = ctx.getEndpoint("direct:start").createExchange();
  exchange.getIn().setBody(Collections.singletonMap("var1", "ala"));
  tpl.send("direct:start", exchange);

  String instanceId = (String) exchange.getProperty("PROCESS_ID_PROPERTY");

  tpl.sendBodyAndProperty("direct:receive", null, ActivitiProducer.PROCESS_ID_PROPERTY, instanceId);

  assertProcessEnded(instanceId);

  service1.assertIsSatisfied();

  @SuppressWarnings("rawtypes")
  Map m = service2.getExchanges().get(0).getIn().getBody(Map.class);
  assertEquals("ala", m.get("var1"));
  assertEquals("var2", m.get("var2"));
}
 
Example #7
Source File: SecondMockTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsCamelMessage() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:quote");
    mock.expectedMessageCount(2);

    template.sendBody("stub:jms:topic:quote", "Hello Camel");
    template.sendBody("stub:jms:topic:quote", "Camel rocks");

    assertMockEndpointsSatisfied();

    List<Exchange> list = mock.getReceivedExchanges();
    String body1 = list.get(0).getIn().getBody(String.class);
    String body2 = list.get(1).getIn().getBody(String.class);
    assertTrue(body1.contains("Camel"));
    assertTrue(body2.contains("Camel"));
}
 
Example #8
Source File: FileEntryLatchTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceive() throws Exception {
    Exchange exchange =  new DefaultExchange(new DefaultCamelContext());
    IngestionFileEntry entry = new IngestionFileEntry("/", FileFormat.EDFI_XML, FileType.XML_STUDENT_PROGRAM, "fileName", "111");
    FileEntryWorkNote workNote = new FileEntryWorkNote("batchJobId", entry, false);
    boolean fileEntryLatchOpened;

    exchange.getIn().setBody(workNote, FileEntryWorkNote.class);

    fileEntryLatchOpened = fileEntryLatch.lastFileProcessed(exchange);

    Assert.assertFalse(fileEntryLatchOpened);

    fileEntryLatchOpened = fileEntryLatch.lastFileProcessed(exchange);

    Assert.assertTrue(fileEntryLatchOpened);
}
 
Example #9
Source File: SimpleProcessTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "process/example.bpmn20.xml" })
public void testRunProcess() throws Exception {
  CamelContext ctx = applicationContext.getBean(CamelContext.class);
  ProducerTemplate tpl = ctx.createProducerTemplate();
  service1.expectedBodiesReceived("ala");

  Exchange exchange = ctx.getEndpoint("direct:start").createExchange();
  exchange.getIn().setBody(Collections.singletonMap("var1", "ala"));
  tpl.send("direct:start", exchange);
  String instanceId = (String) exchange.getProperty("PROCESS_ID_PROPERTY");

  tpl.sendBodyAndProperty("direct:receive", null, ActivitiProducer.PROCESS_ID_PROPERTY, instanceId);

  assertProcessEnded(instanceId);

  service1.assertIsSatisfied();
  Map<?, ?> m = service2.getExchanges().get(0).getIn().getBody(Map.class);
  assertEquals("ala", m.get("var1"));
  assertEquals("var2", m.get("var2"));
}
 
Example #10
Source File: KuduCreateTableCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private void beforeProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    final KuduTable model = exchange.getIn().getBody(KuduTable.class);

    if (model != null && ObjectHelper.isNotEmpty(model.getSchema())) {
        schema = model.getSchema();
    }

    KuduTable.ColumnSchema[] columnSchema = schema.getColumns();
    List<ColumnSchema> columns = new ArrayList<>(columnSchema.length);
    List<String> rangeKeys = new ArrayList<>();
    for (int i = 0; i < columnSchema.length; i++) {
        if (columnSchema[i].isKey()) {
            rangeKeys.add(columnSchema[i].getName());
        }

        columns.add(
                new ColumnSchema.ColumnSchemaBuilder(columnSchema[i].getName(), convertType(columnSchema[i].getType()))
                        .key(columnSchema[i].isKey())
                        .build()
        );
    }

    in.setHeader("Schema", new Schema(columns));
    in.setHeader("TableOptions", new CreateTableOptions().setRangePartitionColumns(rangeKeys));
}
 
Example #11
Source File: ReuseErrorHandlerTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderOk() throws Exception {
    // we do not expect any errors and therefore no messages in the dead letter queue
    getMockEndpoint("mock:dead").expectedMessageCount(0);

    // we expect the file to be converted to csv and routed to the 2nd route
    MockEndpoint file = getMockEndpoint("mock:file");
    file.expectedMessageCount(1);

    // we expect the 2nd route to complete
    MockEndpoint mock = getMockEndpoint("mock:queue.order");
    mock.expectedBodiesReceived("amount=1,name=Camel in Action,id=123,status=OK");

    template.sendBodyAndHeader("file://target/orders", "amount=1#name=Camel in Action", Exchange.FILE_NAME, "order.txt");

    assertMockEndpointsSatisfied();
}
 
Example #12
Source File: DlcSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testDlqMultistep() throws Exception {
    final MockEndpoint mockResult = getMockEndpoint("mock:result");
    mockResult.expectedMessageCount(1);
    mockResult.expectedBodiesReceived("Foo");
    mockResult.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isNull();
    mockResult.message(0).header("myHeader").isEqualTo("changed");

    final MockEndpoint mockError = getMockEndpoint("mock:error");
    mockError.expectedMessageCount(1);
    mockError.expectedBodiesReceived("KaBoom");
    mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isNotNull();
    mockError.message(0).exchangeProperty(Exchange.FAILURE_ROUTE_ID).isEqualTo("myFlakyRoute");
    mockError.message(0).header("myHeader").isEqualTo("flaky");

    template.sendBodyAndHeader("direct:multiroute", "Foo", "myHeader", "original");
    template.sendBodyAndHeader("direct:multiroute", "KaBoom", "myHeader", "original");

    assertMockEndpointsSatisfied();
}
 
Example #13
Source File: SplitReaggregateTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
private void assertBooksByCategory(Exchange exchange) {
    Message in = exchange.getIn();
    @SuppressWarnings("unchecked")
    Set<String> books = Collections.checkedSet(in.getBody(Set.class), String.class);
    String category = in.getHeader("category", String.class);
    switch (category) {
        case "Tech":
            assertTrue(books.containsAll(Collections.singletonList("Apache Camel Developer's Cookbook")));
            break;
        case "Cooking":
            assertTrue(books.containsAll(Arrays.asList("Camel Cookbook",
                "Double decadence with extra cream", "Cooking with Butter")));
            break;
        default:
            fail();
            break;
    }
}
 
Example #14
Source File: NormalizerSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testNormalizeJson() throws Exception {
    final InputStream resource = getClass().getClassLoader().getResourceAsStream("bookstore.json");
    final String request = context().getTypeConverter().convertTo(String.class, resource);

    getMockEndpoint("mock:unknown").setExpectedMessageCount(0);
    getMockEndpoint("mock:csv").setExpectedMessageCount(0);
    getMockEndpoint("mock:xml").setExpectedMessageCount(0);

    getMockEndpoint("mock:json").expectedBodiesReceived(getExpectedBookstore());
    getMockEndpoint("mock:normalized").expectedBodiesReceived(getExpectedBookstore());

    template.sendBodyAndHeader("direct:start", request, Exchange.FILE_NAME, "bookstore.json");

    assertMockEndpointsSatisfied();
}
 
Example #15
Source File: PurgeProcessorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoTenantId() throws Exception {

    RangedWorkNote workNote = RangedWorkNote.createSimpleWorkNote(BATCHJOBID);

    Exchange ex = Mockito.mock(Exchange.class);
    Message message = Mockito.mock(Message.class);
    Mockito.when(ex.getIn()).thenReturn(message);
    Mockito.when(message.getBody(WorkNote.class)).thenReturn(workNote);

    NewBatchJob job = new NewBatchJob();
    Mockito.when(mockBatchJobDAO.findBatchJobById(BATCHJOBID)).thenReturn(job);

    AbstractMessageReport messageReport = Mockito.mock(AbstractMessageReport.class);
    purgeProcessor.setMessageReport(messageReport);

    purgeProcessor.process(ex);
    Mockito.verify(messageReport, Mockito.atLeastOnce()).error(Matchers.any(ReportStats.class),
            Matchers.any(Source.class), Matchers.eq(CoreMessageCode.CORE_0035));
}
 
Example #16
Source File: NormalizerTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testNormalizeJson() throws Exception {
    final InputStream resource = getClass().getClassLoader().getResourceAsStream("bookstore.json");
    final String request = context().getTypeConverter().convertTo(String.class, resource);

    getMockEndpoint("mock:unknown").setExpectedMessageCount(0);
    getMockEndpoint("mock:csv").setExpectedMessageCount(0);
    getMockEndpoint("mock:xml").setExpectedMessageCount(0);

    getMockEndpoint("mock:json").expectedBodiesReceived(getExpectedBookstore());
    getMockEndpoint("mock:normalized").expectedBodiesReceived(getExpectedBookstore());

    template.sendBodyAndHeader("direct:start", request, Exchange.FILE_NAME, "bookstore.json");

    assertMockEndpointsSatisfied();
}
 
Example #17
Source File: UndertowLoadBalanceIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testUndertowLoadBalance() throws Exception {

    // Obtain the endpoint URL from the management model
    EndpointRegistryClient registryClient = new EndpointRegistryClient(managementClient.getControllerClient());
    final String[] endpoints = wrapEndpoints(registryClient.getRegisteredEndpoints("/undertow-load-balance"));

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").loadBalance().roundRobin().to(endpoints);
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBodyAndHeader("direct:start", null, Exchange.HTTP_QUERY, "name=Kermit", String.class);
        Assert.assertEquals("Hello Kermit", result);
    } finally {
        camelctx.close();
    }
}
 
Example #18
Source File: TracingInterceptStrategy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("try")
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    final Message in = exchange.getIn();
    final Span activitySpan = exchange.getProperty(IntegrationLoggingConstants.ACTIVITY_SPAN, Span.class);
    try (Scope activityScope = tracer.scopeManager().activate(activitySpan)) {
        Span span = tracer.buildSpan(stepId).withTag(Tags.SPAN_KIND.getKey(), "step").start();
        in.setHeader(IntegrationLoggingConstants.STEP_SPAN, span);
        return super.process(exchange, doneSync -> {
            String failure = failure(exchange);
            if (failure != null) {
                span.setTag(Tags.ERROR.getKey(), true);
                span.log(failure);
            }
            span.finish();
            callback.done(doneSync);
        });
    }
}
 
Example #19
Source File: CamelVariableTransferTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = {"org/activiti5/camel/variables/CamelVariableTransferTest.testCamelPropertiesAll.bpmn20.xml"})
public void testCamelHeadersNone() throws Exception {
  ProducerTemplate tpl = camelContext.createProducerTemplate();
  Exchange exchange = camelContext.getEndpoint("direct:startNoHeaders").createExchange();
  tpl.send("direct:startNoHeaders", exchange);
  
  assertNotNull(taskService);
  assertNotNull(runtimeService);
  assertEquals(1, taskService.createTaskQuery().count());
  Task task = taskService.createTaskQuery().singleResult();
  assertNotNull(task);
  Map<String, Object> variables = runtimeService.getVariables(task.getExecutionId());
  assertNull(variables.get("property1"));
  assertNull(variables.get("property2"));
  assertNull(variables.get("property3"));
}
 
Example #20
Source File: RouteProcessor.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    System.out.println("Process the bean MnpRouting!");
    MnpRouting mnpRouting = (MnpRouting) exchange.getIn().getBody();
    if(mnpRouting != null){
        // validate phone numbers of format "1234567890"
        if (!mnpRouting.getTelephone().matches("\\d{11}") || mnpRouting.getCredit() < CREDIT_LIMIT){
            exchange.getOut().setBody("Message doesn't pass validation");
            exchange.getOut().setHeader("key", mnpRouting.getTelephone());
        } else{
            exchange.getOut().setBody(mnpRouting.toString());
            exchange.getOut().setHeader("key", mnpRouting.getTelephone());

        }

    }
    //System.out.println(mnpRouting);
}
 
Example #21
Source File: SpringReuseErrorHandlerTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderActiveMQFail() throws Exception {
    // we expect the order to fail and end up in the dead letter queue
    getMockEndpoint("mock:dead").expectedMessageCount(1);

    // we expect the file to be converted to csv and routed to the 2nd route
    MockEndpoint file = getMockEndpoint("mock:file");
    file.expectedMessageCount(1);

    // we do not expect the 2nd route to complete
    MockEndpoint mock = getMockEndpoint("mock:queue.order");
    mock.expectedMessageCount(0);

    template.sendBodyAndHeader("file://target/orders", "amount=1#name=ActiveMQ in Action", Exchange.FILE_NAME, "order.txt");

    // wait 5 seconds to let this test run
    Thread.sleep(5000);

    assertMockEndpointsSatisfied();
}
 
Example #22
Source File: NormalizerSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testNormalizeXml() throws Exception {
    final InputStream resource = getClass().getClassLoader().getResourceAsStream("bookstore.xml");
    final String request = context().getTypeConverter().convertTo(String.class, resource);

    getMockEndpoint("mock:unknown").setExpectedMessageCount(0);
    getMockEndpoint("mock:csv").setExpectedMessageCount(0);
    getMockEndpoint("mock:json").setExpectedMessageCount(0);

    getMockEndpoint("mock:xml").expectedBodiesReceived(getExpectedBookstore());
    getMockEndpoint("mock:normalized").expectedBodiesReceived(getExpectedBookstore());

    template.sendBodyAndHeader("direct:start", request, Exchange.FILE_NAME, "bookstore.xml");

    assertMockEndpointsSatisfied();
}
 
Example #23
Source File: CamelVariableTransferTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = {"org/activiti/camel/variables/CamelVariableTransferTest.testCamelPropertiesAll.bpmn20.xml"})
public void testCamelPropertiesNone() throws Exception {
  ProducerTemplate tpl = camelContext.createProducerTemplate();
  Exchange exchange = camelContext.getEndpoint("direct:startNoProperties").createExchange();
  tpl.send("direct:startNoProperties", exchange);
  
  assertNotNull(taskService);
  assertNotNull(runtimeService);
  assertEquals(1, taskService.createTaskQuery().count());
  Task task = taskService.createTaskQuery().singleResult();
  assertNotNull(task);
  Map<String, Object> variables = runtimeService.getVariables(task.getExecutionId());
  assertNull(variables.get("property1"));
  assertNull(variables.get("property2"));
  assertNull(variables.get("property3"));
}
 
Example #24
Source File: ParamTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testPost() throws Exception {
    final String json = "{ \"name\": \"Scott\" }";

    MockEndpoint update = getMockEndpoint("mock:Scott");
    update.expectedBodiesReceived(json);

    String out = fluentTemplate().to("undertow:http://localhost:" + port1 + "/say/bye/Scott")
            .withHeader(Exchange.HTTP_METHOD, "POST")
            .withHeader(Exchange.CONTENT_ENCODING, "application/json")
            .withBody(json)
            .request(String.class);

    assertMockEndpointsSatisfied();
}
 
Example #25
Source File: RecordCounter.java    From aliada-tool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {
	final File inputFile = exchange.getIn().getBody(File.class);
	
	final Integer jobId = exchange.getIn().getHeader(Constants.JOB_ID_ATTRIBUTE_NAME, Integer.class);
	final JobInstance configuration = cache.getJobInstance(jobId);
	if (configuration == null) {
		log.error(MessageCatalog._00038_UNKNOWN_JOB_ID, jobId);
		throw new IllegalArgumentException(String.valueOf(jobId));
	}
	
	final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
	parser.parse(inputFile, new DefaultHandler() {
		private int howManyRecords;
		
		@Override
		public void startElement(
				final String uri, 
				final String localName, 
				final String qName, 
				final Attributes attributes) throws SAXException {
			if (qName.endsWith(recordElementNameWithNamespace) || qName.equals(recordElementName)) {
				howManyRecords++;
			}
		}
		
		@Override
		public void endDocument() throws SAXException {
			log.info(MessageCatalog._00046_JOB_SIZE, jobId, howManyRecords);
			final JobResource resource = jobRegistry.getJobResource(jobId);
			if (resource != null) {
				resource.setTotalRecordsCount(howManyRecords);					
			}
		}
	});
}
 
Example #26
Source File: IntegrationLoggingListener.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
    if (tracker == null) {
        return message;
    }

    final String activityId = ActivityTracker.getActivityId(exchange);
    if (activityId != null) {
        final Marker marker = camelLogger.getMarker();
        final String step = marker != null ? marker.getName() : "null";

        final Message in = exchange.getIn();
        String stepTrackerId = in.getHeader(IntegrationLoggingConstants.STEP_TRACKER_ID, String.class);
        if( stepTrackerId == null ) {
            stepTrackerId = KeyGenerator.createKey();
        }

        tracker.track(
            "exchange", activityId,
            "step", step,
            "id", stepTrackerId,
            "message", message
        );
    }

    return message;
}
 
Example #27
Source File: AWSS3DeleteObjectCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public void beforeProducer(final Exchange exchange) throws IOException {
    final Message in = exchange.getIn();
    in.setHeader(S3Constants.S3_OPERATION, S3Operations.deleteObject);

    if (filenameKey != null) {
        in.setHeader(S3Constants.KEY, filenameKey);
    }
}
 
Example #28
Source File: TracingActivityTrackingPolicy.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void onExchangeDone(Route route, Exchange exchange) {
    if (tracer == null) {
        return;
    }
    final String activityId = ActivityTracker.getActivityId(exchange);

    if (Objects.nonNull(activityId)) {
        final Span span = exchange.getProperty(IntegrationLoggingConstants.ACTIVITY_SPAN, Span.class);
        if (span != null) {
            span.setTag(Tags.ERROR.getKey(), exchange.isFailed());
            span.finish();
        }
    }
}
 
Example #29
Source File: DeltaProcessorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotPrevIngested() throws Exception{

    NeutralRecord nr = createNeutralRecord("student");
    List<NeutralRecord> neutralRecords = new ArrayList<NeutralRecord>();
    neutralRecords.add(nr);

    DidSchemaParser didSchemaParser = Mockito.mock(DidSchemaParser.class);
    Mockito.when(dIdResolver.getDidSchemaParser()).thenReturn(didSchemaParser);
    Map<String, List<DidNaturalKey>> naturalKeysMap = new HashMap<String, List<DidNaturalKey>>();
    naturalKeysMap.put(nr.getRecordType(), new ArrayList<DidNaturalKey>());
    Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(naturalKeysMap);
    Mockito.when(dIdStrategy.generateId(Mockito.any(NaturalKeyDescriptor.class))).thenReturn("recordId");

    Mockito.when(batchJobDAO.findRecordHash("tenantId", "recordId")).thenReturn(null);

    Exchange exchange = new DefaultExchange(new DefaultCamelContext());
    NeutralRecordWorkNote workNote = new NeutralRecordWorkNote(neutralRecords, "batchJobId", false);
    exchange.getIn().setBody(workNote);

    deltaProcessor.process(exchange);

    NeutralRecordWorkNote newWorkNote = exchange.getIn().getBody(NeutralRecordWorkNote.class);
    List<NeutralRecord> filteredRecords = newWorkNote.getNeutralRecords();

    Assert.assertNotNull(filteredRecords);
    Assert.assertEquals(1, filteredRecords.size());
    Assert.assertEquals("student", filteredRecords.get(0).getRecordType());

}
 
Example #30
Source File: GoogleSheetsAddChartCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private void beforeProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    final GoogleChart model = exchange.getIn().getBody(GoogleChart.class);

    if (model != null) {
        if (ObjectHelper.isNotEmpty(model.getSpreadsheetId())) {
            spreadsheetId = model.getSpreadsheetId();
        }
        if (ObjectHelper.isNotEmpty(model.getTitle())) {
            title = model.getTitle();
        }
        if (ObjectHelper.isNotEmpty(model.getSubtitle())) {
            subtitle = model.getSubtitle();
        }
    }

    BatchUpdateSpreadsheetRequest batchUpdateRequest = new BatchUpdateSpreadsheetRequest();
    batchUpdateRequest.setIncludeSpreadsheetInResponse(true);
    batchUpdateRequest.setRequests(new ArrayList<>());

    AddChartRequest addChartRequest = new AddChartRequest();
    batchUpdateRequest.getRequests().add(new Request().setAddChart(addChartRequest));

    ChartSpec chartSpec = createChartSpec(title, subtitle);
    if (model != null) {
        addChartRequest.setChart(createEmbeddedChart(model, chartSpec));
        if (model.getBasicChart() != null) {
            addBasicChart(chartSpec, model);
        } else if (model.getPieChart() != null) {
            addPieChart(chartSpec, model);
        }
    } else {
        addChartRequest.setChart(createEmptyChart(chartSpec));
    }

    in.setHeader(GoogleSheetsStreamConstants.SPREADSHEET_ID, spreadsheetId);
    in.setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "batchUpdateSpreadsheetRequest", batchUpdateRequest);
}