how can I implement zlib.compress in java - java

I would like to rewrite python code to java . This is python code:
zipped = zlib.compress(data_json_upload.encode("utf-8"))
print ("data encode")
print (zipped)
base64_bytes = base64.b64encode(zipped)
base64_string = base64_bytes.decode('utf-8')
and This is my java code :
*
byte[] bytes = inputString.getBytes("UTF-8");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream os = new GZIPOutputStream(baos);
os.write(bytes, 0, bytes.length);
os.close();
byte[] result = baos.toByteArray();
System.out.println(result);
byte [] base64=Base64.encodeBase64(result);
String send= new String(base64,"UTF-8");
*
however they seems to be return different results for the same string any idea what can I change to get the same code is working on java ?
For example send in java not the same as base64_string in java

GZIPOutputStream will produce a *.gz file. If you just need a zlib stream, use DeflaterOutputStream instead.
// ... the rest are the same ...
DeflaterOutputStream os = new DeflaterOutputStream(baos);
// ... the rest are the same ...

Related

Android: Trying to test sockets

I'm trying to test socket communication in Android Java, but can't seem to get a mock working.
First of all, using Mockito, mock(Socket.class) throws an Exception java.lang.VerifyError.
So I coded my mock like so:
public void testMyTest(){
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
try{
byte[] buffer = new byte[6];
os.write("poulet".getBytes());
is.read(buffer, 0, 6);
Log.w(LOG_TAG, "Read result:" + (new String(buffer, "UTF-8")));
} catch(IOException e){}
}
However is is not reading from os when I call os.write(). The raw result is [B#42204320 and, in string form, it looks like ������������. I tried commenting os.write() but nothing changed.
Does anyone know how to link an input stream to read form an output stream?
To test my classes I just called
final Socket mockedSocket1 = new Socket();
final Socket mockedSocket2 = new Socket();
when(mockedSocket1.getInputStream()).thenReturn(is);
when(mockedSocket2.getOutputStream()).thenReturn(os)
So that my classes get the linked output and input streams that I'm going to test with.
Thanks a lot!
The is's buffer will always be empty.
This: ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); just creates an ByteArrayInputStream with an empty buffer, that buffer won't change when you write something to the ByteArrayOutputStream.
public byte[] toByteArray()
Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it.
...
What you can do is to create the ByteArrayInputStream after you write something to the ByteArrayOutputStream, eg:
try (ByteArrayOutputStream os = new ByteArrayOutputStream();){
byte[] buffer = new byte[6];
os.write("poulet".getBytes("UTF-8"));
try(ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());){
is.read(buffer, 0, 6);
System.out.println("Read result:|" + (new String(buffer, "UTF-8") + "|"));
}
} catch (IOException e) {
}

Convert ZIP to byte array without saving the output to file

I have a ZIP file and when I convert it into byte array and encode it, I am unable to print the encoded format without writing it into file.
Could anyone help in solving this issue?
My code is
InputStream is = null;
OutputStream os = null;
is = new FileInputStream("C:/Users/DarkHorse/Desktop/WebServicesTesting/PolicyCredit.zip");
os = new FileOutputStream("D:/EclipseTestingFolder/EncodedFile1.txt");
int bytesRead = 0;
int chunkSize = 10000000;
byte[] chunk = new byte[chunkSize];
while ((bytesRead = is.read(chunk)) > 0)
{
byte[] ba = new byte[bytesRead];
for(int i=0;i<ba.length;i++)
{
ba[i] = chunk[i];
}
byte[] encStr = Base64.encodeBase64(ba);
os.write(encStr);
}
os.close();
is.close();
}
My Output in the file is
UEsDBBQAAAAIANGL/UboGxdAAQUAAK0WAAAQAAAAUG9saWN5Q3JlZGl0LnhtbJVY3Y6rNhC+r9R34AlqSPankSwkdtNskbLZKOk5Va8QC95d6wRIDZyeffszxgSMGUPKFcx8M/b8egwN87IWcZ6waF+cePLp//qLAw/d8BOL/mRxykRL6sk89T1KLq8adx1XLHp5i55YzkRc8SL3F6534y69O0oQpia6K6LiLTqwpBBpKdUPCRq
But when I am trying to print it on the screen, I am getting in this way
8569115686666816565656573657871764785981117112010065658185656575488765656581656565658571571159787785381517410890711084876110104116987486895189541147810467431145782515265108113838097110107831191071001167811510798769075791075386975681675753100541198273689012110110210211512212010383777185807570991205677479856101103119785655738799905411997704399101807611247471137665119471005666797647109821201211078276
You need to create a string representation of Base 64 encoded data.
System.out.println( new String(encStr, Charset.forName("UTF-8")));
Here are some other examples Base 64 Print Question
String Class
Assuming your result array byte[] encStr = Base64.encodeBase64(ba) is actually the encoded string, try the following:
System.out.println(new String(bytes, Charset.defaultCharset());
If you are using JDK 7 you can use Files.readAllBytes(path)
Your code would be much simpler like below:
Path path = Paths.get("C:/Users/DarkHorse/Desktop/WebServicesTesting/PolicyCredit.zip");
byte[] data = Files.readAllBytes(path);
byte[] encStr = Base64.encodeBase64(data);
System.out.println( new String(encStr));
Your will be able to print on console.

Compressiopn using GZIPOutputStream and decompression in php

I have been communicating with my Java application using php by creating a socket, from Java end, I will compress the result and write those bytes to the php.
public static byte[] compressString(byte[] b) throws IOException{
byte[] compressedBytes = null;
ByteArrayOutputStream out = new ByteArrayOutputStream(b.length);
try{
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(b, 0, b.length);
gzip.finish();
gzip.flush();
gzip.close();
compressedBytes = out.toByteArray();
System.out.println("comp1::"+compressedBytes+", length::"+compressedBytes.length);
}finally{
out.close();
}
return compressedBytes;
}
But when i am performing
$data = fgets($fp);
$decompData = gzuncompress($data);
$decompData is returned null.
Kindly provide a solution as i have tried Deflater with gzuncompress, gzdecode and every possible option. There must be something i am missing here. Consider me as newbie in php.
You need to use gzdecode() for gzip streams, and you may need to open the file using "rb" to read binary data without translation.

Is there an alternative to FileOutputStream type , which does not create a file?

To process some images in my android application I currently use code like this:
FileOutputStream fileOuputStream = new FileOutputStream(imgpath);
[..DO SOME STUFF..]
Bitmap data = BitmapFactory.decodeByteArray(bFile, 0, bFile.length, options);
data.compress(Bitmap.CompressFormat.JPEG, 90, fileOuputStream);
[..DO SOME STUFF..]
File file = new File(imgpath);
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
[..DO SOME STUFF..]
file.delete();
//NOTE: The code is all in the same method
the problem is that passing my image from one part of the code to another using this method creates a temporary file.
I was looking for a way to read / write the file data using a memory variable, something like "generic stream" in which store data in order to replace use of "FileInputStream " and "FileOutputStream " and do not write temporary file.
If you are able to use an InputStream or OutputStream you can use ByteArrayInputStream or ByteArrayOutputStream for in memory handling of the data.
If you have two thread you can also use PipedInputStream and PipedOutputStream together to communicate between the threads.
You could write your data to a ByteArrayOutputStream and use the byte array of that stream:
ByteArrayOutputStream out = new ByteArrayOutputStream();
data.compress(Bitmap.CompressFormat.JPEG, 90, out);
// now take the bytes out of your Stream
byte[] imgData = out.toByteArray();

ObjectOutputStream.toByteArray returns garbage

I need to get the byte array out of everything I send to the output stream. But instead I get 4 bytes of rubbish. Why?
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.write(new byte[]{1,2,3,4,5,6,7,8,9});
byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original)); // why not [1,2,3,4,5,6,7,8,9]?
There are several flaws in your code. First of all you should use writeObject():
objectOutputStream.writeObject(new byte[]{1,2,3,4,5,6,7,8,9});
then you should use symmetric ObjectInputStream for reading:
final ObjectInputStream objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(
byteArrayOutputStream.toByteArray()
)
);
byte[] original = (byte[]) objectInputStream.readObject();
However if you already have a byte[], there is no point in using Java serialization to convert it to byte array (which it already is!) Just write and read it directly:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9});
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
byteArrayOutputStream.toByteArray()
);
final byte[] original = new byte[9];
byteArrayInputStream.read(original);
System.out.println(Arrays.toString(original));
An ObjectOutputStream is not a OutputStream and if it did the same thing there wouldn't be much point in having it.
An ObjectOutputStream is used for writing Objects, it has a header (which you can see) and footer (which you can't see unless you close the stream)
You didn't write anything into the objectOutputStream, but some meta information, that comes with the ObjectOutputStream.
For the purpose of your small example you can use the ByteArrayOutputStream. Then You need to write the data into the stream using byteArrayOutputStream.flush().
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(new byte[]{1,2,3,4,5,6,7,8,9});
byteArrayOutputStream.flush();
byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original));
And don't forget to close the stream when you are done!
byteArrayOutputStream.close();
ObjectOutputStreams are used to serialize Objects.
If you want to serialize Objects you should use ObjectOutputStream#writeObject and ObjectInputStream#readObject.
Example : http://java.sun.com/developer/technicalArticles/Programming/serialization/

Categories

Resources