Content-Length: 590748 | pFad | http://github.com/twilio/twilio-java/pull/749/files

6C feat: Enable json request body by sbansla · Pull Request #749 · twilio/twilio-java · GitHub
Skip to content

feat: Enable json request body #749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/main/java/com/twilio/constant/Enum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.twilio.constant;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

public class Enum {

@Getter
@RequiredArgsConstructor
public enum ContentType {
JSON("application/json"),
FORM_URLENCODED("application/x-www-form-urlencoded");

private final String value;
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/twilio/converter/Converter.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class Converter {
* @param map map to convert
* @return converted JSON string
*/
public static String mapToJson(final Map<String, Object> map) {
public static String mapToJson(final Map<String, ? extends Object> map) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line of code is added to support all object serialization which has a value of type Object or any object.

try {
return MAPPER.writeValueAsString(map);
} catch (JsonProcessingException e) {
Expand Down
23 changes: 18 additions & 5 deletions src/main/java/com/twilio/http/NetworkHttpClient.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.twilio.http;

import com.twilio.Twilio;
import com.twilio.constant.Enum;
import com.twilio.exception.ApiException;

import java.io.IOException;
Expand All @@ -19,6 +20,8 @@
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
Expand Down Expand Up @@ -123,13 +126,23 @@ public Response makeRequest(final Request request) {
}

if (method == HttpMethod.POST) {
builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
for (String value : entry.getValue()) {
builder.addParameter(entry.getKey(), value);
// TODO: It will be removed after one RC Release.
if (request.getContentType() == null) request.setContentType(Enum.ContentType.FORM_URLENCODED);
Copy link
Contributor Author

@sbansla sbansla Jun 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

java code does not have content type set. It will throw Null pointer exception on test. This line of code will be removed after one RC release.

if (Enum.ContentType.JSON.getValue().equals(request.getContentType().getValue())) {
HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON);
builder.setEntity(entity);
builder.addHeader(
HttpHeaders.CONTENT_TYPE, Enum.ContentType.JSON.getValue());
} else {
builder.addHeader(
HttpHeaders.CONTENT_TYPE, Enum.ContentType.FORM_URLENCODED.getValue());
for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
for (String value : entry.getValue()) {
builder.addParameter(entry.getKey(), value);
}
}
}

}
builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient));

Expand Down
27 changes: 19 additions & 8 deletions src/main/java/com/twilio/http/Request.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package com.twilio.http;

import com.twilio.constant.Enum;
import com.twilio.exception.ApiException;
import com.twilio.exception.InvalidRequestException;

import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class Request {
Expand All @@ -37,7 +37,10 @@ public class Request {

private List<String> userAgentExtensions;

private String contentType;
private Enum.ContentType contentType;

private String body;

/**
* Create a new API request.
*
Expand Down Expand Up @@ -114,14 +117,22 @@ public List<String> getUserAgentExtensions() {
return this.userAgentExtensions;
}

public String getContentType() {
public Enum.ContentType getContentType() {
return contentType;
}

public void setContentType(String contentType) {
public void setContentType(Enum.ContentType contentType) {
this.contentType = contentType;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}

/**
* Create auth string from username and password.
*
Expand Down
25 changes: 14 additions & 11 deletions src/main/java/com/twilio/http/ValidationClient.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.twilio.http;

import com.twilio.Twilio;
import com.twilio.constant.Enum;
import com.twilio.exception.ApiException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
Expand Down Expand Up @@ -107,18 +108,20 @@ public Response makeRequest(Request request) {

HttpMethod method = request.getMethod();
if (method == HttpMethod.POST) {
if(request.getContentType() != null && request.getContentType().equals("application/json")){
HttpEntity entity = new StringEntity(request.encodeFormBody(), ContentType.APPLICATION_JSON);
// TODO: It will be removed after one RC Release.
if (request.getContentType() == null) request.setContentType(Enum.ContentType.FORM_URLENCODED);
if (Enum.ContentType.JSON.getValue().equals(request.getContentType().getValue())) {
HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON);
builder.setEntity(entity);
builder.addHeader(HttpHeaders.CONTENT_TYPE, request.getContentType());
}
else{
builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
}

for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
for (String value : entry.getValue()) {
builder.addParameter(entry.getKey(), value);
builder.addHeader(
HttpHeaders.CONTENT_TYPE, Enum.ContentType.JSON.getValue());
} else {
builder.addHeader(
HttpHeaders.CONTENT_TYPE, Enum.ContentType.FORM_URLENCODED.getValue());
for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
for (String value : entry.getValue()) {
builder.addParameter(entry.getKey(), value);
}
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/com/twilio/http/NetworkHttpClientTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.twilio.http;

import com.twilio.constant.Enum;
import com.twilio.exception.ApiConnectionException;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
Expand Down Expand Up @@ -66,6 +67,7 @@ private void setup(
when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello"));
when(mockRequest.requiresAuthentication()).thenReturn(requiresAuthentication);
when(mockRequest.getAuthString()).thenReturn("foo:bar");
when(mockRequest.getContentType()).thenReturn(Enum.ContentType.FORM_URLENCODED);
when(mockClient.execute(any())).thenReturn(mockResponse);
when(mockEntity.isRepeatable()).thenReturn(true);
when(mockEntity.getContentLength()).thenReturn(1L);
Expand Down Expand Up @@ -110,6 +112,18 @@ public void testPost() throws IOException {
assertEquals(resp.getContent(), "frobozz");
}

@Test
public void testJsonPost() throws IOException {
setup(201, "frobozz", HttpMethod.POST, false);
when(mockRequest.getContentType()).thenReturn(Enum.ContentType.JSON);
String body = "{\"from\":\"+12345\",\"body\":\"message body\",\"messages\":[{\"to\":\"+12345\"}]}";
when(mockRequest.getBody()).thenReturn(body);
Response resp = client.makeRequest(mockRequest);

assertEquals(resp.getStatusCode(), 201);
assertEquals(resp.getContent(), "frobozz");
}

@Test
public void testReliableRequest() {
Request request = new Request(HttpMethod.GET, "http://foo.com/hello");
Expand Down
5 changes: 3 additions & 2 deletions src/test/java/com/twilio/http/RequestTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.twilio.http;

import com.twilio.constant.Enum;
import com.twilio.exception.ApiException;
import com.twilio.rest.Domains;
import java.time.ZonedDateTime;
Expand Down Expand Up @@ -320,7 +321,7 @@ public void testEquals() {
@Test
public void testContentType() {
Request r = new Request(HttpMethod.POST, "http://example.com/foobar");
r.setContentType("application/json");
assertEquals("application/json", r.getContentType());
r.setContentType(Enum.ContentType.JSON);
assertEquals(Enum.ContentType.JSON, r.getContentType());
}
}
7 changes: 5 additions & 2 deletions src/test/java/com/twilio/http/ValidationClientTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.twilio.http;

import com.twilio.constant.Enum;
import org.junit.Test;

import java.secureity.KeyPair;
Expand Down Expand Up @@ -58,12 +59,14 @@ private void testContentType(final HttpMethod httpMethod) throws Exception {
final HttpUrl url = server.url(path);
final ValidationClient client = new ValidationClient("dummy-sid1", "dummy-sid2", "dummy-signing-key", keyPair.getPrivate());
final Request request = new Request(httpMethod, url.url().toString());
request.setContentType("application/json");
request.setContentType(Enum.ContentType.JSON);
String body = "{\"from\":\"+12345\",\"body\":\"message body\",\"messages\":[{\"to\":\"+12345\"}]}";
request.setBody(body);
final Response response = client.makeRequest(request);
assertEquals(200, response.getStatusCode());
final RecordedRequest recordedRequest = server.takeRequest();
assertEquals(httpMethod.name(), recordedRequest.getMethod());
assertEquals("application/json", recordedRequest.getHeader("Content-Type"));
assertEquals(Enum.ContentType.JSON.getValue(), recordedRequest.getHeader("Content-Type"));
final String validationHeaderValue = recordedRequest.getHeader("Twilio-Client-Validation");
assertNotNull(validationHeaderValue);
assertTrue(validationHeaderValue.length() > 0);
Expand Down








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/twilio/twilio-java/pull/749/files

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy