orpiske commented on code in PR #7683:
URL: https://github.com/apache/camel/pull/7683#discussion_r884936943


##########
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/service/WhatsAppServiceRestAPIJDKAdapter.java:
##########
@@ -0,0 +1,244 @@
+/*
+ * 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.whatsapp.service;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpRequest.BodyPublisher;
+import java.net.http.HttpRequest.BodyPublishers;
+import java.net.http.HttpRequest.Builder;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.CompletableFuture;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Exchange;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.component.whatsapp.WhatsAppService;
+import org.apache.camel.component.whatsapp.model.BaseMessage;
+import org.apache.camel.component.whatsapp.model.ContactMessageRequest;
+import org.apache.camel.component.whatsapp.model.InteractiveMessageRequest;
+import org.apache.camel.component.whatsapp.model.LocationMessageRequest;
+import org.apache.camel.component.whatsapp.model.MediaMessageRequest;
+import org.apache.camel.component.whatsapp.model.MessageResponse;
+import org.apache.camel.component.whatsapp.model.TemplateMessageRequest;
+import org.apache.camel.component.whatsapp.model.TextMessageRequest;
+import org.apache.camel.component.whatsapp.model.UploadMedia;
+import org.apache.camel.component.whatsapp.model.UploadMediaRequest;
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Java11 Http Client implementation
+ */
+public class WhatsAppServiceRestAPIJDKAdapter implements WhatsAppService {
+    private static final Logger LOG = 
LoggerFactory.getLogger(WhatsAppServiceRestAPIJDKAdapter.class);
+
+    private static final String MESSAGES_ENDPOINT = "/messages";
+    private static final String MEDIA_ENDPOINT = "/media";
+
+    private final Map<Class<?>, 
WhatsAppServiceRestAPIJDKAdapter.OutgoingMessageHandler<?>> handlers;
+    private final ObjectMapper mapper;
+    private final String baseUri;
+    private final String authorizationToken;
+
+    public WhatsAppServiceRestAPIJDKAdapter(HttpClient client, String baseUri, 
String apiVersion, String phoneNumberId,
+                                            String authorizationToken) {
+        this.baseUri = baseUri + "/" + apiVersion + "/" + phoneNumberId;
+        this.mapper = new ObjectMapper().registerModule(new JavaTimeModule());
+        this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+        this.authorizationToken = authorizationToken;
+
+        final Map<Class<?>, 
WhatsAppServiceRestAPIJDKAdapter.OutgoingMessageHandler<?>> m = new HashMap<>();
+        m.put(TextMessageRequest.class, new 
OutgoingPlainMessageHandler(client, mapper, this.baseUri + MESSAGES_ENDPOINT));
+        m.put(MediaMessageRequest.class, new 
OutgoingPlainMessageHandler(client, mapper, this.baseUri + MESSAGES_ENDPOINT));
+        m.put(LocationMessageRequest.class, new 
OutgoingPlainMessageHandler(client, mapper, this.baseUri + MESSAGES_ENDPOINT));
+        m.put(ContactMessageRequest.class, new 
OutgoingPlainMessageHandler(client, mapper, this.baseUri + MESSAGES_ENDPOINT));
+        m.put(InteractiveMessageRequest.class,
+                new OutgoingPlainMessageHandler(client, mapper, this.baseUri + 
MESSAGES_ENDPOINT));
+        m.put(UploadMediaRequest.class, new 
OutgoingMediaMessageHandler(client, mapper, this.baseUri + MEDIA_ENDPOINT));
+        m.put(TemplateMessageRequest.class, new 
OutgoingPlainMessageHandler(client, mapper, this.baseUri + MESSAGES_ENDPOINT));
+
+        this.handlers = m;
+    }
+
+    @Override
+    public void sendMessage(Exchange exchange, AsyncCallback callback, 
BaseMessage message) {
+        @SuppressWarnings("unchecked")
+        final 
WhatsAppServiceRestAPIJDKAdapter.OutgoingMessageHandler<BaseMessage> handler
+                = 
(WhatsAppServiceRestAPIJDKAdapter.OutgoingMessageHandler<BaseMessage>) handlers
+                        .get(message.getClass());
+
+        ObjectHelper.notNull(handler, "handler");
+
+        try {
+            handler.sendMessage(exchange, callback, message, 
authorizationToken);
+        } catch (IOException | InterruptedException e) {
+            throw new RuntimeCamelException("Could not send message " + 
message, e);
+        }
+    }
+
+    static class OutgoingMediaMessageHandler
+            extends 
WhatsAppServiceRestAPIJDKAdapter.OutgoingMessageHandler<UploadMediaRequest> {
+
+        public OutgoingMediaMessageHandler(HttpClient httpClient, ObjectMapper 
mapper, String uri,
+                                           Class<? extends MessageResponse> 
resultClass) {
+            super(httpClient, mapper, uri, null, resultClass);
+        }
+
+        public OutgoingMediaMessageHandler(HttpClient httpClient, ObjectMapper 
mapper, String uri) {
+            this(httpClient, mapper, uri, MessageResponse.class);
+        }
+
+        @Override
+        protected void addBody(Builder builder, UploadMediaRequest message) {
+            Map<Object, Object> formData = new HashMap<>();
+            formData.put("messaging_product", "whatsapp");
+            formData.put("file", message.getUploadMedia());
+
+            String boundary = new BigInteger(256, new Random()).toString();
+            try {
+                builder.POST(ofMimeMultipartData(formData, boundary));
+            } catch (IOException e) {
+                throw new RuntimeCamelException("Could not serialize " + 
message, e);
+            }
+
+            builder.header("content-type", "multipart/form-data; boundary=" + 
boundary);
+        }
+
+        public static BodyPublisher ofMimeMultipartData(Map<Object, Object> 
data, String boundary) throws IOException {
+            var byteArrays = new ArrayList<byte[]>();
+            byte[] separator = ("--" + boundary + "\r\nContent-Disposition: 
form-data; name=").getBytes(StandardCharsets.UTF_8);
+            for (Map.Entry<Object, Object> entry : data.entrySet()) {
+                byteArrays.add(separator);
+
+                if (entry.getValue() instanceof UploadMedia) {
+                    UploadMedia uploadMedia = (UploadMedia) entry.getValue();
+                    byteArrays.add(("\"" + entry.getKey() + "\"; filename=\"" 
+ uploadMedia.getFile().toPath().getFileName()
+                                    + "\"\r\nContent-Type: " + 
uploadMedia.getContentType()
+                                    + 
"\r\n\r\n").getBytes(StandardCharsets.UTF_8));
+                    
byteArrays.add(Files.readAllBytes(uploadMedia.getFile().toPath()));
+                    byteArrays.add("\r\n".getBytes(StandardCharsets.UTF_8));
+                } else {
+                    byteArrays.add(("\"" + entry.getKey() + "\"\r\n\r\n" + 
entry.getValue() + "\r\n")
+                            .getBytes(StandardCharsets.UTF_8));
+                }
+            }
+            byteArrays.add(("--" + boundary + 
"--\r\n").getBytes(StandardCharsets.UTF_8));
+            return BodyPublishers.ofByteArrays(byteArrays);

Review Comment:
   I'd avoid working directly with bytes here. Instead, I think you can make 
this code much simpler by using a `ByteBuffer` and then using it to generate 
the `byte[]` passed to the `BodyPublishers`.
   
   Among other things, it can also help avoiding the long chains of string 
concatenation (which could be problematic if this part of the code is in the 
hot path).
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@camel.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to