Zlib decompression in java not working - java

I am compressing a string in PHP 5.4.4-14+deb7u7 using
$cdat = gzcompress($dat, 9);
http://php.net/manual/en/function.gzcompress.php
Then in android/java I want to decompress it, from here:
Android: decompress string that was compressed with PHP gzcompress()
I am using:
public static String unzipString(String zippedText) {
String unzipped = null;
try {
byte[] zbytes = zippedText.getBytes("ISO-8859-1");
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString();
} catch (IOException e) {
}
return unzipped;
}
But when I tried it, it decompressed into an empty string, when the downloaded compressed string in android was really long.
The downloaded string was like
x�͜{o�8�a`�= �!�����[��K!(6c�E�$��]�)�HF��F\!����ə���L�LNnH]Lj٬T��M���f�'�u#�*_�7'�S^�w��*kڼn�Yޚ�I��e$.1C��~�ݟ��F�A�_Mv_�R͋��ܴ�Z^L���sU?A���?�׮�ZVmֽ6��>�B��C�M�*����^�sٸ�j����������?�"_�j�ܣY�E���h0�g��w[=&�D �oht=>�l�?��Po";`.�e�E�E��[���������sq��0���i]��������zUL�O{П��ժ�k��b�.&7��-d1_��ۣ�狝�y���=F��K!�rC�{�$����c�&9ޣH���n�x�
Does anyone know what the problem is?
Thanks.
public static Pair<String,Integer> GetHTTPResponse(String url, List<NameValuePair> urlparameters) {
String responseVal = null;
int responseCode = 0;
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = TIMEOUT_SECONDS * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = TIMEOUT_SECONDS * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(urlparameters));
HttpResponse response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
responseVal = Common.GetStringFromBufferedReader(rd);
Log.d("SERVER", responseVal);
}
catch (Exception e) {
responseCode = 0;
}
if (responseVal != null) {
responseVal = Common.unzipString(responseVal);
}
return new Pair<String, Integer>(responseVal, responseCode);
}

You can't use
BufferedReader rd =
new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
responseVal = Common.GetStringFromBufferedReader(rd);
As InputStreamReader's Javadoc notes,
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.
Instead, you could use HttpEntity.writeTo(OutputStream) and a ByteArrayOutputStream like
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] content = baos.toByteArray();
Then you can directly pass the content to your function in that byte[], and never silently swallow an Exception.
public static String unzipString(byte[] zbytes) {
String charsetName = "ISO-8859-1";
String unzipped = null;
try {
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString(charsetName);
} catch (IOException e) {
e.printStackTrace();
}
return unzipped;
}

Related

Missing Bottom part of image using getResponse().getOutputStream().write

i got the image from post response
PostMethod post = new PostMethod(action);
HttpClient httpClient = createHttpClient();
........
httpClient.executeMethod(post);
try {
log.info("post successfully");
String contentType = post.getResponseHeader("Content-type").getValue();
int contentLength = (int) post.getResponseContentLength();
byte[] responseBody = FileUtils.convertInputStreamtoByteArray(post.getResponseBodyAsStream());
log.info("get response sucessfully : size "+ responseBody.length +" contentLength " + contentLength);
return new ReturnBean(null, responseBody,contentType,contentLength);
} catch (Exception e) {
log.error(e.getMessage());
log.error(e.getStackTrace());
e.printStackTrace();
throw new ResponseFailedException(e.getMessage());
}
this is how i convert inputstream to byte array.
public static byte[] convertInputStreamtoByteArray(InputStream is){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = is.read(buf)) >= 0) {
baos.write(buf, 0, i);
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return baos.toByteArray();
}
this is how i return the image as a response.
byte[] imageSource = (byte[])returnStream.getBean();
log.info("imageSource " + imageSource.length);
getResponse().setContentType((String) returnStream.getBean2());
getResponse().setContentLength((Integer) returnStream.getBean3());
getResponse().getOutputStream().write(imageSource);
getResponse().getOutputStream().flush();
i was able to print out the image but im having a problem because the bottom part of it is missing . i checked the size of byte that i got and it is equal to the size of actual image.
when i used IOUtils.copyLarge(); instead of my method convertInputStreamtoByteArray
ServletOutputStream outputStream = getResponse().getOutputStream();
InputStream inputStream = (InputStream) returnStream.getBean();
IOUtils.copyLarge(inputStream , outputStream);
it works . i dont know what happen because i used it a while ago and it didnt work.

Upload Image to FTP Server using ADF Mobile Application

I want to upload an image to FTP Server. Currently i am using JDeveloper 12c(12.1.3.0).
My Code:
private static final int BUFFER_SIZE = 4096;
public String fileUploadMethod(String imagePath){
String ftpUrl = "ftp://";
String host = "http://192.168.0.42";
String user = "XXXXXX";
String pass = "XXXXXX";
String filePath = "783771-1.jpg";
String uploadPath = imagePath;
ftpUrl =ftpUrl + user +":"+ pass+"#"+host+"/"+filePath+";";
System.out.println("Upload URL: " + ftpUrl);
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
OutputStream outputStream = conn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadPath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File uploaded");
return "File uploaded";
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I am getting an error MalFormedURLException i.e. in detail message "unknown protocol:ftp"
Is there any other option to upload an image using JDeveloper.
Any idea regarding this.
Thanks, Siddharth
Your ftpUrl is wrong. Remove http:// in the host variable. Should be ok then
I haven't really tried ftp upload. But I had tried with multipart form upload. As far as I know, MAF doesnt provide Out-Of-Box support for file upload. What I did was essential recreating the HTTP stream for the image upload.
The POC code is attached below. This may be definitely the CRUDEST implementation but I am not sure if there is a better way.
public void doUpload() {
try {
DeviceManager dm = DeviceManagerFactory.getDeviceManager();
String imgData =
dm.getPicture(50, DeviceManager.CAMERA_DESTINATIONTYPE_FILE_URI, DeviceManager.CAMERA_SOURCETYPE_CAMERA,
false, DeviceManager.CAMERA_ENCODINGTYPE_PNG, 0, 0);
imgData = imgData.substring(7, imgData.length());
int start = imgData.lastIndexOf('/');
String fileName = imgData.substring(start+1, imgData.length());
RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter();
restServiceAdapter.clearRequestProperties();
String requestMethod = RestServiceAdapter.REQUEST_TYPE_POST;
String requestEndPoint = restServiceAdapter.getConnectionEndPoint("serverBaseUrl");
String requestURI = "/workers/100000018080264";
String request = requestEndPoint + requestURI;
HashMap httpHeadersValue = new HashMap();
httpHeadersValue.put("X-ANTICSRF", "TRUE");
httpHeadersValue.put("Connection", "Keep-Alive");
httpHeadersValue.put("content-type","multipart/form-data; boundary=----------------------------4abf1aa47e18");
// Get the connection
HttpConnection connection = restServiceAdapter.getHttpConnection(requestMethod, request, httpHeadersValue);
OutputStream os = connection.openOutputStream();
byte byteBuffer[] = new byte[50];
int len;
//String temp is appended before the image body
String temp = "------------------------------4abf1aa47e18\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" +fileName+ "\"\r\nContent-Type: image/jpeg\r\n\r\n";
InputStream stream = new ByteArrayInputStream(temp.getBytes("UTF-8"));
if (stream != null) {
while ((len = stream.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream.close();
}
FileInputStream in = new FileInputStream(imgData);
if (in != null) {
while ((len = in.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
in.close();
}
//The below String is appended after the image body
InputStream stream2 =new ByteArrayInputStream("\r\n------------------------------4abf1aa47e18--\r\n".getBytes("UTF-8"));
if (stream2 != null) {
while ((len = stream2.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream2.close();
}
int status = connection.getResponseCode();
InputStream inputStream = restServiceAdapter.getInputStream(connection);
ByteArrayOutputStream incomingBytes = new ByteArrayOutputStream() // get and process the response.
while ((len = inputStream.read(byteBuffer)) >= 0) {
incomingBytes.write(byteBuffer, 0, len);
}
String ret = incomingBytes.toString();
incomingBytes.close();
} catch (Exception e) {
e.printStackTrace();
}
}

HttpURLConnection output to byte array then to String

I'm reading a response from an HttpURLConnection object to a String like so:
HttpURLConnection conn = ...;
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream());
StringBuilder sb = ...;
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String asString = sb.toString();
If I want to read instead to a byte array first, then convert that byte array to a String, what's the right way to do it?
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
byte[] buf = new byte[512];
while (true) {
int len = in.read(buf);
if (len == -1) {
break;
}
baos.write(buf, 0, len);
}
byte[] out = baos.toByteArray();
// as a string:
String asString = new String(out);
but I'm not specifying the character in either case - are the two String outputs at the end of the examples equivalent?
Thanks

How to read byte array in php

I am sending a mp3 file using the following code to a server.In server I want a php code to receive this byte array of mp3 and convert it into file and store it there.
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
File file = new File(Environment.getExternalStorageDirectory()+ "/my.mp3");
final InputStream in = new FileInputStream(file);
final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
final byte[] data = out.toByteArray();
String urlString = "http://10.0.0.56/upload.php";
HttpPost postRequest = new HttpPost(urlString);
postRequest.setEntity(new ByteArrayEntity(data));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(postRequest);
HttpEntity entity = response.getEntity();
InputStream ins = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(ins));
String temp_str;
StringBuilder sb = new StringBuilder();
while((temp_str = br.readLine()) != null) {
sb.append(temp_str);
}
Log.e("response", sb.toString());
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
return "exception";
}
Any one know how to read the mp3 file using php.
Your upload.php could look something like this:
$mp3_bin = file_get_contents('php://input');
file_put_contents( '/path/to/my/mp3', $mp3_bin );
Short and sweet ;)
Edit:
# A bit of golfing gives a one liner:
file_put_contents('/path/to/my.mp3', file_get_contents('php://input'));

How to send byte array from Android device to servlet

I need to send some byte array from android device to Servlet. For this I try to use next code:
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
DataInputStream in = new DataInputStream((InputStream)request.getInputStream());
response.setContentType("text/plain");
byte[] buffer = new byte[1024];
int len = 0;
File file;
file=new File(getServletContext().getRealPath("/POST_LOG!!!!.txt"));
if(!file.exists()){
file.createNewFile();
}
while ((len = in.read(buffer)) > 0) {
FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/POST_LOG!!!!.txt"), true);
fos.write(buffer);
fos.close();
}
PrintWriter out = response.getWriter();
out.write("Done");
out.close();
Device side :
URL uploadUrl;
try {
uploadUrl = new URL(url);
HttpURLConnection c = (HttpURLConnection) uploadUrl
.openConnection();
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
c.setUseCaches(false);
c.connect();
OutputStream out = c.getOutputStream();
for (int i = 0; i < 1000; i++) { // generate random bytes for
// uploading
byte[] buffer = new byte[256];
for (int j = 0; j < 256; j++) {
Random r = new Random();
buffer[j] = (byte) r.nextInt();
}
out.write(buffer);
out.flush();
}
out.close();
} catch (Exception e) {
MessageBox("Error. " + e.toString());
}
return (long) 0;
}
I dont understand why this code doesnt work. When I try to debug my POST method it even not called. I will grateful for your examples
I found the solution. I just changed my device-side code using custom InputStream.
Device side :
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new InputStreamEntity(new MyInputStream(),
4096 * 1024 * 10));
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
httpPost.abort();
} catch (IOException e) {
e.printStackTrace();
httpPost.abort();
}
You have a lot of options:
send the byte values: 125,11,25,40 (that's a dumb option)
send it base64- or hex- encoded, and then decode it (use apache commons-codec)
submit it as multipart/form-data

Categories

Resources