From 265095075b84d581af2d173760d5c2fd534edc82 Mon Sep 17 00:00:00 2001
From: Siddharth Shehria <83392744+sidshehria@users.noreply.github.com>
Date: Wed, 3 Jul 2024 08:43:16 +0530
Subject: [PATCH 1/2] Update Post.java
Following Changes made to optimize it:
1)Use CloseableHttpClient and CloseableHttpResponse:
Updated to use the modern HttpClient from Apache HttpComponents.
Ensured resources are closed properly with try-with-resources.
2) Logging Improvements:
Enhanced logging statements for better clarity.
3)Charset Handling:
Used StandardCharsets.ISO_8859_1 instead of the string literal "ISO-8859-1".
4)Removed Redundant Loop:
The loop running only once is unnecessary, hence removed for clarity.
---
.../demo/java/com/cloudhopper/sxmp/Post.java | 115 ++++++------------
1 file changed, 36 insertions(+), 79 deletions(-)
diff --git a/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java b/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java
index 174e46a8..0c725471 100644
--- a/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java
+++ b/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java
@@ -1,48 +1,28 @@
package com.cloudhopper.sxmp;
-/*
- * #%L
- * ch-sxmp
- * %%
- * Copyright (C) 2012 - 2013 Cloudhopper by Twitter
- * %%
- * Licensed 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.
- * #L%
- */
-
import com.cloudhopper.commons.util.HexUtil;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.ResponseHandler;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.BasicResponseHandler;
-import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.nio.charset.StandardCharsets;
/**
- *
- * @author joelauer
+ * Post class to send a HTTP POST request.
+ * Optimized for better resource management and performance.
*/
public class Post {
private static final Logger logger = LoggerFactory.getLogger(Post.class);
- static public void main(String[] args) throws Exception {
-
+ public static void main(String[] args) {
+ // Message to be sent
String message = "Test With @ Character";
- //String message = "Tell Twitter what you're doing!\nStd msg charges apply. Send 'stop' to quit.\nVisit twitter.com or email help@twitter.com for help.";
- StringBuilder string0 = new StringBuilder(200)
+ // Build XML payload with message encoded in ISO-8859-1
+ String xmlPayload = new StringBuilder(200)
.append("\n")
.append("\n")
.append(" \n")
@@ -51,66 +31,43 @@ static public void main(String[] args) throws Exception {
.append(" true\n")
.append(" 40404\n")
.append(" +13135551234\n")
- .append(" " + HexUtil.toHexString(message.getBytes("ISO-8859-1")) + "\n")
+ .append(" " + HexUtil.toHexString(message.getBytes(StandardCharsets.ISO_8859_1)) + "\n")
.append(" \n")
.append("\n")
- .append("");
+ .toString();
- /**
- //.append("")
- //.append("")
- .append("\n")
- .append(" \n")
- .append(" \n")
- .append(" \n")
- .append(" \n")
- //.append(" +13135551212\n")
- .append(" +13135551200\n")
- .append(" \n")
- .append(" \n")
- .append("")
- .append("");
- */
-
- // Get target URL
+ // Target URL for the POST request
String strURL = "http://localhost:9080/api/sxmp/1.0";
- // Get file to be posted
- //String strXMLFilename = args[1];
- //File input = new File(strXMLFilename);
-
- HttpClient client = new DefaultHttpClient();
-
- long totalStart = System.currentTimeMillis();
+ // Use try-with-resources to ensure HttpClient is closed properly
+ try (CloseableHttpClient client = HttpClients.createDefault()) {
+ long totalStart = System.currentTimeMillis(); // Track total start time
- for (int i = 0; i < 1; i++) {
- long start = System.currentTimeMillis();
+ // Create and configure HttpPost object
+ HttpPost post = new HttpPost(strURL);
+ StringEntity entity = new StringEntity(xmlPayload, StandardCharsets.ISO_8859_1);
+ entity.setContentType("text/xml; charset=ISO-8859-1");
+ post.setEntity(entity);
- // execute request
- try {
- HttpPost post = new HttpPost(strURL);
+ long start = System.currentTimeMillis(); // Track request start time
- StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1");
- entity.setContentType("text/xml; charset=\"ISO-8859-1\"");
- post.setEntity(entity);
-
- ResponseHandler responseHandler = new BasicResponseHandler();
-
- String responseBody = client.execute(post, responseHandler);
- long stop = System.currentTimeMillis();
+ // Execute HTTP POST request and measure the response time
+ try (CloseableHttpResponse response = client.execute(post)) {
+ long stop = System.currentTimeMillis(); // Track request stop time
+ // Log response details
logger.debug("----------------------------------------");
- logger.debug("Response took " + (stop-start) + " ms");
- logger.debug(responseBody);
+ logger.debug("Response took " + (stop - start) + " ms");
+ logger.debug("Response: {}", response.getEntity().getContent().toString());
logger.debug("----------------------------------------");
- } finally {
- // do nothing
}
- }
- long totalEnd = System.currentTimeMillis();
-
- logger.debug("Response took " + (totalEnd-totalStart) + " ms");
+ long totalEnd = System.currentTimeMillis(); // Track total end time
+ logger.debug("Total response time: " + (totalEnd - totalStart) + " ms");
+ } catch (Exception e) {
+ // Log any exceptions that occur during the request
+ logger.error("Error occurred while sending HTTP POST request", e);
+ }
}
}
From d12d29e5a978f86ba4c76d7eae4850b96c046915 Mon Sep 17 00:00:00 2001
From: Siddharth Shehria <83392744+sidshehria@users.noreply.github.com>
Date: Wed, 3 Jul 2024 08:46:21 +0530
Subject: [PATCH 2/2] Update Post.java
Changes Made to optimize the Code:
1) Use CloseableHttpClient and CloseableHttpResponse:
Updated to use the modern HttpClient from Apache HttpComponents.
Ensured resources are closed properly with try-with-resources.
2) Logging Improvements:
Enhanced logging statements for better clarity.
3) Charset Handling:
Used StandardCharsets.ISO_8859_1 instead of the string literal "ISO-8859-1".
4) Removed Redundant Loop:
The loop running only once is unnecessary, hence removed for clarity.
---
.../demo/java/com/cloudhopper/sxmp/Post.java | 20 +++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java b/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java
index 0c725471..fbcac463 100644
--- a/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java
+++ b/ch-sxmp/src/demo/java/com/cloudhopper/sxmp/Post.java
@@ -1,5 +1,25 @@
package com.cloudhopper.sxmp;
+/*
+ * #%L
+ * ch-sxmp
+ * %%
+ * Copyright (C) 2012 - 2013 Cloudhopper by Twitter
+ * %%
+ * Licensed 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.
+ * #L%
+ */
+
import com.cloudhopper.commons.util.HexUtil;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;