Setting socket buffer size in Apache HttpClient - apache

How do you set the socket buffer size in Apache HttpClient version 4.3.3?

HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024);
HttpPost post = new HttpPost(url);
String res = null;
try
{
post.addHeader("Connection", "Keep-Alive");
post.addHeader("Content-Name", selectedFile.getName());
post.setEntity(new ByteArrayEntity(fileBytes));
HttpResponse response = client.execute(post);
res = EntityUtils.toString(response.getEntity());
}
catch (Exception e)
{
e.printStackTrace();
}

You create a custom ConnectionConfig object with your desired buffer size and pass it as a parameter when creating your HttpClient object. For example:
ConnectionConfig connConfig = ConnectionConfig.custom()
.setBufferSize(DESIRED_BUFFER_SIZE)
.build();
try (CloseableHttpClient client = HttpClients.custom()
.setDefaultConnectionConfig(connConfig)
.build()) {
HttpGet get = new HttpGet("http://google.com");
try (CloseableHttpResponse response = client.execute(get)) {
// Do something with the response
} catch (IOException e) {
System.err.println("Error transferring file: " + e.getLocalizedMessage());
}
} catch (IOException e) {
System.err.println("Error connecting to server: " + e.getLocalizedMessage());
}
There are lots of other configurable options available, checkout the API for the full list.

Related

GoogleIdTokenVerifier.verify always returns null

I am trying to validate a JWT Token sent by Google to my application . I am using the below code to validate the JWT token but verifier.verify(token) always returns null even if the token is valid. I have tested the token in another NodeJS code i have and it works fine in NodeJS but in the below java code i am not able to validate the token . Any help in letting me know why verifier.verify(token) returns null is appreciated.
public static boolean isRequestFromGoogle(String audience, String token) {
//HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
//JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(httpTransport,
jsonFactory).setAudience(Collections.singletonList(audience)).build();
try {
System.out.println("token is " + token);
System.out.println("verifier is " + verifier.toString());
GoogleIdToken idToken = verifier.verify(token);
if (idToken == null) {
System.out.println("idToken is null");
return false;
}
Payload payload = idToken.getPayload();
String issuer = (String) payload.get("iss");
String proj = (String) payload.get("aud");
System.out.println("Issuer is" + issuer);
System.out.println("Project is" + proj);
return issuer.equals("https://accounts.google.com");
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

javax.net.ssl.sslpeerunverifiedexception no peer certificate Error In lifelogApi

We are getting SSL peer unverified error while fetching the access token from Lifelog api. I am able to get the authcode, but when i am trying to get access token, it is giving me SSL peer error. It works fine with few device, but most of the device it is giving SSL error.
private void getAccessToken(final String authCode)
{
final String finalUrl = String.format("https://platform.lifelog.sonymobile.com/oauth/2/token?client_id=%s&client_secret=%s&code=%s",CLIENT_ID,CLIENT_SECRET,authCode);
Thread networkThread = new Thread(new Runnable() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(finalUrl);
// Add your data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("client_id", CLIENT_ID));
nameValuePairs.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("code", authCode));
AbstractHttpEntity ent=new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
post.setEntity(ent);
// Execute HTTP Post Request
HttpResponse response =null;
try {
response = client.execute(post);
Log.d("Response:" , response.toString());
} catch (IOException e) {
e.printStackTrace();
}
String dataObject = response.toString();
JSONObject obj;
if(dataObject != null) {
obj = null;
try {
String json_string = EntityUtils.toString(response.getEntity());
// displayToast(json_string);
obj = new JSONObject(json_string);
SharedPreferences prefs =getSharedPreferences("Myprefs", Context.MODE_PRIVATE);
prefs.edit().putString("Access_token", obj.getString("access_token"));
// prefs.edit().putString(AUTH_REFRESH_TOKEN, obj.getString(AUTH_REFRESH_TOKEN));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
});
networkThread.start(); }
The problem may be with your use of HttpClient. It looks like Google has removed support for this call in Android 6.0.
http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
You should be able to use HttpsURLConnection instead of Httpclient to access the Lifelog Web Service.
I'm using google-oauth-client, I was able to use on Android 5.x with this initialization for
import com.google.api.client.http.HttpTransport;
private void initializeSocketFactory() {
if (Build.VERSION.SDK_INT >= 23) {
HTTP_TRANSPORT = new NetHttpTransport();
} else {
//Android 5 and bellow needs this SSL Socket factory initialization
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, null, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
NetHttpTransport.Builder netTransportBuilder = new NetHttpTransport.Builder();
netTransportBuilder.setSslSocketFactory(socketFactory);
HTTP_TRANSPORT = netTransportBuilder.build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
Log.e(LOG_TAG, "Problem instantiating cipher for ssl socket", e);
}
}
}
You use HTTP_TRANSPORT to instantiate:
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;

Client and Server UDP transport layer

I need to send a message saying "Hi" from client to a server, the server will reply back to the client adding to the received message "Received", once the client receives this new message it will send this to another server and that server will add another message to the received message saying "Replied". So in the end the client will receive the message "Hi Received Replied".
Client code:
public class UDPClient{
public static void main(String args[]) {
// args[0] = message to be sent to the server;
// args[1] = IP address of the server
DatagramSocket aSocket=null;
try {
aSocket=new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m,args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData(), 0, reply.getLength()));
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e){System.out.println("IO: " + e.getMessage());
}finally {
if(aSocket != null) aSocket.close();
}
}
}
Server Code:
public class UDPServer{
public static void main(String args[]) {
DatagramSocket aSocket = null;
try{
aSocket = new DatagramSocket(6789);
byte[] buffer = new byte[1000];
while(true){
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
aSocket.receive(request);
System.out.println("Server is ready and waiting for requests ... ");
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),request.getAddress(), request.getPort());
}
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e) {System.out.println("IO: " + e.getMessage());
}finally {
if(aSocket != null) aSocket.close();
}
}
}

Error on WP7 app WebRequest

I have this errors on 'error List'.
'ContentLength' is not a member of 'System.Net.WebRequest'
'GetRequestStream' is not a member of 'System.Net.WebRequest'
'GetResponse' is not a member of 'System.Net.WebRequest'
I'm make an App WindowsPhone 7 with vb.net on VisualStudio 2010
i can't understand why. Thanks
You can't due to the async nature of WP. It seems like you have lifted examples from a non WP project. In WP, you have to make the call and then register an even that listens to the completion of the task. Further reading on Async Calls
private void GetSource(object sender, RoutedEventArgs e)
{
System.Net.WebRequest request = WebRequest.Create("http://www.bbc.co.uk");
//request.ContentType = "application/json";
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
var request = asynchronousResult.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
WebResponse response = request.EndGetResponse(asynchronousResult);
using (Stream stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
var responseString = reader.ReadToEnd();
MessageBox.Show(responseString);
}
}
}
catch (WebException e)
{
// Handle exception
MessageBox.Show(e.Message);
}
}
}
public void SendPost(Uri uri, string json)
{
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.UploadStringCompleted += this.sendPostCompleted;
webClient.UploadStringAsync(uri, "POST", json);
}