org.apache.camel.Message Java Examples

The following examples show how to use org.apache.camel.Message. 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: SoapPayloadConverterTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void convertXmlToCxfToXml() throws IOException, XMLStreamException {

    // read XML bytes as an XML Document
    final ByteArrayInputStream bis = new ByteArrayInputStream(IOUtils.readBytesFromStream(inputStream));
    final Document request = StaxUtils.read(bis);
    bis.reset();

    // convert XML to CxfPayload
    final Exchange exchange = createExchangeWithBody(bis);
    final Message in = exchange.getIn();
    requestConverter.process(exchange);

    Assertions.assertThat(in.getBody()).isInstanceOf(CxfPayload.class);

    // convert CxfPayload back to XML
    final SoapMessage soapMessage = new SoapMessage(Soap12.getInstance());
    in.setHeader("CamelCxfMessage", soapMessage);
    responseConverter.process(exchange);

    assertIsInstanceOf(InputStream.class, in.getBody());
    Document response = StaxUtils.read((InputStream) in.getBody());

    XMLUnit.setIgnoreAttributeOrder(true);
    assertThat(response, isSimilarTo(request).ignoreWhitespace());
}
 
Example #2
Source File: SplitReaggregateSpringTest.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 #3
Source File: SourceOverride.java    From smsrouter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
	Message message = exchange.getIn();
	
	if(!message.getHeaders().containsKey(countryHeader)) {
		logger.debug("country header {} not present", countryHeader);
		return;
	}
	
	String destCountry = message.getHeader(countryHeader, String.class)
			.toUpperCase();
	String override = overrideSources.get(destCountry);
	if(override != null) {
		logger.debug("Overriding with source number {}", override);
		message.setHeader(sourceHeader, override);
	}
}
 
Example #4
Source File: ActivityTrackingInterceptStrategy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    final String trackerId = KeyGenerator.createKey();
    final long createdAt = System.nanoTime();
    final Message in = exchange.getIn();
    in.setHeader(IntegrationLoggingConstants.STEP_TRACKER_ID, trackerId);

    return super.process(exchange, doneSync -> {
        final String activityId =  ActivityTracker.getActivityId(exchange);

        if (activityId != null) {
            tracker.track(
                "exchange", activityId,
                "step", stepId,
                "id", trackerId,
                "duration", System.nanoTime() - createdAt,
                "failure", failure(exchange)
            );
        }

        callback.done(doneSync);
    });
}
 
Example #5
Source File: FhirTransactionCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void afterProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    @SuppressWarnings("unchecked")
    List<IBaseResource> body = in.getBody(List.class);

    StringBuilder transaction = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
        "<Transaction xmlns=\"http://hl7.org/fhir\">");
    IParser parser = fhirContext.newXmlParser();
    for (IBaseResource resource: body) {
        String encodedResource = parser.encodeResourceToString(resource);
        transaction.append(encodedResource);
    }
    transaction.append("</Transaction>");

    in.setBody(transaction.toString());
}
 
Example #6
Source File: SqlConnectorCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private boolean isRecordsFound(Message in) {

        switch (statementType) {

            case SELECT:
                Integer rowCount = (Integer) in.getHeader(CamelSqlConstants.SQL_ROW_COUNT);
                if (rowCount.intValue() > 0) {
                    return true;
                }
                break;

            case UPDATE:
            case DELETE:
            case INSERT:
                Integer updateCount = (Integer) in.getHeader(CamelSqlConstants.SQL_UPDATE_COUNT);
                if (updateCount.intValue() > 0) {
                    return true;
                }
                break;

        }
        return false;
    }
 
Example #7
Source File: MqttCamelRouteBuilder.java    From Ardulink-2 with Apache License 2.0 6 votes vote down vote up
private Processor divideByValueOf(ValueBuilder valueBuilder) {
	return new Processor() {
		@Override
		public void process(Exchange exchange) throws Exception {
			Message in = exchange.getIn();
			BigDecimal sum = new BigDecimal(
					checkNotNull(in.getBody(Number.class), "Body of %s is null", in).toString());
			BigDecimal divisor = new BigDecimal(checkNotNull(valueBuilder.evaluate(exchange, Integer.class),
					"No %s set in exchange %s", valueBuilder, exchange).toString());
			in.setBody(sum.divide(divisor, HALF_UP));
		}

		@Override
		public String toString() {
			return "Processor divideByValueOf by " + valueBuilder;
		}

	};
}
 
Example #8
Source File: TwitterMediaAction.java    From syndesis-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Builds JSON message body of the MediaEntities detected in the Twitter message. Removes
 * the Body of the message if no Entities are found
 *
 *
 * @param exchange 	The Camel Exchange object containing the Message, that in turn should
 * 					contain the MediaEntity and MediaURL
 */
private void process(Exchange exchange) {
	// validate input
	if (ObjectHelper.isEmpty(exchange)) {
		throw new NullPointerException("Exchange is empty. Should be impossible.");
	}

	Message message = exchange.getMessage();
	if (ObjectHelper.isEmpty(message)) {
		throw new NullPointerException("Message is empty. Should be impossible.");
	}

	Object incomingBody = message.getBody();

	if (incomingBody instanceof Status) {
		message.setBody((new TweetMedia((Status)incomingBody)).toJSON());
	} else {
		throw new ClassCastException("Body isn't Status, why are you using this component!?"
				+ (incomingBody != null ? incomingBody.getClass() : " empty"));
	}
}
 
Example #9
Source File: KnativeHttpConsumer.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
private Buffer computeResponseBody(Message message) throws NoTypeConversionAvailableException {
    Object body = message.getBody();
    Exception exception = message.getExchange().getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = sw.toString().getBytes(StandardCharsets.UTF_8);
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain");

        // and mark the exception as failure handled, as we handled it by returning
        // it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }

    return body != null
        ? Buffer.buffer(message.getExchange().getContext().getTypeConverter().mandatoryConvertTo(byte[].class, body))
        : null;
}
 
Example #10
Source File: FhirSearchCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void afterProducer(Exchange exchange) {
    Message in = exchange.getIn();
    Bundle bundle = in.getBody(Bundle.class);
    if (bundle == null) {
        return;
    }

    List<String> results = new ArrayList<>();
    for (Bundle.BundleEntryComponent entry: bundle.getEntry()) {
        String resource = fhirContext.newXmlParser().encodeResourceToString(entry.getResource());
        results.add(resource);
    }

    in.setBody(results);
}
 
Example #11
Source File: AggregateStepHandler.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    final Message message = exchange.hasOut() ? exchange.getOut() : exchange.getIn();

    if (message != null && message.getBody() instanceof List) {
        try {
            List<String> unifiedBodies = new ArrayList<>();
            List<?> jsonBeans = message.getBody(List.class);
            for (Object unifiedJsonBean : jsonBeans) {
                JsonNode unifiedJson = JsonUtils.reader().readTree(String.valueOf(unifiedJsonBean));
                if (unifiedJson.isObject()) {
                    JsonNode body = unifiedJson.get("body");
                    if (body != null) {
                        unifiedBodies.add(JsonUtils.writer().writeValueAsString(body));
                    }
                }
            }

            message.setBody("{\"body\":" + JsonUtils.jsonBeansToArray(unifiedBodies) + "}");
        } catch (JsonParseException e) {
            LOG.warn("Unable to aggregate unified json array type", e);
        }
    }
}
 
Example #12
Source File: SignaturesSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageModificationAfterSigning() throws InterruptedException {
    MockEndpoint mockSigned = getMockEndpoint("mock:signed");
    mockSigned.whenAnyExchangeReceived(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            Message in = exchange.getIn();
            in.setBody(in.getBody(String.class) + "modified");
        }
    });

    MockEndpoint mockVerified = getMockEndpoint("mock:verified");
    mockVerified.setExpectedMessageCount(0);

    try {
        template.sendBody("direct:sign", "foo");
        fail();
    } catch (CamelExecutionException cex) {
        assertTrue(ExceptionUtils.getRootCause(cex) instanceof SignatureException);
        assertEquals("SignatureException: Cannot verify signature of exchange",
            ExceptionUtils.getRootCauseMessage(cex));
    }

    assertMockEndpointsSatisfied();
}
 
Example #13
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 #14
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 #15
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
static int determineResponseCode(Exchange camelExchange, Object body) {
    boolean failed = camelExchange.isFailed();
    int defaultCode = failed ? 500 : 200;

    Message message = camelExchange.getMessage();
    Integer currentCode = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
    int codeToUse = currentCode == null ? defaultCode : currentCode;

    if (codeToUse != 500) {
        if ((body == null) || (body instanceof String && ((String) body).trim().isEmpty())) {
            // no content
            codeToUse = currentCode == null ? 204 : currentCode;
        }
    }

    return codeToUse;
}
 
Example #16
Source File: StubRunnerCamelPredicate.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private List<String> headersMatch(Message message, Contract groovyDsl) {
	List<String> unmatchedHeaders = new ArrayList<>();
	Map<String, Object> headers = message.getHeaders();
	for (Header it : groovyDsl.getInput().getMessageHeaders().getEntries()) {
		String name = it.getName();
		Object value = it.getClientValue();
		Object valueInHeader = headers.get(name);
		boolean matches;
		if (value instanceof RegexProperty) {
			Pattern pattern = ((RegexProperty) value).getPattern();
			matches = pattern.matcher(valueInHeader.toString()).matches();
		}
		else {
			matches = valueInHeader != null
					&& valueInHeader.toString().equals(value.toString());
		}
		if (!matches) {
			unmatchedHeaders.add("Header with name [" + name + "] was supposed to "
					+ unmatchedText(value) + " but the value is ["
					+ (valueInHeader != null ? valueInHeader.toString() : "null")
					+ "]");
		}
	}
	return unmatchedHeaders;
}
 
Example #17
Source File: ThrottlerDynamicTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testThrottleDynamic() throws Exception {
    final int throttleRate = 3;
    final int messageCount = throttleRate + 2;

    getMockEndpoint("mock:unthrottled").expectedMessageCount(messageCount);
    getMockEndpoint("mock:throttled").expectedMessageCount(throttleRate);
    getMockEndpoint("mock:after").expectedMessageCount(throttleRate);

    for (int i = 0; i < messageCount; i++) {
        Exchange exchange = getMandatoryEndpoint("direct:start").createExchange();
        {
            Message in = exchange.getIn();
            in.setHeader("throttleRate", throttleRate);
            in.setBody("Camel Rocks");
        }
        template.asyncSend("direct:start", exchange);
    }

    // the test will stop once all of the conditions have been met
    // the only way this set of conditions can happen is if 2
    // messages are currently suspended for throttling
    assertMockEndpointsSatisfied();
}
 
Example #18
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 #19
Source File: AuthenticationCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static void assertHeaderSetTo(final ComponentProxyComponent component, final String headerName, final String headerValue) throws Exception {
    final Processor processor = component.getBeforeProducer();

    final Exchange exchange = mock(Exchange.class);
    final Message message = mock(Message.class);
    when(exchange.getIn()).thenReturn(message);
    when(exchange.getOut()).thenReturn(message);
    when(exchange.getPattern()).thenReturn(ExchangePattern.InOut);

    final ExtendedCamelContext context = mock(ExtendedCamelContext.class);
    when(exchange.getContext()).thenReturn(context);

    final AsyncProcessorAwaitManager async = mock(AsyncProcessorAwaitManager.class);
    when(context.getAsyncProcessorAwaitManager()).thenReturn(async);

    processor.process(exchange);

    verify(message).setHeader(headerName, headerValue);
}
 
Example #20
Source File: AdviceWithWeaveTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:in").id("slowRoute")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        Thread.sleep(10000);
                        Message in = exchange.getIn();
                        in.setBody("Slow reply to: " + in.getBody());
                    }
                }).id("reallySlowProcessor")
                .to("mock:out");
        }
    };
}
 
Example #21
Source File: EMailSendCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private void beforeProducer(Exchange exchange) throws MessagingException, IOException {
    final Message in = exchange.getIn();
    final EMailMessageModel mail = in.getBody(EMailMessageModel.class);
    if (mail == null) {
        return;
    }

    in.setHeader(MAIL_FROM, updateMail(from, mail.getFrom()));
    in.setHeader(MAIL_TO, updateMail(to, mail.getTo()));
    in.setHeader(MAIL_CC, updateMail(cc, mail.getCc()));
    in.setHeader(MAIL_BCC, updateMail(bcc, mail.getBcc()));
    in.setHeader(MAIL_SUBJECT, updateMail(subject, mail.getSubject()));

    Object content = updateMail(text, mail.getContent());
    in.setBody(content);
    setContentType(content, in);
}
 
Example #22
Source File: MyProcessor.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    String result = "Unknown language";

    final Message inMessage = exchange.getIn();
    final String body = inMessage.getBody(String.class);
    final String language = inMessage.getHeader("language", String.class);

    if ("en".equals(language)) {
        result = "Hello " + body;
    } else if ("fr".equals(language)) {
        result = "Bonjour " + body;
    }

    inMessage.setBody(result);
}
 
Example #23
Source File: ZipFileSplitterTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {

    List<IngestionFileEntry> files = new ArrayList<IngestionFileEntry>();
    files.add(new IngestionFileEntry("/", null, null, "test1.xml", null));
    files.add(new IngestionFileEntry("/", null, null, "test2.xml", null));

    Exchange exchange = Mockito.mock(Exchange.class);
    Message message = Mockito.mock(Message.class);
    Mockito.when(exchange.getIn()).thenReturn(message);
    Mockito.when(message.getHeader("jobId")).thenReturn(jobId);
    Mockito.when(message.getHeader("BatchJobId")).thenReturn(jobId);
    Mockito.when(message.getBody(WorkNote.class)).thenReturn(controlFileWorkNote);
    Mockito.when(controlFileWorkNote.getBatchJobId()).thenReturn(jobId);

    Mockito.doCallRealMethod().when(zipFileSplitter).splitZipFile(exchange);
    Mockito.doCallRealMethod().when(zipFileSplitter).setBatchJobDAO(Matchers.any(BatchJobDAO.class));
    Mockito.when(batchJobDAO.createFileLatch(Matchers.anyString(), Matchers.any(List.class))).thenReturn(true);
    Mockito.when(batchJobDAO.findBatchJobById(Matchers.anyString())).thenReturn(newBatchJob);
    Mockito.when(newBatchJob.getFiles()).thenReturn(files);

    zipFileSplitter.setBatchJobDAO(batchJobDAO);
    List<FileEntryWorkNote> res = zipFileSplitter.splitZipFile(exchange);


    Assert.assertEquals(res.size(), 2);
}
 
Example #24
Source File: SendDirectMessageCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ComponentProxyComponent component, Map<String, Object> options) {
    component.setBeforeProducer(exchange -> {
        String defaultMessage = ConnectorOptions.extractOption(options, "message");
        final Message in = exchange.getIn();
        final DirectMessageText message = in.getBody(DirectMessageText.class);
        // only set the default message if there is no message in the body
        if (message == null || message.getMessage() == null) {
            in.setBody(defaultMessage);
        } else {
            in.setBody(message.getMessage());
        }
    });
}
 
Example #25
Source File: RequestPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
void convertAsXml(final Message in) {
    final String body = bodyAsString(in);
    if (body == null) {
        return;
    }

    try {
        final XMLStreamReader bodyReader = XML_INPUT_FACTORY.createXMLStreamReader(new StringReader(body));

        final XMLStreamReader eventReader = XML_INPUT_FACTORY.createFilteredReader(bodyReader, new XmlPayloadProcessor(in.getHeaders()));

        final Source source = new StAXSource(eventReader);
        final ByteArrayOutputStream out = new ByteArrayOutputStream(body.length());
        final Result result = new StreamResult(out);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);

        in.setBody(new String(out.toByteArray(), StandardCharsets.UTF_8));
    } catch (XMLStreamException | TransformerFactoryConfigurationError | TransformerException e) {
        LOG.warn("Unable to parse payload, continuing without conversion", e);

        return;
    }

}
 
Example #26
Source File: GoogleCalendarGetEventCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void afterProducer(Exchange exchange) {

        final Message in = exchange.getIn();
        final Event event = exchange.getIn().getBody(Event.class);
        final GoogleCalendarEventModel model = GoogleCalendarEventModel.newFrom(event);

        in.setBody(model);
    }
 
Example #27
Source File: KuduCreateTableCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void afterProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    final KuduTable table = exchange.getIn().getBody(KuduTable.class);

    KuduTable model = new KuduTable();
    if (ObjectHelper.isNotEmpty(table)) {
        model.setName(table.getName());
        model.setSchema(table.getSchema());
        model.setBuilder(table.getBuilder());
    }

    in.setBody(model);
}
 
Example #28
Source File: MongoCustomizersUtil.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Used to convert any result MongoOperation (either {@link DeleteResult} or {@link UpdateResult}
 * to a {@link Long}
 */
static void convertMongoResultToLong(Exchange exchange) {
    Message in = exchange.getIn();
    if (in.getBody() instanceof DeleteResult) {
        Long docsDeleted = in.getBody(DeleteResult.class).getDeletedCount();
        in.setBody(docsDeleted);
    } else if (in.getBody() instanceof UpdateResult) {
        Long docsUpdated = in.getBody(UpdateResult.class).getModifiedCount();
        in.setBody(docsUpdated);
    } else {
        LOGGER.warn("Impossible to convert the body, type was {}", in.getBody() == null ? null : in.getBody().getClass());
    }
}
 
Example #29
Source File: Expression.java    From mdw with Apache License 2.0 5 votes vote down vote up
public String substitute(Message message) {
    StringBuffer substituted = new StringBuffer(input.length());
    Matcher matcher = tokenPattern.matcher(input);
    int index = 0;
    while (matcher.find()) {
        String match = matcher.group();
        substituted.append(input.substring(index, matcher.start()));
        Object value = evaluateXPath(match.substring(2, match.length() - 1), message);
        if (value != null)
            substituted.append(value);
        index = matcher.end();
    }
    substituted.append(input.substring(index));
    return substituted.toString();
}
 
Example #30
Source File: GoogleSheetsUpdateSpreadsheetCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void afterProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    final BatchUpdateSpreadsheetResponse batchUpdateResponse = in.getBody(BatchUpdateSpreadsheetResponse.class);

    GoogleSpreadsheet model = new GoogleSpreadsheet();
    model.setSpreadsheetId(batchUpdateResponse.getSpreadsheetId());

    if (ObjectHelper.isNotEmpty(batchUpdateResponse.getUpdatedSpreadsheet())) {
        SpreadsheetProperties spreadsheetProperties = batchUpdateResponse.getUpdatedSpreadsheet().getProperties();
        if (ObjectHelper.isNotEmpty(spreadsheetProperties)) {
            model.setTitle(spreadsheetProperties.getTitle());
            model.setUrl(batchUpdateResponse.getUpdatedSpreadsheet().getSpreadsheetUrl());
            model.setTimeZone(spreadsheetProperties.getTimeZone());
            model.setLocale(spreadsheetProperties.getLocale());
        }

        List<GoogleSheet> sheets = new ArrayList<>();
        if (ObjectHelper.isNotEmpty(batchUpdateResponse.getUpdatedSpreadsheet().getSheets())) {
            batchUpdateResponse.getUpdatedSpreadsheet().getSheets().stream()
                    .map(Sheet::getProperties)
                    .forEach(props -> {
                        GoogleSheet sheet = new GoogleSheet();
                        sheet.setSheetId(props.getSheetId());
                        sheet.setIndex(props.getIndex());
                        sheet.setTitle(props.getTitle());
                        sheets.add(sheet);
                    });

        }
        model.setSheets(sheets);
    }

    in.setBody(model);
}