How to serialize a request? - java

I have the request below, if occurs an error at the service I'd like to save in a database the request serialized to send again in other moment.
URI uri = fromUri(config.getUri()).path("/myservice").build();
Client client = ClientProducer.get();
response = client
.target(uri)
.request()
.headers(obterCabecalhos())
.accept(MediaType.APPLICATION_JSON)
.post(Entity.json(myEntity));
if (response.getStatus() != OK.getStatusCode()) {
throw new TSEIntegracaoException();
// Here I'd like to serialize the request and save in a database
}

I do not think that is possible. How about creating a class that encapsulate your request data (uri, headers, payload) and serializing the instance of that class instead.
An example:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.DatatypeConverter;
public class DemoClient {
public static void main(String[] args) throws Exception {
Client client = ClientBuilder.newClient();
URI uri = URI.create("http://localhost:8000");
Map<String, List<Object>> headers = new HashMap<>();
headers.put(HttpHeaders.ACCEPT, Arrays.asList((Object) MediaType.APPLICATION_JSON));
PostRequestData requestData = new PostRequestData(uri, headers, new String("hello world"));
Response response = requestData.post(client);
if (response.getStatus() != Status.ACCEPTED.getStatusCode()) {
// let's serialise it into binary
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
objectOutputStream.writeObject(requestData);
// save bytestream or print it?
String bin = DatatypeConverter.printHexBinary(byteStream.toByteArray());
System.out.println(bin);
// let's replay the request
byte[] newBytes = DatatypeConverter.parseHexBinary(bin);
ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(newBytes));
PostRequestData newRequestdata = (PostRequestData) oin.readObject();
Response newResponse = newRequestdata.post(client);
if (newResponse.getStatus() != Status.ACCEPTED.getStatusCode()) {
System.out.println("give up!");
}
}
}
static class PostRequestData implements Serializable {
private static final long serialVersionUID = -5786067257552259115L;
final URI uri;
final Map<String, List<Object>> headers;
final Serializable entity;
public PostRequestData(URI uri, Map<String, List<Object>> headers, Serializable entity) {
this.uri = uri;
this.headers = headers;
this.entity = entity;
}
public Response post(Client client) {
MultivaluedHashMap<String, Object> multimap = new MultivaluedHashMap<String, Object>();
headers.forEach((k,v) -> multimap.put(k, v));
return client.target(uri)
.request()
.headers(multimap)
.post(Entity.text(entity));
}
}
}

Related

How to set up a multipart POST request in java 11?

I am trying to build a multipart HttpRequest using Java 11 as below. I am also trying to pass username
and password and later i might need a file also in the same request. However i keep getting 415 or 400 bad request errors.
The code is below.
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Client{
private HttpClient httpClient;
private HttpResponse httpResponse;
private String Response;
private Map<Object, Object> urlParameters;
public Client(String URL) {
httpClient=BuildClient(URL);
urlParameters= new HashMap<>();
urlParameters.put("username","xxxx");
urlParameters.put("password","xxxx");
try {
PostRequest(httpClient,URL,urlParameters);
} catch (IOException e) {
System.out.println("Client Error");
e.printStackTrace();
}
}
public HttpClient BuildClient(String URL) {
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
}
//This is the code for request build
public HttpResponse PostRequest(HttpClient httpClient, String url, Map<Object, Object> params) throws IOException {
String boundary = new BigInteger(256, new Random()).toString();
HttpRequest request = HttpRequest.newBuilder()
//.POST(HttpRequest.BodyPublishers.fromPublisher(subscriber -> ))
.POST(HttpRequest.BodyPublishers.noBody())
.POST(HttpRequest.BodyPublishers.ofString("{\"username\":\"XXXXX\"}{\"password\":\"XXXX\"}"))
//.POST(HttpRequest.BodyPublishers.ofFile(Path.of("")))
.uri(URI.create("http://example.com/request/add"))
.setHeader("User-Agent", "firefox")
.setHeader("Content-Type", "multipart/form-data")
.build();
HttpResponse<String> response = null;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(request.headers());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
return response;
}
public HttpRequest.BodyPublisher FormatData(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if(builder.length()>0)
{
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
return HttpRequest.BodyPublishers.ofString(builder.toString());
//return null;
}
}
I was wandering if can be done without add some library as maven dependency such as apache HTTP client.

Java Refreshing Auth token after 30 min

I want to know how to keep refreshing token every 30 min. Currently i dont have it. I need to cache that token for 30 min and then replace current token with the new refresh token.
Right now when i pass 1000 records all records uses same Auth token but the program runs more than 1 hour. I get Auth token expired error for some of the records.
Can anyone help me with how to handle that scenario ?
Thanks in advance
This is call class and will be calling token class.
package main.java.com.test;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import com.google.common.base.Stopwatch;
public class Call {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws IOException
{
new Call().execute();
}
public String execute() throws IOException {
String number = "01";
String id = "0123456789";
String cd = "107BC0000X";
Token getToken = new Token();
String token = null;
try {
token = getToken.Token();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("access token" + token);
return token;
}
}
This is another class called Token
package main.java.com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jettison.json.JSONObject;
public class Token {
private final String USER_AGENT = "Mozilla/5.0";
public String Token() throws Exception
{
Token http = new Token();
http.sendGet();
String token = http.sendPost();
return token;
}
private String sendPost() throws Exception
{
String url = "https://YOUR_AUTH0_DOMAIN/oauth/token";
HttpClient client = new DefaultHttpClient();
HttpClient httpClient1 = wrapClient(client);
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent" , "Mozilla/5.0");
List urlParam = (List) new ArrayList();
urlParam.add(new BasicNameValuePair("client_id", ""));
urlParam.add(new BasicNameValuePair("grant_type", ""));
urlParam.add(new BasicNameValuePair("client_secret", ""));
post.setEntity(new UrlEncodedFormEntity(urlParam));
HttpResponse response = httpClient1.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null){
result.append(line);
}
String[] JsonTags0 = result.toString().split(",");
String[] JsonTags1 = result.toString().split(":");
String token1 = JsonTags1[1].trim();
return token1.substring(1,37);
}
private void sendGet()
{
}
public static HttpClient wrapClient(HttpClient base)
{
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager1();
ctx.init(null, new TrustManager[] {tm},null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ClientConnectionManager ccm = base.getConnectionManager(ctx , SSLSocketFactory , ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf , 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}

Understanding REST create request url

What will be the url for creating an entity say myEntity through a rest url? myEntity has two parameter name and description. Here is how rest controller looks like:
#POST
#Path("/create")
#Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createJobType(MyEntity myEntity) {}
If it looks ok then how would myEntity parameters will passed through request url?
It's test class:
#Test
public void testShouldCreateMyEntity() {
MyEntity entity = new MyEntity();
entity.setName("Sample Name");
entity.setDescription("Sample Description);
String url = buildRequestURL("/create/"+entity).toUrl(); // Confused :(
}
Not sure if I should pass entity with URL. If not then how the entity would be passed?
There are many ways of testing your endpoint, and these tests might vary according to your needs.
For example, if authentication is required, or if HTTPS is required.
But supposing you don't need authentication and HTTPS is not used, you can test your endpoint with this code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import com.google.gson.Gson;
public class RestClientTest {
/**
* #param args
*/
public static void main(String[] args) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("http://localaddressportetc.../create"); // <-- I suggest you change this to "entity" since this is what is being created by the POST
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/json"));
MyEntity entity = new MyEntity();
entity.setName("Sample Name");
entity.setDescription("Sample Description");
Gson gson = new Gson();
String entityJSON = gson.toJson(entity);
StringEntity input = new StringEntity(entityJSON);
input.setContentType("application/json");
httpPost.setEntity(input);
for (NameValuePair h : nvps)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}

getApplicationContext() Issue

I'm following this tutorial :
http://www.tutos-android.com/importer-ajouter-certificat-ssl-auto-signe-bouncy-castle-android/comment-page-2#comment-2159
(SSl auto signed certificate problem)
JsonParserFUnction code :
package com.example.androidsupervision;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class JsonReaderPost {
public JsonReaderPost() {
}
public void Reader() throws IOException, JSONException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
String ints = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query","SELECT+AlertId+FROM+Orion.Alerts"));
//HttpClient client = new DefaultHttpClient();
**//Here is the problem**
HttpClient client =new MyHttpClient(getApplicationContext());
HttpPost httpPost = new
HttpPost("https://192.168.56.101:17778/SolarWinds/InformationService/v3/Json/Query");
httpPost.addHeader("content-type", "application/json");
httpPost.addHeader("Authorization", "Basic YWRtaW46");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response;
String result = null;
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
// System.out.println("RESPONSE: " + result);
Log.e("Result", "RESPONSE: " + result);
instream.close();
}
// Converting the String result into JSONObject jsonObj and then into
// JSONArray to get data
JSONObject jsonObj = new JSONObject(result);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject r = results.getJSONObject(i);
ints = r.getString("AlertId");
Log.e("Final Result", "RESPONSE: " + ints);
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I get in this line an error :
HttpClient client =new MyHttpClient(getApplicationContext());
The error is : The method getApplicationContext() is undefined for the type JsonReaderPost
You should send the context of your activity when you instantiate the class:
private Context mContext;
public JsonReaderPost(Context mContext) {
this.mContext = mContext;
}
Then, you should use "mContext" instead of getApplicationContext();
It is unknown because your class doesn't extend any other Class that has a Context, so it doesn't know what that method is. Such is, for example, an Activity.
However, using getApplicationContext(), unless you really know what you're doing, is almost always wrong. This will bring undesired behaviors like Exceptions when handled not properly. You should always use the Context of the class you're handling.
You can know which classes implement Context and get more info on contexts here.

Java IPN JSP works but Servlet fails

Have been trying to get the IPN response call to work via a servlet. I can use the demo jsp to receive the IPN request and also issue and receive the IPN response.
https://www.paypal.com/us/cgi-bin/webscr?cmd=p/pdn/ipn-codesamples-pop-outside#java
But when I try the same code in a servlet it does not work - the servlet receives the initial IPN request, I am able to pull the request variables but when I shoot them back to paypal the response I get is basically a bunch of HTML and not the typical VERIFIED message. I have surfed for a while and also tried changing my servlet any number of ways to no avail.
Thanks
Here is My servlet Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class PPListen extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8669468768750366974L;
static Logger logger = Logger.getLogger(PPListen.class.getName());
private static final String PAYPAL_TEST_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
private static final String PAYPAL_PROD_URL ="https://www.paypal.com/cgi-bin/webscr";
//private HttpClient httpClient;
public PPListen() {
// TODO Auto-generated constructor stub
}
public void service(HttpServletRequest request, HttpServletResponse respose) throws ServletException, IOException {
if (logger.isInfoEnabled()) {logger.info("Into Service ");}
PropertyConfigurator.configure("c:\\D-Drive\\EclipseProjects\\gcms\\WEB-INF\\log4j.conf");
String uri = request.getRequestURI();
String rh = request.getRemoteHost();
System.out.println("URI:"+uri+":");
System.out.println("Remote Host:"+rh+":");
// This is required by PayPal
Enumeration<String> e = request.getParameterNames();
String outStr = "cmd=_notify_validate";
logger.debug("******* Output Data");
while (e.hasMoreElements()) {
String name = e.nextElement();
String val = request.getParameter(name);
outStr = outStr + "&"+name+"="+URLEncoder.encode(val);
if (logger.isDebugEnabled()) {
logger.debug("Received Value Named:"+name+": Value:"+val+":");
}
}
URL u = new URL(PAYPAL_TEST_URL);
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(outStr);
pw.close();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
logger.debug("******* Output Data");
while (true) {
String result = in.readLine();
if (result == null) {
break;
}
logger.debug(result);
}
logger.debug("******* END");
in.close();
}
/*
public void service2(HttpServletRequest request, HttpServletResponse respose) throws ServletException, IOException {
if (logger.isInfoEnabled()) {logger.info("Into Service ");}
PropertyConfigurator.configure("c:\\D-Drive\\EclipseProjects\\gcms\\WEB-INF\\log4j.conf");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
String uri = request.getRequestURI();
String rh = request.getRemoteHost();
System.out.println("URI:"+uri+":");
System.out.println("Remote Host:"+rh+":");
// This is required by PayPal
params.add(new NameValuePair("cmd","_notify_validate"));
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
String val = request.getParameter(name);
params.add(new NameValuePair(name,val));
if (logger.isDebugEnabled()) {
logger.debug("Received Value Named:"+name+": Value:"+val+":");
}
}
NameValuePair[] uu = (NameValuePair[])params.toArray(new NameValuePair[params.size()]);
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(PAYPAL_PROD_URL);
post.setRequestBody(uu);
if (logger.isDebugEnabled()) {
logger.debug("--- calling parameters out to PayPal are ---");
for (NameValuePair nvp: params) {
logger.debug(" Being Sent - Name:"+nvp.getName()+": Value:"+nvp.getValue());
}
logger.debug("--- end of calling parameters out to PayPal ---");
}
logger.debug("--- Prior to Connect Specific");
logger.debug("--- after Connect Specific");
client.executeMethod(post);
logger.debug("--- after POST");
// String resp = post.getResponseBodyAsString();
int status = post.getStatusCode();
byte[] responseBody = post.getResponseBody();
logger.debug("Value Returned From PayPal is :"+new String(responseBody));
logger.debug("Query String :"+post.getQueryString()+":");
logger.debug("Status Code of call is "+status+":");
}
}
Any help will be great. Thanks

Categories

Resources