I need to do the same operation but in one stream. May you help me, please?
public static byte[] archivingAndSerialization(Object object){
ByteArrayOutputStream serializationByteArray = new ByteArrayOutputStream();
ByteArrayOutputStream archvingByteArray = new ByteArrayOutputStream();
try {
ObjectOutputStream byteStream = new ObjectOutputStream(serializationByteArray);
byteStream.writeObject(object);
ZipOutputStream out = new ZipOutputStream(archvingByteArray);
out.putNextEntry(new ZipEntry("str"));
out.write(serializationByteArray.toByteArray());
out.flush();
out.close();
} catch (IOException e) {
logger.error("Error while IOException!", e);
}
return archvingByteArray.toByteArray();
}
Try
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(new DeflatingOutputStream(baos));
oos.writeObject(object);
oos.close();
return baos.toByteArray();
Note: Unless the object is medium to large in size, compressing it will make it bigger, as it add a header. ;)
To deserialize
ObjectInputStream ois = new ObjectInputStream(
new InflatorInputStream(new ByteArrayInputStream(bytes)));
return ois.readObject();
Related
I have run SAST in my codebase and got some Medium severity alerts in the Checkmarx scan and few of them states 'Unclosed_Objects' . I am not understanding this issue. Any pointers will help me.
This is giving alerts in this section of the code. All the close() methods.
public Object deepCopy(final Object value) throws HibernateException {
try {
// use serialization to create a deep copy
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(value);
oos.flush();
oos.close();
bos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray());
Object obj = new ObjectInputStream(bais).readObject();
bais.close();
return obj;
} catch (ClassNotFoundException | IOException ex) {
throw new HibernateException(ex);
}
Here is some part of my code:
This I use to receive JSONObject if it is an JSONObject, if it fails to create a JSONObject of the incoming buffer, then it is an object of class PackageFile
that contains metadata and a byte[].
public JSONObject receiveJSONObject(){
JSONObject json =null;
byte[] headerBytes=null;
ByteBuffer buffer=null;
try{
buffer= ByteBuffer.allocateDirect(2000024);
socketChannel.read(buffer);
buffer.flip();
headerBytes = new byte[buffer.remaining()];
buffer.get(headerBytes);
String jsonString = new String(headerBytes);
json = new JSONObject(jsonString);
return json;
}catch(Exception ex){
if(ex.toString().equals("org.json.JSONException: A JSONObject")){
System.out.println("byte[] is a FilePackage");
getDownloadedFilePackage(buffer);
}else{
ex.printStackTrace();
}
json=null;
}
return json;
}
private boolean getDownloadedFilePackage(ByteBuffer buffer){
FilePackage filePackage=null;
ByteArrayInputStream in=null;
ObjectInputStream obIn=null;
try{
if(buffer!=null){
in = new ByteArrayInputStream(buffer.array()); //Fails,,see: PR1
obIn = new ObjectInputStream(Channels.newInputStream(socketChannel));
filePackage= (FilePackage) obIn.readObject();
fdm.addFilePackageToDownloadingProtocol(filePackage);
in.close();
obIn.close();
return true;
}
}catch(Exception ex){
ex.printStackTrace();
}
return false;
}
PR1: When it fails in = new ByteArrayInputStream(buffer.array());, it gives this exception:
java.lang.UnsupportedOperationException
at java.nio.ByteBuffer.array(ByteBuffer.java:959)
at Client.CommunicationProtocol.getDownloadedFilePackage(CommunicationProtocol.java:115)
at Client.CommunicationProtocol.receiveJSONObject(CommunicationProtocol.java:100)
at Client.OperationManagerNIO.run(OperationManagerNIO.java:19)
at java.lang.Thread.run(Thread.java:745)
This part of the code below send the FilePackage:
public void sendFilePackage(FilePackage filePackage,SocketChannel channel){
ByteArrayOutputStream baos =null;
ObjectOutputStream oos =null;
try{
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(filePackage);
//baos.writeTo(oos);//not used
oos.flush();
channel.write(ByteBuffer.wrap(baos.toByteArray()));
}catch(Exception ex){
ex.printStackTrace();
}
}
Please help me! I can receive any message with JSONObject without any problems, but the problem is when I'm trying to send a class object, it does not work! I have been on this problem for 2 days now, and I can not see straight anymore.
As I said before, the problem is receiving the FilePackage(Class) object, it throws an exception on the first row that handles the incoming buffer from TCP NIO socketChannel.
I have tried to:
Just send FilePackage object - didn't succeed, the problem lays there, - how to send and retrieve a class object via Objectoutputstream and bytearrayoutputstream.
I'm having difficulty with ObjectInputStream. I wrote a simple test which fails on the read with an EOF error. Any input would be greatly appreciated.
public class Test
{
#Test
public void testObjectStreams( ) throws IOException, ClassNotFoundException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
String stringTest = "TEST";
oos.writeObject( stringTest );
oos.close();
baos.close();
byte[] bytes = baos.toByteArray();
String hexString = DatatypeConverter.printHexBinary( bytes);
byte[] reconvertedBytes = DatatypeConverter.parseHexBinary(hexString);
assertArrayEquals( bytes, reconvertedBytes );
ByteArrayInputStream bais = new ByteArrayInputStream(reconvertedBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
String readString = (String) ois.readObject();
assertEquals( stringTest, readString);
}
}
I want to save values as an ArrayList of double in a file. Whenever there is new value, it should be added in an ArrayList without erasing the previous ones. I'm try to use the function,DataStream. Is it possible? If its possible, please let me know how to implement that.
Please refer below code .
private static String LFILE = "serial";
public static void updateFile(Double num) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
List<Double> list = getDoubles();
list.add(num);
fos = new FileOutputStream(LFILE);
oos = new ObjectOutputStream(fos);
oos.writeObject(list);
}catch(Exception e){
e.printStackTrace();
try {
oos.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static List<Double> getDoubles() {
FileInputStream fis = null;
ObjectInputStream ois = null;
List<Double> newList = new ArrayList<Double>();
try {
fis = new FileInputStream(LFILE);
ois = new ObjectInputStream(fis);
newList = (ArrayList<Double>) ois.readObject();
} catch (Exception ex) {
try {
fis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return newList;
}
The class you want to use are ObjectOutputStream and ObjectInputStream
e.g.
http://www.javadb.com/writing-objects-to-file-with-objectoutputstream
http://www.javadb.com/reading-objects-from-file-using-objectinputstream
XStream is a library for Java which supports save/send objects in a xml-format. It is simple to use. XML is human readable making it easy to check its corrent or modify.
Is there anything in apache commons to convert a Object to byte array, like the following method does?
public static byte[] toByteArray(Object obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.flush();
byte[] data = baos.toByteArray();
return data;
}
[try-finally block closing buffers were omitted to simplify]
In commons lang:
SerializationUtils.serialize(Serializable obj)