//The below code will help you to send the JSON data/File to AWS S3 Bucket from Liferay Portlet.
package com.portlet;
import com.constants.TestPortletKeys;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.model.Layout;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.service.LayoutLocalServiceUtil;
import com.liferay.portal.kernel.util.StringPool;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.osgi.service.component.annotations.Component;
/**
* @author Inthiyaz
*/
@Component(immediate = true, property = { "com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true", "javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp", "javax.portlet.name=" + TestPortletKeys.Test,
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user" }, service = Portlet.class)
public class TestPortlet extends MVCPortlet {
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
// TODO Auto-generated method stub
System.out.println("Render Method of a Test Portlet");
try {
// Creating sample JSON Data
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
for (Layout layout : LayoutLocalServiceUtil.getLayouts(-1, -1)) {
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("id", layout.getPlid());
jsonObject.put("title", layout.getName());
jsonArray.put(jsonObject);
}
System.out.println("JSON :" + jsonArray);
JSONObject jsonData = JSONFactoryUtil.createJSONObject();
// Client Id of AWS S3 bucket
jsonData.put("client_id", "1123231daasdfasdfsdf");
// Client Secret Key of AWS S3
jsonData.put("client_secret", "111111111111112222222222asdfdsf22223333333wsdfadsfawewrwerwerqwer");
//Give sample scope if you have any
jsonData.put("scope", "some_sample_scope");
//calling method to generate connection from AWS and pass jSON data
connectionGenerator(jsonData.toString(), jsonArray);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.render(renderRequest, renderResponse);
}
// Method to create connection and generate the token
public static void connectionGenerator(String jsonData, JSONArray jsonArray) throws IOException {
HttpClient client = HttpClients.createDefault();
//Provide AWS Authorize URL
String url = "http://123adfasdfasdexecute-api.com/v1/authorize";
StringEntity entity = new StringEntity(jsonData);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
String signedUrl = StringPool.BLANK;
try {
System.out.println("HTTPPSOT :-" + httpPost);
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseJSON = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = JSONFactoryUtil.createJSONObject(responseJSON);
String tokenObj = jsonObj.getString("payload").toString();
JSONObject token = JSONFactoryUtil.createJSONObject(tokenObj);
System.out.println("Token Object :" + tokenObj);
// Passing generated token and input JSON Array data
generatSignedURLfromPayload(token.get("token").toString(), jsonArray);
} else {
System.out.println( "Http Status is not Okay while generating token :" + response.getStatusLine().getStatusCode());
}
} catch (JSONException e) {
System.out.println("Exception in Client while generating token");
}
}
// Method to generate Signed URL from Payload by using a token
private static void generatSignedURLfromPayload(String token, JSONArray jsonArray) throws ClientProtocolException, IOException {
System.out.println("Getting Singed URL");
HttpClient client = HttpClients.createDefault();
// AWS S3 URL where we need to push the file with JSON DATA
String url = "http://123adfasdfasdexecute-api.com/v1/entity/upload-url?name=processdata";
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", token);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
String signedUrl = StringPool.BLANK;
try {
HttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseJSON = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = JSONFactoryUtil.createJSONObject(responseJSON);
JSONObject payLoad = JSONFactoryUtil.createJSONObject(jsonObj.getString("payload"));
signedUrl = payLoad.getString("url");
// By using Pay Load URL pusing jsondata
uploadFileContenttoAWSS3(signedUrl, jsonArray);
} else {
System.out.println("Http Status is not Okay while Signed URL :" + response.getStatusLine().getStatusCode());
}
} catch (JSONException e) {
System.out.println("Exception in Client in signed URL");
}
}
//Method to upload json data to AWS S3
public static void uploadFileContenttoAWSS3(String api, JSONArray jsonArray)
throws ClientProtocolException, IOException {
System.out.println(" Upload data to AWS S3");
URL url = new URL(api);
//used to form a connection
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-type", "plain/text");
//Used to write the data after connection
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonArray.toString());
out.close();
connection.getResponseCode();
System.out.println("HTTP response code: " + connection.getResponseCode());
}
}
package com.portlet;
import com.constants.TestPortletKeys;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.model.Layout;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.service.LayoutLocalServiceUtil;
import com.liferay.portal.kernel.util.StringPool;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.osgi.service.component.annotations.Component;
/**
* @author Inthiyaz
*/
@Component(immediate = true, property = { "com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true", "javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp", "javax.portlet.name=" + TestPortletKeys.Test,
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user" }, service = Portlet.class)
public class TestPortlet extends MVCPortlet {
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
// TODO Auto-generated method stub
System.out.println("Render Method of a Test Portlet");
try {
// Creating sample JSON Data
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
for (Layout layout : LayoutLocalServiceUtil.getLayouts(-1, -1)) {
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("id", layout.getPlid());
jsonObject.put("title", layout.getName());
jsonArray.put(jsonObject);
}
System.out.println("JSON :" + jsonArray);
JSONObject jsonData = JSONFactoryUtil.createJSONObject();
// Client Id of AWS S3 bucket
jsonData.put("client_id", "1123231daasdfasdfsdf");
// Client Secret Key of AWS S3
jsonData.put("client_secret", "111111111111112222222222asdfdsf22223333333wsdfadsfawewrwerwerqwer");
//Give sample scope if you have any
jsonData.put("scope", "some_sample_scope");
//calling method to generate connection from AWS and pass jSON data
connectionGenerator(jsonData.toString(), jsonArray);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.render(renderRequest, renderResponse);
}
// Method to create connection and generate the token
public static void connectionGenerator(String jsonData, JSONArray jsonArray) throws IOException {
HttpClient client = HttpClients.createDefault();
//Provide AWS Authorize URL
String url = "http://123adfasdfasdexecute-api.com/v1/authorize";
StringEntity entity = new StringEntity(jsonData);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
String signedUrl = StringPool.BLANK;
try {
System.out.println("HTTPPSOT :-" + httpPost);
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseJSON = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = JSONFactoryUtil.createJSONObject(responseJSON);
String tokenObj = jsonObj.getString("payload").toString();
JSONObject token = JSONFactoryUtil.createJSONObject(tokenObj);
System.out.println("Token Object :" + tokenObj);
// Passing generated token and input JSON Array data
generatSignedURLfromPayload(token.get("token").toString(), jsonArray);
} else {
System.out.println( "Http Status is not Okay while generating token :" + response.getStatusLine().getStatusCode());
}
} catch (JSONException e) {
System.out.println("Exception in Client while generating token");
}
}
// Method to generate Signed URL from Payload by using a token
private static void generatSignedURLfromPayload(String token, JSONArray jsonArray) throws ClientProtocolException, IOException {
System.out.println("Getting Singed URL");
HttpClient client = HttpClients.createDefault();
// AWS S3 URL where we need to push the file with JSON DATA
String url = "http://123adfasdfasdexecute-api.com/v1/entity/upload-url?name=processdata";
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", token);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
String signedUrl = StringPool.BLANK;
try {
HttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseJSON = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = JSONFactoryUtil.createJSONObject(responseJSON);
JSONObject payLoad = JSONFactoryUtil.createJSONObject(jsonObj.getString("payload"));
signedUrl = payLoad.getString("url");
// By using Pay Load URL pusing jsondata
uploadFileContenttoAWSS3(signedUrl, jsonArray);
} else {
System.out.println("Http Status is not Okay while Signed URL :" + response.getStatusLine().getStatusCode());
}
} catch (JSONException e) {
System.out.println("Exception in Client in signed URL");
}
}
//Method to upload json data to AWS S3
public static void uploadFileContenttoAWSS3(String api, JSONArray jsonArray)
throws ClientProtocolException, IOException {
System.out.println(" Upload data to AWS S3");
URL url = new URL(api);
//used to form a connection
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-type", "plain/text");
//Used to write the data after connection
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonArray.toString());
out.close();
connection.getResponseCode();
System.out.println("HTTP response code: " + connection.getResponseCode());
}
}