Unclosed Objects Alerts in CheckMarx scan - java

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);
}

Related

Class cast Exception reading a written file of an ArrayList of Show Objects

/**
* A method that writes variables in a file for shows in the program.
*
* #author
* #version (1.2 2022.01.05)
*/
public void writeShowData(String fileName) throws FileNotFoundException{
String showPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{
FileOutputStream fos = new FileOutputStream(showPath+fileName,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(show);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* #author
* #version (1.2 2022.01.05)
*/
public void readShowData(String fileName) throws FileNotFoundException {
try
{ FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List <Show>shows =(List<Show>)ois.readObject();
ois.close();
System.out.println(shows.toString());// for testing
}
catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
the line : List <Show> shows= (List<Show>)ois.readObject(); gives a
ClassCastexception :class Show cannot be cast to class java.util.List
(etc etc....
I tried many things but can't get it working well.
I made the class show and related classes
Serializable and then write it to shows.ser but when it reads it goes wrong.
Who can help me out on this?
I solved your problem as below. Firstly, you need to change your writing method. If a data file does not exist, you need to create a regular (without append) FileOuputStream for stream header otherwise you will get java.io.StreamCorruptedException (ref). FileOutputStream should be created differently for the next additions.
public static void writeShowData(String fileName) {
String showPath = "E:\\path\\";
try {
File file = new File(showPath + fileName);
ObjectOutputStream oos;
if(file.exists()) {
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), true); // with reset fos
oos = new ObjectOutputStream(fos) {
protected void writeStreamHeader() throws IOException {
reset();
}
};
} else {
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); // regular fos
oos = new ObjectOutputStream(fos);
}
oos.writeObject(show);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Secondly, you need to modify your reading method. If your FileInputStream has data, you need to iterate to add your list.
public static void readShowData(String fileName) {
try {
FileInputStream fis = new FileInputStream("E:\\path\\" + fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List<Show> shows = new ArrayList<>();
while (fis.available() > 0) {
Show s = (Show) ois.readObject();
System.out.println(s.number);
shows.add(s);
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
here is my latest version that is working, the new code does leave out a few lines like if(file.exists){file.delete()}.etc... because the used streams doing that automaticly.
i totally overwrite the file(s) with an update method instead of writing one object at a time.
The earlier answers and some testing by myself made me understand how to get it done right for the purposes in my code.
/**
* A method that writes/saves variables of an Arraylist in a file for seatReservations in the program.
*
* #author Willem
* #version (1.6 2022.01.20)
*/
public void overWriteShowData(String fileName1) throws FileNotFoundException {
String seatReservationPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{ File file = new File(seatReservationPath + fileName1);
ObjectOutputStream oos;
FileOutputStream fos = new FileOutputStream(file.getCanonicalPath(),false); // regular fos
oos = new ObjectOutputStream(fos);
oos.writeObject(shows);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* #author
* #version (1.6 2022.01.20)
*/
public void readShowData(String fileName1) throws IOException, EOFException,ClassNotFoundException{
FileInputStream fis = new FileInputStream(fileName1);
ObjectInputStream ois = new ObjectInputStream(fis);
shows = (List<Show>) ois.readObject();
ois.close();
}
private void updateAllData(String fileName) {
try {
if(fileName.equals("theatres.ser"))
{overWriteTheatreData(fileName);}
if(fileName.equals("seatPlans.ser"))
{overWriteSeatPlanData(fileName);}
if(fileName.equals("shows.ser"))
{overWriteShowData(fileName);}
if(fileName.equals("customers.ser"))
{overWriteCustomerData(fileName);}
if(fileName.equals("seatReservations.ser"))
{overWriteSeatReservationData(fileName);}
} catch (FileNotFoundException fnfe) {
//fnfe.printStackTrace();
CinemaReservationSystemGUI.cannotFindFileMessage(fileName);
}
}

Modifying objects in binary file

Considering I have an object from a custom class and I write it to a .dat file using FileOutputStream and ObjectOutputStream . How will I modify a object present in the file? I can only read or write objects into a file..
I know that we can create a temporary file and then renaming the file accordingly, but isnt there any other way?
I do get outputs as expected , but isnt there any other method?
Yes you can do it by using FileOutputStream & ObjectOutputStream class
class MyBean {
public String firstvalue;
public String secondvalue;
public MyBean (String firstvalue,String secondvalue){
this.firstvalue=firstvalue;
this.secondvalue=secondvalue;
}
}
public class FileSerialization {
public static void main(String[] args) {
try {
MyBean mb = new MyBean("first value", "second value");
// write object to file
FileOutputStream fos = new FileOutputStream("mybean.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(mb);
oos.close();
// read object from file
FileInputStream fis = new FileInputStream("mybean.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
MyBean result = (MyBean) ois.readObject();
ois.close();
System.out.println("One:" + result.firstvalue + ", Two:" + result.secondvalue);
result.firstvalue="Changed;";
// write object to file
fos = new FileOutputStream("mybean.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(result);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Java Cant read or write object to file

There is this method klasOpslaan(Klas deKlas). I need to write deKlas to an object. Afterwards I need to read it with method klasInladen. I am getting an error writing aborted; java.io.NotSerializableException: week5.practicum4.Klas although I implemented Serializeable. I did note that when writing my object it makes the object but doesn't write to it. I did implement everything but StackOverflow wont let me post it.
public class KlasManager implements Serializable {
public void klasOpslaan(Klas deKlas) throws IOException, FileNotFoundException {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Klas opgeslassgen");
oos.writeObject(deKlas);
oos.close();
}
public Klas klasInladen() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Klas deKlas = (Klas) ois.readObject();
ois.close();
return deKlas;
}
}
edit: needed Serializeable in other classes, not in this one.

Save and load SMO weka model from file

I am using Weka SMO to classify my training data and I want to save and load easily to/from file my SMO model. I have created a save method in order to store Classifier to file. My code is the following:
private static Classifier loadModel(Classifier c, String name, File path) throws Exception {
FileInputStream fis = new FileInputStream("/weka_models/" + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
return c;
}
private static void saveModel(Classifier c, String name, File path) throws Exception {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream("/weka_models/" + name + ".model"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
oos.writeObject(c);
oos.flush();
oos.close();
}
My problem is, how to convert ObjectInputStream to Classifier object.
Ok it was an easy one, I ve just had to use readObject.
private static Classifier loadModel(File path, String name) throws Exception {
Classifier classifier;
FileInputStream fis = new FileInputStream(path + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (Classifier) ois.readObject();
ois.close();
return classifier;
}

Serialization and archiving object

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();

Categories