You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by ac...@apache.org on 2016/05/21 08:41:05 UTC
[2/5] camel git commit: CAMEL-9969: Added a component for Telegram
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/Update.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/Update.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/Update.java
new file mode 100644
index 0000000..01b0a99
--- /dev/null
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/Update.java
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.model;
+
+import java.io.Serializable;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Represents an update with reference to the previous state.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Update implements Serializable {
+
+ private static final long serialVersionUID = -4001092937174853655L;
+
+ @JsonProperty("update_id")
+ private Long updateId;
+
+ private IncomingMessage message;
+
+ public Update() {
+ }
+
+ public Long getUpdateId() {
+ return updateId;
+ }
+
+ public void setUpdateId(Long updateId) {
+ this.updateId = updateId;
+ }
+
+ public IncomingMessage getMessage() {
+ return message;
+ }
+
+ public void setMessage(IncomingMessage message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("Update{");
+ sb.append("updateId=").append(updateId);
+ sb.append(", message=").append(message);
+ sb.append('}');
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/UpdateResult.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/UpdateResult.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/UpdateResult.java
new file mode 100644
index 0000000..f9de8a4
--- /dev/null
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/UpdateResult.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.model;
+
+import java.io.Serializable;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Represents the result of a call to <i>getUpdates</i> REST service.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class UpdateResult implements Serializable {
+
+ private static final long serialVersionUID = -4560342931918215225L;
+
+ private boolean ok;
+
+ @JsonProperty("result")
+ private List<Update> updates;
+
+ public UpdateResult() {
+ }
+
+ public boolean isOk() {
+ return ok;
+ }
+
+ public void setOk(boolean ok) {
+ this.ok = ok;
+ }
+
+ public List<Update> getUpdates() {
+ return updates;
+ }
+
+ public void setUpdates(List<Update> updates) {
+ this.updates = updates;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("UpdateResult{");
+ sb.append("ok=").append(ok);
+ sb.append(", updates=").append(updates);
+ sb.append('}');
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/User.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/User.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/User.java
new file mode 100644
index 0000000..cdd3552
--- /dev/null
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/User.java
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.model;
+
+import java.io.Serializable;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * An user inside the Telegram network.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class User implements Serializable {
+
+ private static final long serialVersionUID = -6233453333504612269L;
+
+ private Long id;
+
+ @JsonProperty("first_name")
+ private String firstName;
+
+ @JsonProperty("last_name")
+ private String lastName;
+
+ private String username;
+
+ public User() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("User{");
+ sb.append("id=").append(id);
+ sb.append(", firstName='").append(firstName).append('\'');
+ sb.append(", lastName='").append(lastName).append('\'');
+ sb.append(", username='").append(username).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/RestBotAPI.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/RestBotAPI.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/RestBotAPI.java
new file mode 100644
index 0000000..559f3db
--- /dev/null
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/RestBotAPI.java
@@ -0,0 +1,83 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.service;
+
+import java.util.List;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.cxf.jaxrs.ext.multipart.Attachment;
+
+/**
+ * Describes the Telegram Bot APIs.
+ */
+@Path("/")
+public interface RestBotAPI {
+
+ String BOT_API_DEFAULT_URL = "https://api.telegram.org";
+
+ @GET
+ @Path("/bot{authorizationToken}/getUpdates")
+ @Produces(MediaType.APPLICATION_JSON)
+ UpdateResult getUpdates(
+ @PathParam("authorizationToken") String authorizationToken,
+ @QueryParam("offset") Long offset,
+ @QueryParam("limit") Integer limit,
+ @QueryParam("timeout") Integer timeoutSeconds);
+
+
+ @POST
+ @Path("/bot{authorizationToken}/sendMessage")
+ @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+ void sendMessage(
+ @PathParam("authorizationToken") String authorizationToken,
+ @FormParam("chat_id") String chatId,
+ @FormParam("text") String text,
+ @FormParam("parse_mode") String parseMode,
+ @FormParam("disable_web_page_preview") Boolean disableWebPagePreview,
+ @FormParam("disable_notification") Boolean disableNotification,
+ @FormParam("reply_to_message_id") Long replyToMessageId);
+
+
+ @POST
+ @Path("/bot{authorizationToken}/sendPhoto")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ void sendPhoto(@PathParam("authorizationToken") String authorizationToken, List<Attachment> attachments);
+
+
+ @POST
+ @Path("/bot{authorizationToken}/sendAudio")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ void sendAudio(@PathParam("authorizationToken") String authorizationToken, List<Attachment> attachments);
+
+ @POST
+ @Path("/bot{authorizationToken}/sendVideo")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ void sendVideo(@PathParam("authorizationToken") String authorizationToken, List<Attachment> attachments);
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/TelegramServiceRestBotAPIAdapter.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/TelegramServiceRestBotAPIAdapter.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/TelegramServiceRestBotAPIAdapter.java
new file mode 100644
index 0000000..9d14f05
--- /dev/null
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/TelegramServiceRestBotAPIAdapter.java
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.service;
+
+import java.io.ByteArrayInputStream;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
+import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
+
+import org.apache.camel.component.telegram.TelegramService;
+import org.apache.camel.component.telegram.model.OutgoingAudioMessage;
+import org.apache.camel.component.telegram.model.OutgoingMessage;
+import org.apache.camel.component.telegram.model.OutgoingPhotoMessage;
+import org.apache.camel.component.telegram.model.OutgoingTextMessage;
+import org.apache.camel.component.telegram.model.OutgoingVideoMessage;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.jaxrs.ext.multipart.Attachment;
+import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
+
+/**
+ * Adapts the {@code RestBotAPI} to the {@code TelegramService} interface.
+ */
+public class TelegramServiceRestBotAPIAdapter implements TelegramService {
+
+ private RestBotAPI api;
+
+ public TelegramServiceRestBotAPIAdapter() {
+ this.api = JAXRSClientFactory.create(RestBotAPI.BOT_API_DEFAULT_URL, RestBotAPI.class, Collections.singletonList(new JacksonJsonProvider()));
+ WebClient.getConfig(this.api).getHttpConduit().getClient().setAllowChunking(false);
+ }
+
+ @Override
+ public UpdateResult getUpdates(String authorizationToken, Long offset, Integer limit, Integer timeoutSeconds) {
+ return api.getUpdates(authorizationToken, offset, limit, timeoutSeconds);
+ }
+
+ @Override
+ public void sendMessage(String authorizationToken, OutgoingMessage message) {
+ if (message instanceof OutgoingTextMessage) {
+ this.sendMessage(authorizationToken, (OutgoingTextMessage) message);
+ } else if (message instanceof OutgoingPhotoMessage) {
+ this.sendMessage(authorizationToken, (OutgoingPhotoMessage) message);
+ } else if (message instanceof OutgoingAudioMessage) {
+ this.sendMessage(authorizationToken, (OutgoingAudioMessage) message);
+ } else if (message instanceof OutgoingVideoMessage) {
+ this.sendMessage(authorizationToken, (OutgoingVideoMessage) message);
+ } else {
+ throw new IllegalArgumentException("Unsupported message type " + (message != null ? message.getClass().getName() : null));
+ }
+ }
+
+
+ private void sendMessage(String authorizationToken, OutgoingTextMessage message) {
+ api.sendMessage(authorizationToken, message.getChatId(), message.getText(), message.getParseMode(), message.getDisableWebPagePreview(), message.getDisableNotification(), message
+ .getReplyToMessageId());
+ }
+
+
+ private void sendMessage(String authorizationToken, OutgoingPhotoMessage message) {
+ List<Attachment> parts = new LinkedList<>();
+
+ fillCommonMediaParts(parts, message);
+
+ parts.add(buildMediaPart("photo", message.getFilenameWithExtension(), message.getPhoto()));
+ if (message.getCaption() != null) {
+ parts.add(buildTextPart("caption", message.getCaption()));
+ }
+
+ api.sendPhoto(authorizationToken, parts);
+ }
+
+ private void sendMessage(String authorizationToken, OutgoingAudioMessage message) {
+ List<Attachment> parts = new LinkedList<>();
+
+ fillCommonMediaParts(parts, message);
+
+ parts.add(buildMediaPart("audio", message.getFilenameWithExtension(), message.getAudio()));
+ if (message.getTitle() != null) {
+ parts.add(buildTextPart("title", message.getTitle()));
+ }
+ if (message.getDurationSeconds() != null) {
+ parts.add(buildTextPart("duration", String.valueOf(message.getDurationSeconds())));
+ }
+ if (message.getPerformer() != null) {
+ parts.add(buildTextPart("performer", message.getPerformer()));
+ }
+
+ api.sendAudio(authorizationToken, parts);
+ }
+
+ private void sendMessage(String authorizationToken, OutgoingVideoMessage message) {
+ List<Attachment> parts = new LinkedList<>();
+
+ fillCommonMediaParts(parts, message);
+
+ parts.add(buildMediaPart("video", message.getFilenameWithExtension(), message.getVideo()));
+ if (message.getCaption() != null) {
+ parts.add(buildTextPart("caption", message.getCaption()));
+ }
+ if (message.getDurationSeconds() != null) {
+ parts.add(buildTextPart("duration", String.valueOf(message.getDurationSeconds())));
+ }
+ if (message.getWidth() != null) {
+ parts.add(buildTextPart("width", String.valueOf(message.getWidth())));
+ }
+ if (message.getHeight() != null) {
+ parts.add(buildTextPart("height", String.valueOf(message.getHeight())));
+ }
+
+ api.sendVideo(authorizationToken, parts);
+ }
+
+ private void fillCommonMediaParts(List<Attachment> parts, OutgoingMessage message) {
+ parts.add(buildTextPart("chat_id", message.getChatId()));
+
+ if (message.getReplyToMessageId() != null) {
+ parts.add(buildTextPart("reply_to_message_id", String.valueOf(message.getReplyToMessageId())));
+ }
+ if (message.getDisableNotification() != null) {
+ parts.add(buildTextPart("disable_notification", String.valueOf(message.getDisableNotification())));
+ }
+ }
+
+ private Attachment buildTextPart(String name, String value) {
+ MultivaluedMap m = new MultivaluedHashMap<>();
+ m.putSingle("Content-Type", "text/plain");
+ m.putSingle("Content-Disposition", "form-data; name=\"" + escapeMimeName(name) + "\"");
+
+ Attachment a = new Attachment(m, value);
+ return a;
+ }
+
+ private Attachment buildMediaPart(String name, String fileNameWithExtension, byte[] value) {
+ Attachment a = new Attachment(name, new ByteArrayInputStream(value),
+ new ContentDisposition("form-data; name=\"" + escapeMimeName(name) + "\"; filename=\"" + escapeMimeName(fileNameWithExtension) + "\""));
+ return a;
+ }
+
+ private String escapeMimeName(String name) {
+ return name.replace("\"", "");
+ }
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/util/TelegramConverter.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/util/TelegramConverter.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/util/TelegramConverter.java
new file mode 100644
index 0000000..f22659d
--- /dev/null
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/util/TelegramConverter.java
@@ -0,0 +1,158 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.util;
+
+import org.apache.camel.Converter;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.telegram.TelegramConstants;
+import org.apache.camel.component.telegram.TelegramMediaType;
+import org.apache.camel.component.telegram.model.IncomingMessage;
+import org.apache.camel.component.telegram.model.OutgoingAudioMessage;
+import org.apache.camel.component.telegram.model.OutgoingMessage;
+import org.apache.camel.component.telegram.model.OutgoingPhotoMessage;
+import org.apache.camel.component.telegram.model.OutgoingTextMessage;
+import org.apache.camel.component.telegram.model.OutgoingVideoMessage;
+import org.apache.camel.component.telegram.model.Update;
+
+/**
+ * Utilities for converting between Telegram APIs and standard java objects.
+ */
+@Converter
+public final class TelegramConverter {
+
+ private TelegramConverter() {
+ }
+
+ @Converter
+ public static String toString(Update update) {
+ return update != null ? toString(update.getMessage()) : null;
+ }
+
+ @Converter
+ public static String toString(IncomingMessage message) {
+ return message != null ? message.getText() : null;
+ }
+
+ @Converter
+ public static OutgoingMessage toOutgoingMessage(String message, Exchange exchange) {
+ if (message == null) {
+ // fail fast
+ return null;
+ }
+
+ Object typeObj = exchange.getIn().getHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE);
+ TelegramMediaType type;
+ if (typeObj instanceof String) {
+ type = TelegramMediaType.valueOf((String) typeObj);
+ } else {
+ type = (TelegramMediaType) typeObj;
+ }
+
+ // If the message is a string, it will be converted to a OutgoingTextMessage
+ if (type == null) {
+ type = TelegramMediaType.TEXT;
+ }
+
+ OutgoingMessage result;
+
+ switch (type) {
+ case TEXT: {
+ OutgoingTextMessage txt = new OutgoingTextMessage();
+ txt.setText(message);
+ result = txt;
+ break;
+ }
+ default: {
+ throw new IllegalArgumentException("Unsupported conversion from String to media type " + type);
+ }
+ }
+
+
+ return result;
+ }
+
+ @Converter
+ public static OutgoingMessage toOutgoingMessage(byte[] message, Exchange exchange) {
+ if (message == null) {
+ // fail fast
+ return null;
+ }
+
+ Object typeObj = exchange.getIn().getHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE);
+ TelegramMediaType type;
+ if (typeObj instanceof String) {
+ type = TelegramMediaType.valueOf((String) typeObj);
+ } else {
+ type = (TelegramMediaType) typeObj;
+ }
+
+ // If the message is a string, it will be converted to a OutgoingTextMessage
+ if (type == null) {
+ throw new IllegalStateException("Binary message require the header " + TelegramConstants.TELEGRAM_MEDIA_TYPE + " to be set with an appropriate org.apache.camel.component.telegram"
+ + ".TelegramMediaType object");
+ }
+
+ OutgoingMessage result;
+
+ switch (type) {
+ case PHOTO_JPG:
+ case PHOTO_PNG: {
+ OutgoingPhotoMessage img = new OutgoingPhotoMessage();
+ String caption = (String) exchange.getIn().getHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION);
+ String fileName = "photo." + type.getFileExtension();
+
+ img.setCaption(caption);
+ img.setFilenameWithExtension(fileName);
+ img.setPhoto(message);
+
+ result = img;
+ break;
+ }
+ case AUDIO: {
+ OutgoingAudioMessage audio = new OutgoingAudioMessage();
+ String title = (String) exchange.getIn().getHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION);
+ String fileName = "audio." + type.getFileExtension();
+
+ audio.setTitle(title);
+ audio.setFilenameWithExtension(fileName);
+ audio.setAudio(message);
+
+ result = audio;
+ break;
+ }
+ case VIDEO: {
+ OutgoingVideoMessage video = new OutgoingVideoMessage();
+ String title = (String) exchange.getIn().getHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION);
+ String fileName = "video." + type.getFileExtension();
+
+ video.setCaption(title);
+ video.setFilenameWithExtension(fileName);
+ video.setVideo(message);
+
+ result = video;
+ break;
+ }
+ default: {
+ throw new IllegalArgumentException("Unsupported conversion from byte[] to media type " + type);
+ }
+ }
+
+ return result;
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/TypeConverter
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/TypeConverter b/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/TypeConverter
new file mode 100644
index 0000000..dc95ea9
--- /dev/null
+++ b/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/TypeConverter
@@ -0,0 +1,18 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+org.apache.camel.component.telegram.util.TelegramConverter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/component/telegram
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/component/telegram b/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/component/telegram
new file mode 100644
index 0000000..aa45db0
--- /dev/null
+++ b/components/camel-telegram/src/main/resources/META-INF/services/org/apache/camel/component/telegram
@@ -0,0 +1,17 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+class=org.apache.camel.component.telegram.TelegramComponent
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramChatBotTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramChatBotTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramChatBotTest.java
new file mode 100644
index 0000000..e240f62
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramChatBotTest.java
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import java.util.List;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.telegram.model.OutgoingTextMessage;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.verification.Timeout;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+
+/**
+ * Tests a chain made of a consumer and a producer to create a direct chat-bot.
+ */
+public class TelegramChatBotTest extends TelegramTestSupport {
+
+ @Before
+ public void mockAPIs() {
+ TelegramService service = mockTelegramService();
+
+ UpdateResult request = getJSONResource("messages/updates-single.json", UpdateResult.class);
+ request.getUpdates().get(0).getMessage().setText("Hello World!");
+ request.getUpdates().get(0).getMessage().getChat().setId("my-chat-id");
+
+ UpdateResult request2 = getJSONResource("messages/updates-single.json", UpdateResult.class);
+ request2.getUpdates().get(0).getMessage().setText("intercept");
+ request2.getUpdates().get(0).getMessage().getChat().setId("my-chat-id");
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(service.getUpdates(any(), any(), any(), any()))
+ .thenReturn(request)
+ .thenReturn(request2)
+ .thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testChatBotResult() throws Exception {
+
+ TelegramService service = currentMockService();
+
+ ArgumentCaptor<OutgoingTextMessage> captor = ArgumentCaptor.forClass(OutgoingTextMessage.class);
+
+ verify(service, new Timeout(5000, times(2))).sendMessage(eq("mock-token"), captor.capture());
+
+ List<OutgoingTextMessage> msgs = captor.getAllValues();
+
+ assertCollectionSize(msgs, 2);
+ assertTrue(msgs.stream().anyMatch(m -> "echo from the bot: Hello World!".equals(m.getText())));
+ assertTrue(msgs.stream().anyMatch(m -> "echo from the bot: taken".equals(m.getText())));
+ assertTrue(msgs.stream().noneMatch(m -> m.getParseMode() != null));
+ }
+
+ /**
+ * This method simulates the first step of the chat-bot logic.
+ *
+ * @param exchange the current exchange originating from the telegram bot
+ */
+ public void chatBotProcess1(Exchange exchange) {
+ if (exchange.getIn().getBody(String.class).equals("intercept")) {
+ exchange.getIn().setBody("taken");
+ }
+ }
+
+ /**
+ * This method simulates the second step of the chat-bot logic.
+ *
+ * @param message the message coming from the telegram bot
+ * @return the reply, if any
+ */
+ public String chatBotProcess2(String message) {
+ return "echo from the bot: " + message;
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+
+ from("telegram:bots/mock-token")
+ .bean(TelegramChatBotTest.this, "chatBotProcess1")
+ .bean(TelegramChatBotTest.this, "chatBotProcess2")
+ .to("telegram:bots/mock-token");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConfigurationTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConfigurationTest.java
new file mode 100644
index 0000000..b2ddf5f
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConfigurationTest.java
@@ -0,0 +1,58 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Test;
+
+/**
+ * Tests that the configuration is loaded properly.
+ */
+public class TelegramConfigurationTest extends TelegramTestSupport {
+
+
+
+ @Test
+ public void testChatBotResult() throws Exception {
+ TelegramEndpoint endpoint = (TelegramEndpoint) context().getEndpoints().stream().filter(e -> e instanceof TelegramEndpoint).findAny().get();
+ TelegramConfiguration config = endpoint.getConfiguration();
+
+ assertEquals("bots", config.getType());
+ assertEquals("mock-token", config.getAuthorizationToken());
+ assertEquals("12345", config.getChatId());
+ assertEquals(Long.valueOf(2000L), config.getDelay());
+ assertEquals(Integer.valueOf(10), config.getTimeout());
+ assertEquals(Integer.valueOf(60), config.getLimit());
+ }
+
+
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+
+ from("direct:telegram")
+ .to("telegram:bots/mock-token?chatId=12345&delay=2000&timeout=10&limit=60");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerEmptyResponseTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerEmptyResponseTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerEmptyResponseTest.java
new file mode 100644
index 0000000..293930b
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerEmptyResponseTest.java
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test the empty responses.
+ */
+public class TelegramConsumerEmptyResponseTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(api.getUpdates(any(), any(), any(), any())).thenAnswer((i) -> defaultRes);
+ }
+
+ @Test(expected = AssertionError.class)
+ public void testBehaviourWithEmptyUpdates() throws Exception {
+ endpoint.setResultWaitTime(500L);
+ endpoint.expectedMinimumMessageCount(1);
+
+ endpoint.assertIsSatisfied();
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token").to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMappingTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMappingTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMappingTest.java
new file mode 100644
index 0000000..005de59
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMappingTest.java
@@ -0,0 +1,106 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import java.time.Instant;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.Chat;
+import org.apache.camel.component.telegram.model.IncomingMessage;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.model.User;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests the JSON mapping of the API updates.
+ */
+public class TelegramConsumerMappingTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult res1 = getJSONResource("messages/updates-single.json", UpdateResult.class);
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(api.getUpdates(any(), any(), any(), any())).thenReturn(res1).thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testMessageMapping() throws Exception {
+ endpoint.expectedMinimumMessageCount(1);
+ endpoint.expectedMessageCount(1);
+ endpoint.assertIsSatisfied();
+
+ Exchange ex = endpoint.getExchanges().get(0);
+ Message m = ex.getIn();
+
+ assertNotNull(m);
+
+ // checking headers
+ assertEquals("-45658", m.getHeader(TelegramConstants.TELEGRAM_CHAT_ID));
+
+ // checking body
+ assertNotNull(m.getBody());
+ assertTrue(m.getBody() instanceof IncomingMessage);
+ IncomingMessage body = (IncomingMessage) m.getBody();
+
+ assertEquals("a message", body.getText());
+ assertEquals(Long.valueOf(179L), body.getMessageId());
+ assertEquals(Instant.ofEpochSecond(1463436626L), body.getDate());
+
+ // checking from
+ User user = body.getFrom();
+ assertNotNull(user);
+ assertEquals("John", user.getFirstName());
+ assertEquals("Doe", user.getLastName());
+ assertEquals(Long.valueOf(1585844777), user.getId());
+
+ // checking chat
+ Chat chat = body.getChat();
+ assertNotNull(chat);
+ assertEquals("-45658", chat.getId());
+ assertEquals("A chat group", chat.getTitle());
+ assertEquals("group", chat.getType());
+
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token").to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaPhotoTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaPhotoTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaPhotoTest.java
new file mode 100644
index 0000000..303a55e
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaPhotoTest.java
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.IncomingMessage;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests the reception of messages without text having media content.
+ */
+public class TelegramConsumerMediaPhotoTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult res = getJSONResource("messages/updates-media.json", UpdateResult.class);
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(api.getUpdates(any(), any(), any(), any()))
+ .thenReturn(res)
+ .thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testReceptionOfTwoMessagesOneWithMedia() throws Exception {
+ endpoint.expectedMinimumMessageCount(2);
+ endpoint.assertIsSatisfied();
+
+ Exchange mediaExchange = endpoint.getExchanges().get(1);
+ IncomingMessage msg = mediaExchange.getIn().getBody(IncomingMessage.class);
+
+ assertNotNull(msg.getPhoto());
+ assertCollectionSize(msg.getPhoto(), 4);
+ assertEquals(4, msg.getPhoto().stream().map(ph -> ph.getFileId()).distinct().count());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token")
+ .to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaVideoTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaVideoTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaVideoTest.java
new file mode 100644
index 0000000..6368f7b
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMediaVideoTest.java
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.IncomingMessage;
+import org.apache.camel.component.telegram.model.IncomingPhotoSize;
+import org.apache.camel.component.telegram.model.IncomingVideo;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests the reception of messages without text having media content.
+ */
+public class TelegramConsumerMediaVideoTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult res = getJSONResource("messages/updates-media-video.json", UpdateResult.class);
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(api.getUpdates(any(), any(), any(), any()))
+ .thenReturn(res)
+ .thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testReceptionOfAMessageWithAVideo() throws Exception {
+ endpoint.expectedMinimumMessageCount(1);
+ endpoint.assertIsSatisfied();
+
+ Exchange mediaExchange = endpoint.getExchanges().get(0);
+ IncomingMessage msg = mediaExchange.getIn().getBody(IncomingMessage.class);
+
+ IncomingVideo video = msg.getVideo();
+
+ assertNotNull(video);
+ assertEquals(Integer.valueOf(2), video.getDurationSeconds());
+ assertEquals(Integer.valueOf(360), video.getHeight());
+ assertEquals(Integer.valueOf(640), video.getWidth());
+ assertEquals(Long.valueOf(299284), video.getFileSize());
+ assertEquals("BAADBAADAgADyzvwCC7_4AyvdAXXXX", video.getFileId());
+
+ IncomingPhotoSize thumb = video.getThumb();
+ assertNotNull(thumb);
+
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token")
+ .to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMultipleTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMultipleTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMultipleTest.java
new file mode 100644
index 0000000..e30767e
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerMultipleTest.java
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests a conversation having multiple updates.
+ */
+public class TelegramConsumerMultipleTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult res1 = getJSONResource("messages/updates-single.json", UpdateResult.class);
+ res1.getUpdates().get(0).getMessage().setText("message1");
+
+ UpdateResult res2 = getJSONResource("messages/updates-multiple.json", UpdateResult.class);
+ res2.getUpdates().get(0).getMessage().setText("message2");
+ res2.getUpdates().get(1).getMessage().setText("message3");
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(api.getUpdates(any(), any(), any(), any())).thenReturn(res1).thenReturn(res2).thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testReceptionOfThreeMessagesFromTwoUpdates() throws Exception {
+ endpoint.expectedMinimumMessageCount(3);
+ endpoint.expectedBodiesReceived("message1", "message2", "message3");
+
+ endpoint.assertIsSatisfied();
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token")
+ .convertBodyTo(String.class)
+ .to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerServiceErrorTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerServiceErrorTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerServiceErrorTest.java
new file mode 100644
index 0000000..605639d
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerServiceErrorTest.java
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test the recovery after service unavailability.
+ */
+public class TelegramConsumerServiceErrorTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult res1 = getJSONResource("messages/updates-single.json", UpdateResult.class);
+ res1.getUpdates().get(0).getMessage().setText("message1");
+
+ UpdateResult logicalErrorRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+ logicalErrorRes.setOk(false);
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+
+ when(api.getUpdates(any(), any(), any(), any()))
+ .thenThrow(new RuntimeException("Service exception"))
+ .thenReturn(logicalErrorRes)
+ .thenReturn(res1)
+ .thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testConsumerRecovery() throws Exception {
+ endpoint.expectedMinimumMessageCount(1);
+ endpoint.expectedBodiesReceived("message1");
+
+ endpoint.assertIsSatisfied();
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token")
+ .convertBodyTo(String.class)
+ .to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerSingleTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerSingleTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerSingleTest.java
new file mode 100644
index 0000000..61ba504
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramConsumerSingleTest.java
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.EndpointInject;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests a simple conversation.
+ */
+public class TelegramConsumerSingleTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "mock:telegram")
+ private MockEndpoint endpoint;
+
+ @Before
+ public void mockAPIs() {
+ TelegramService api = mockTelegramService();
+
+ UpdateResult res1 = getJSONResource("messages/updates-single.json", UpdateResult.class);
+ res1.getUpdates().get(0).getMessage().setText("message1");
+
+ UpdateResult res2 = getJSONResource("messages/updates-single.json", UpdateResult.class);
+ res2.getUpdates().get(0).getMessage().setText("message2");
+
+ UpdateResult defaultRes = getJSONResource("messages/updates-empty.json", UpdateResult.class);
+ when(api.getUpdates(any(), any(), any(), any())).thenReturn(res1).thenReturn(res2).thenAnswer((i) -> defaultRes);
+ }
+
+ @Test
+ public void testReceptionOfTwoMessages() throws Exception {
+ endpoint.expectedMinimumMessageCount(2);
+ endpoint.expectedBodiesReceived("message1", "message2");
+
+ endpoint.assertIsSatisfied();
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("telegram:bots/mock-token")
+ .convertBodyTo(String.class)
+ .to("mock:telegram");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerChatIdResolutionTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerChatIdResolutionTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerChatIdResolutionTest.java
new file mode 100644
index 0000000..1d0cfa4
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerChatIdResolutionTest.java
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.Endpoint;
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.telegram.model.OutgoingTextMessage;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import static org.mockito.Matchers.eq;
+
+/**
+ * Tests a producer route with a fixed destination.
+ */
+public class TelegramProducerChatIdResolutionTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "direct:telegram")
+ private Endpoint endpoint;
+
+ @Test
+ public void testRouteWithFixedChatId() throws Exception {
+
+ TelegramService api = mockTelegramService();
+
+ context().createProducerTemplate().sendBody(endpoint, "Hello");
+
+ ArgumentCaptor<OutgoingTextMessage> captor = ArgumentCaptor.forClass(OutgoingTextMessage.class);
+
+ Mockito.verify(api).sendMessage(eq("mock-token"), captor.capture());
+ assertEquals("my-id", captor.getValue().getChatId());
+ assertEquals("Hello", captor.getValue().getText());
+ assertNull(captor.getValue().getParseMode());
+ }
+
+ @Test
+ public void testRouteWithOverridenChatId() throws Exception {
+
+ TelegramService api = mockTelegramService();
+
+ Exchange exchange = endpoint.createExchange();
+ exchange.getIn().setBody("Hello 2");
+ exchange.getIn().setHeader(TelegramConstants.TELEGRAM_CHAT_ID, "my-second-id");
+
+ context().createProducerTemplate().send(endpoint, exchange);
+
+ ArgumentCaptor<OutgoingTextMessage> captor = ArgumentCaptor.forClass(OutgoingTextMessage.class);
+
+ Mockito.verify(api).sendMessage(eq("mock-token"), captor.capture());
+ assertEquals("my-second-id", captor.getValue().getChatId());
+ assertEquals("Hello 2", captor.getValue().getText());
+ assertNull(captor.getValue().getParseMode());
+
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("direct:telegram").to("telegram:bots/mock-token?chatId=my-id");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerMediaTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerMediaTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerMediaTest.java
new file mode 100644
index 0000000..8831ea4
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramProducerMediaTest.java
@@ -0,0 +1,141 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram;
+
+import org.apache.camel.Endpoint;
+import org.apache.camel.EndpointInject;
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.telegram.model.OutgoingAudioMessage;
+import org.apache.camel.component.telegram.model.OutgoingPhotoMessage;
+import org.apache.camel.component.telegram.model.OutgoingVideoMessage;
+import org.apache.camel.component.telegram.util.TelegramTestSupport;
+import org.apache.camel.component.telegram.util.TelegramTestUtil;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import static org.mockito.Matchers.eq;
+
+/**
+ * Tests a producer that sends media information.
+ */
+public class TelegramProducerMediaTest extends TelegramTestSupport {
+
+ @EndpointInject(uri = "direct:telegram")
+ private Endpoint endpoint;
+
+ @Test
+ public void testRouteWithPngImage() throws Exception {
+
+ TelegramService service = mockTelegramService();
+
+ Exchange ex = endpoint.createExchange();
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION, "Photo");
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE, TelegramMediaType.PHOTO_PNG.name());
+ byte[] image = TelegramTestUtil.createSampleImage("PNG");
+ ex.getIn().setBody(image);
+
+ context().createProducerTemplate().send(endpoint, ex);
+
+ ArgumentCaptor<OutgoingPhotoMessage> captor = ArgumentCaptor.forClass(OutgoingPhotoMessage.class);
+
+ Mockito.verify(service).sendMessage(eq("mock-token"), captor.capture());
+ assertEquals("my-id", captor.getValue().getChatId());
+ assertEquals(image, captor.getValue().getPhoto());
+ assertEquals("photo.png", captor.getValue().getFilenameWithExtension());
+ assertEquals("Photo", captor.getValue().getCaption());
+ }
+
+ @Test
+ public void testRouteWithJpgImage() throws Exception {
+
+ TelegramService service = mockTelegramService();
+
+ Exchange ex = endpoint.createExchange();
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION, "Photo");
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE, TelegramMediaType.PHOTO_JPG); // without using .name()
+ byte[] image = TelegramTestUtil.createSampleImage("JPG");
+ ex.getIn().setBody(image);
+
+ context().createProducerTemplate().send(endpoint, ex);
+
+ ArgumentCaptor<OutgoingPhotoMessage> captor = ArgumentCaptor.forClass(OutgoingPhotoMessage.class);
+
+ Mockito.verify(service).sendMessage(eq("mock-token"), captor.capture());
+ assertEquals("my-id", captor.getValue().getChatId());
+ assertEquals(image, captor.getValue().getPhoto());
+ assertEquals("photo.jpg", captor.getValue().getFilenameWithExtension());
+ assertEquals("Photo", captor.getValue().getCaption());
+ }
+
+ @Test
+ public void testRouteWithAudio() throws Exception {
+
+ TelegramService service = mockTelegramService();
+
+ Exchange ex = endpoint.createExchange();
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION, "Audio");
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE, TelegramMediaType.AUDIO.name());
+ byte[] audio = TelegramTestUtil.createSampleAudio();
+ ex.getIn().setBody(audio);
+
+ context().createProducerTemplate().send(endpoint, ex);
+
+ ArgumentCaptor<OutgoingAudioMessage> captor = ArgumentCaptor.forClass(OutgoingAudioMessage.class);
+
+ Mockito.verify(service).sendMessage(eq("mock-token"), captor.capture());
+ assertEquals("my-id", captor.getValue().getChatId());
+ assertEquals(audio, captor.getValue().getAudio());
+ assertEquals("audio.mp3", captor.getValue().getFilenameWithExtension());
+ assertEquals("Audio", captor.getValue().getTitle());
+ }
+
+ @Test
+ public void testRouteWithVideo() throws Exception {
+
+ TelegramService service = mockTelegramService();
+
+ Exchange ex = endpoint.createExchange();
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TITLE_CAPTION, "Video");
+ ex.getIn().setHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE, TelegramMediaType.VIDEO.name());
+ byte[] video = TelegramTestUtil.createSampleVideo();
+ ex.getIn().setBody(video);
+
+ context().createProducerTemplate().send(endpoint, ex);
+
+ ArgumentCaptor<OutgoingVideoMessage> captor = ArgumentCaptor.forClass(OutgoingVideoMessage.class);
+
+ Mockito.verify(service).sendMessage(eq("mock-token"), captor.capture());
+ assertEquals("my-id", captor.getValue().getChatId());
+ assertEquals(video, captor.getValue().getVideo());
+ assertEquals("video.mp4", captor.getValue().getFilenameWithExtension());
+ assertEquals("Video", captor.getValue().getCaption());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("direct:telegram").to("telegram:bots/mock-token?chatId=my-id");
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/integration/TelegramServiceTest.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/integration/TelegramServiceTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/integration/TelegramServiceTest.java
new file mode 100644
index 0000000..e1721d7
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/integration/TelegramServiceTest.java
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.integration;
+
+import java.io.IOException;
+
+import org.apache.camel.component.telegram.TelegramService;
+import org.apache.camel.component.telegram.TelegramServiceProvider;
+import org.apache.camel.component.telegram.model.OutgoingAudioMessage;
+import org.apache.camel.component.telegram.model.OutgoingPhotoMessage;
+import org.apache.camel.component.telegram.model.OutgoingTextMessage;
+import org.apache.camel.component.telegram.model.OutgoingVideoMessage;
+import org.apache.camel.component.telegram.model.UpdateResult;
+import org.apache.camel.component.telegram.util.TelegramTestUtil;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Tests if the BotAPI are working correctly.
+ */
+public class TelegramServiceTest {
+
+ private static String authorizationToken;
+
+ private static String chatId;
+
+ @BeforeClass
+ public static void init() {
+ authorizationToken = System.getenv("TELEGRAM_AUTHORIZATION_TOKEN");
+ chatId = System.getenv("TELEGRAM_CHAT_ID");
+ }
+
+ @Test
+ public void testGetUpdates() {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ UpdateResult res = service.getUpdates(authorizationToken, null, null, null);
+
+ Assert.assertNotNull(res);
+ Assert.assertTrue(res.isOk());
+ }
+
+ @Test
+ public void testSendMessage() {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ OutgoingTextMessage msg = new OutgoingTextMessage();
+ msg.setChatId(chatId);
+ msg.setText("This is an auto-generated message from the Bot");
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendFull() {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ OutgoingTextMessage msg = new OutgoingTextMessage();
+ msg.setChatId(chatId);
+ msg.setText("This is an *auto-generated* message from the Bot");
+ msg.setDisableWebPagePreview(true);
+ msg.setParseMode("Markdown");
+ msg.setDisableNotification(false);
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendPhoto() throws IOException {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ byte[] image = TelegramTestUtil.createSampleImage("PNG");
+
+ OutgoingPhotoMessage msg = new OutgoingPhotoMessage();
+ msg.setPhoto(image);
+ msg.setChatId(chatId);
+ msg.setFilenameWithExtension("file.png");
+
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendPhotoFull() throws IOException {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ byte[] image = TelegramTestUtil.createSampleImage("PNG");
+
+ OutgoingPhotoMessage msg = new OutgoingPhotoMessage();
+ msg.setPhoto(image);
+ msg.setChatId(chatId);
+ msg.setFilenameWithExtension("file.png");
+ msg.setCaption("Photo");
+ msg.setDisableNotification(false);
+
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendAudio() throws IOException {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ byte[] audio = TelegramTestUtil.createSampleAudio();
+
+ OutgoingAudioMessage msg = new OutgoingAudioMessage();
+ msg.setAudio(audio);
+ msg.setChatId(chatId);
+ msg.setFilenameWithExtension("audio.mp3");
+
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendAudioFull() throws IOException {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ byte[] audio = TelegramTestUtil.createSampleAudio();
+
+ OutgoingAudioMessage msg = new OutgoingAudioMessage();
+ msg.setAudio(audio);
+ msg.setChatId(chatId);
+ msg.setFilenameWithExtension("audio.mp3");
+ msg.setTitle("Audio");
+ msg.setDurationSeconds(5);
+ msg.setPerformer("Myself");
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendVideo() throws IOException {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ byte[] video = TelegramTestUtil.createSampleVideo();
+
+ OutgoingVideoMessage msg = new OutgoingVideoMessage();
+ msg.setVideo(video);
+ msg.setChatId(chatId);
+ msg.setFilenameWithExtension("video.mp4");
+
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+ @Test
+ public void testSendVideoFull() throws IOException {
+ TelegramService service = TelegramServiceProvider.get().getService();
+
+ byte[] video = TelegramTestUtil.createSampleVideo();
+
+ OutgoingVideoMessage msg = new OutgoingVideoMessage();
+ msg.setVideo(video);
+ msg.setChatId(chatId);
+ msg.setFilenameWithExtension("video.mp4");
+ msg.setDurationSeconds(2);
+ msg.setCaption("A Video");
+ msg.setWidth(90);
+ msg.setHeight(50);
+
+ service.sendMessage(authorizationToken, msg);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestSupport.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestSupport.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestSupport.java
new file mode 100644
index 0000000..23db461
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestSupport.java
@@ -0,0 +1,91 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.camel.component.telegram.TelegramService;
+import org.apache.camel.component.telegram.TelegramServiceProvider;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.After;
+import org.mockito.Mockito;
+
+/**
+ * A support test class for Telegram tests.
+ */
+public class TelegramTestSupport extends CamelTestSupport {
+
+ /**
+ * Indicates whether the {@code TelegramService} has been mocked during last test.
+ */
+ private boolean telegramServiceMocked;
+
+ /**
+ * Restores the status of {@code TelegramServiceProvider} if it has been mocked.
+ */
+ @After
+ public void tearDown() {
+ if (telegramServiceMocked) {
+ TelegramServiceProvider.get().restoreDefaultService();
+ this.telegramServiceMocked = false;
+ }
+ }
+
+ /**
+ * Setup an alternative mock {@code TelegramService} in the {@code TelegramServiceProvider} and return it.
+ *
+ * @return the mock service
+ */
+ public TelegramService mockTelegramService() {
+ TelegramService mockService = Mockito.mock(TelegramService.class);
+ TelegramServiceProvider.get().setAlternativeService(mockService);
+ this.telegramServiceMocked = true;
+
+ return mockService;
+ }
+
+ /**
+ * Retrieves the currently mocked {@code TelegramService}.
+ *
+ * @return the current mock of the telegram service
+ */
+ public TelegramService currentMockService() {
+ return TelegramServiceProvider.get().getAlternativeService();
+ }
+
+ /**
+ * Retrieves a response from a JSON file on classpath.
+ *
+ * @param fileName the filename in the classpath
+ * @param clazz the target class
+ * @param <T> the type of the returned object
+ * @return the object representation of the JSON file
+ */
+ public <T> T getJSONResource(String fileName, Class<T> clazz) {
+ ObjectMapper mapper = new ObjectMapper();
+ try (InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName)) {
+ T value = mapper.readValue(stream, clazz);
+ return value;
+ } catch (IOException e) {
+ throw new IllegalArgumentException("Unable to load file " + fileName, e);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestUtil.java
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestUtil.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestUtil.java
new file mode 100644
index 0000000..1457314
--- /dev/null
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/util/TelegramTestUtil.java
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.telegram.util;
+
+import java.io.IOException;
+
+import org.apache.cxf.helpers.IOUtils;
+
+/**
+ * Utility functions for telegram tests.
+ */
+public final class TelegramTestUtil {
+
+ private TelegramTestUtil() {
+ }
+
+ /**
+ * Creates a sample image.
+ *
+ * @param imageIOType the image-io code of the image type (eg. PNG, JPG)
+ * @return a sample image
+ * @throws IOException if anything goes wrong
+ */
+ public static byte[] createSampleImage(String imageIOType) throws IOException {
+ byte[] img;
+ if (imageIOType.equalsIgnoreCase("png")) {
+ img = IOUtils.readBytesFromStream(TelegramTestUtil.class.getResourceAsStream("/attachments/sample.png"));
+ } else if (imageIOType.equalsIgnoreCase("jpg")) {
+ img = IOUtils.readBytesFromStream(TelegramTestUtil.class.getResourceAsStream("/attachments/sample.jpg"));
+ } else {
+ throw new IllegalArgumentException("Unknown format " + imageIOType);
+ }
+ return img;
+ }
+
+
+ public static byte[] createSampleAudio() throws IOException {
+ byte[] audio = IOUtils.readBytesFromStream(TelegramTestUtil.class.getResourceAsStream("/attachments/sample.mp3"));
+ return audio;
+ }
+
+ public static byte[] createSampleVideo() throws IOException {
+ byte[] video = IOUtils.readBytesFromStream(TelegramTestUtil.class.getResourceAsStream("/attachments/sample.mp4"));
+ return video;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/resources/attachments/sample.jpg
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/resources/attachments/sample.jpg b/components/camel-telegram/src/test/resources/attachments/sample.jpg
new file mode 100644
index 0000000..30f2c24
Binary files /dev/null and b/components/camel-telegram/src/test/resources/attachments/sample.jpg differ
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/resources/attachments/sample.mp3
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/resources/attachments/sample.mp3 b/components/camel-telegram/src/test/resources/attachments/sample.mp3
new file mode 100644
index 0000000..3904c08
Binary files /dev/null and b/components/camel-telegram/src/test/resources/attachments/sample.mp3 differ
http://git-wip-us.apache.org/repos/asf/camel/blob/8dc984eb/components/camel-telegram/src/test/resources/attachments/sample.mp4
----------------------------------------------------------------------
diff --git a/components/camel-telegram/src/test/resources/attachments/sample.mp4 b/components/camel-telegram/src/test/resources/attachments/sample.mp4
new file mode 100644
index 0000000..467aa73
Binary files /dev/null and b/components/camel-telegram/src/test/resources/attachments/sample.mp4 differ