I keep getting the error java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.io.FileOutputStream - serialization

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Vector<Vector> tableData = model.getDataVector();
//Saving of object in a file
try {
FileOutputStream file = new FileOutputStream("StudentFile.bin");
ObjectOutputStream output = new ObjectOutputStream(file);
// Method for serialization of object
output.writeObject(file);
output.close();
file.close();
} catch (Exception ex) {
ex.printStackTrace();
}
new ComputerScience_IA_UI().setVisible(true);
this.dispose();//to close the current jframe
}
this is my code
I wanted it to save data in a file
But every time it always gave me the same error java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.io.FileOutputStream

this is the right code
try {
FileInputStream file = new FileInputStream("StudentFile.bin");
ObjectInputStream input = new ObjectInputStream(file);
Vector<Vector> tableData = (Vector<Vector>)input.readObject();
input.close();
file.close();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
for (int i = 0; i < tableData.size(); i++) {
Vector row = tableData.get(i);
model.addRow(new Object [] {row.get(0), row.get(1), row.get(2), row.get(3), row.get(4), row.get(5)});
}
} catch (Exception ex) {
ex.printStackTrace();
}

Related

Converting Docx to PDF getting spacing issues

I am trying to convert a document to PDF using apache POI or Docx4j ( Apache FOP) both are giving issues while conversion.
While using apache POI it leaves line spaces when it is not there in document also.
But while using Apache FOP the table heading and table is getting shifted on next page.
I am new to this.
Can you advise which one would be better and how to avoid these spaces.
Here are code samples
SampleCode1 using apache POI
try
{
oLog.error("function POI begin");
String WordDocFile= "C:\\PRPCPersonalEdition\\tomcat\\TestDocument.docx";
oLog.error("WordDocFile is"+WordDocFile);
String pdfDocFile="C:\\PRPCPersonalEdition\\tomcat\\TestDocument.pdf";
oLog.error("pdfDocFile is"+pdfDocFile);
InputStream iStream= new FileInputStream(WordDocFile);
OutputStream os = new FileOutputStream(pdfDocFile);
org.apache.poi.xwpf.usermodel.XWPFDocument document=new org.apache.poi.xwpf.usermodel.XWPFDocument(iStream);
oLog.error("Loaded XWPFDocument");
org.apache.poi.xwpf.converter.pdf.PdfOptions options= org.apache.poi.xwpf.converter.pdf.PdfOptions.create() ;
org.apache.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(document,os,options);
iStream.close();
os.close();
return "Success";
}
catch(Exception e)
{
e.printStackTrace();
oLog.error("print exception"+e);
return "FAIL";
}
SampleCode2 using Docx4j
try
{ final org.docx4j.wml.ObjectFactory objectFactory = new org.docx4j.wml.ObjectFactory();
String WordDocFile= "C:\\PRPCPersonalEdition\\tomcat\\TestDocument.docx";
String pdfDocFile="C:\\PRPCPersonalEdition\\tomcat\\TestDocument.pdf";
InputStream iStream= new FileInputStream(WordDocFile);
org.docx4j.openpackaging.packages.WordprocessingMLPackage pack = org.docx4j.openpackaging.packages.WordprocessingMLPackage.load(iStream);
org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart docPart = pack.getMainDocumentPart();
OutputStream os = new FileOutputStream(pdfDocFile);
org.docx4j.Docx4J.toPDF(pack,os);
iStream.close();
os.close();
return "Success";
}
catch(Exception e)
{
e.printStackTrace();
oLog.error("print exception"+e);
return "FAIL";
}
#Sample Code 3 using itext
try
{
java.util.List lstInputStream = new java.util.ArrayList < java.io.InputStream > ();
oLog.error("function PDF iText begin");
String WordDocFile= "C:\PRPCPersonalEdition\tomcat\DraftMin.docx";
String pdfDocFile="C:\PRPCPersonalEdition\tomcat\DraftMinItext12.pdf";
InputStream iStream= new FileInputStream(WordDocFile);
oLog.error("Read Input file"+iStream);
java.io.InputStream isCurrentStream = null;
OutputStream os = new FileOutputStream(pdfDocFile);
java.io.ByteArrayOutputStream osCurrentStream = null;
org.apache.poi.xwpf.usermodel.XWPFDocument document=new org.apache.poi.xwpf.usermodel.XWPFDocument(iStream);
fr.opensagres.poi.xwpf.converter.pdf.PdfOptions options = fr.opensagres.poi.xwpf.converter.pdf.PdfOptions.create();
fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(document,(java.io.OutputStream)osCurrentStream, options);
com.itextpdf.text.Document finalDocument = new com.itextpdf.text.Document();
finalDocument.addAuthor("Your Corporation");
finalDocument.addCreationDate();
finalDocument.addProducer();
finalDocument.addCreator("System");
finalDocument.addTitle("Your Corporation");
finalDocument.setPageSize(com.itextpdf.text.PageSize.A4);
com.itextpdf.text.pdf.PdfCopy copy1 = new com.itextpdf.text.pdf.PdfCopy(finalDocument, (java.io.OutputStream) os);
finalDocument.open();
PRFile file = new PRFile("C:\PRPCPersonalEdition\tomcat\Savepdf.pdf");
PROutputStream prOS = new PROutputStream(file);
prOS.write(osCurrentStream.toByteArray());
oLog.debug("file write");
prOS.close();
PRInputStream prIS = new PRInputStream(file);
oLog.debug("file read");
isCurrentStream = (java.io.InputStream) prIS;
oLog.debug("casting to java.io.InputStream");
file.delete();
lstInputStream.add(isCurrentStream);
java.util.Iterator < java.io.InputStream > pdfIterator = lstInputStream.iterator();
while (pdfIterator.hasNext()) {
java.io.InputStream pdf = pdfIterator.next();
com.itextpdf.text.pdf.PdfReader.unethicalreading = true;
com.itextpdf.text.pdf.PdfReader readingpdf = new com.itextpdf.text.pdf.PdfReader(pdf);
int n = readingpdf.getNumberOfPages();
for ( int i=1;i<n;i++)
{
oLog.error("Entered in loop"+i);
copy1.addPage(copy1.getImportedPage(readingpdf, i));
oLog.error("Read Page n : "+i);
}
}
finalDocument.close();
iStream.close();
os.close();
return "Success";
}
catch(Exception e)
{
e.printStackTrace();
oLog.error("print exception"+e);
return "FAIL";
}

Dropbox Java Api Upload File

How do I upload a file public and get link ? I am using Dropbox Java core api. Here.
public static void Yukle(File file) throws DbxException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
InputStream inputStream = fileInputStream;
try (InputStream in = new FileInputStream(file)) {
UploadBuilder metadata = clientV2.files().uploadBuilder("/"+file.getName());
metadata.withMode(WriteMode.OVERWRITE);
metadata.withClientModified(new Date());
metadata.withAutorename(false);
metadata.uploadAndFinish(in);
System.out.println(clientV2.files());
}
}
I use the following code to upload files to DropBox:
public DropboxAPI.Entry uploadFile(final String fullPath, final InputStream is, final long length, final boolean replaceFile) {
final DropboxAPI.Entry[] rev = new DropboxAPI.Entry[1];
rev[0] = null;
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (replaceFile == true) {
try {
mDBApi.delete(fullPath);
} catch (Exception e) {
e.printStackTrace();
}
//! ReplaceFile is always true
rev[0] = mDBApi.putFile(fullPath, is, length, null, true, null);
} else {
rev[0] = mDBApi.putFile(fullPath, is, length, null, null);
}
} catch (DropboxException e) {
e.printStackTrace();
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rev[0];
}

Drools marshall/unmarshall not save global

I have a Test to unmarshall kiesession, with data in Global, but the unmarshall not return global.
The code is that :
Java Test
KieServices kieServices = KieServices.Factory.get();
KieContainer kContainer = kieServices.getKieClasspathContainer();
KieBase kBase1 = kContainer.getKieBase("KBase1");
KieSession kieSession1 = kContainer.newKieSession("KSession2_1");
Map<String, Object> map = new ConcurrentHashMap<String, Object>();
int tam = 10000;
for (int i = 0; i < tam; i++) {
map.put("map" + i, i);
}
kieSession1.setGlobal("map", map);
for (int i = 0; i < tam; i++) {
Client client = new Client();
client.setName("test");
client.setEdad(10);
kieSession1.insert(client);
}
kieSession1.fireAllRules();
Marshaller marshaller = MarshallerFactory.newMarshaller(kBase1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
marshaller.marshall(baos, kieSession1);
} catch (IOException e) {
fail("error");
}
byte[] data = baos.toByteArray();
try {
baos.close();
} catch (IOException e) {
fail("error");
}
//
kieSession1.dispose();
InputStream is = new ByteArrayInputStream(data);
try {
kieSession1 = marshaller.unmarshall(is);
} catch (ClassNotFoundException e) {
fail("error");
} catch (IOException e) {
fail("error : " + e);
} finally {
try {
is.close();
} catch (IOException e) {
}
}
assertEquals(tam, kieSession1.getFactCount());
assertNotNull("No existe Global !!", kieSession1.getGlobal("map"));
Drools Rule
global java.util.Map map
rule "test"
when
then
System.out.println("test !!" + map.size());
end
The version are :
org.drools:drools-compiler:jar:6.1.0.Final
org.drools:drools-core:jar:6.1.0.Final
org.kie:kie-api:jar:6.1.0.Final.1.2
org.kie:kie-internal:jar:6.1.0.Final
Globals are not inserted into the Working Memory, consequently they are not saved with the KieSession's state.
Globals have to be inserted every time you restore KieSession's state.
Just ran into this awesome behaviour, so here's a solution for loading:
You can initialise your globals BEFORE loading the session by registering a resolver with the environment:
Environment environment = kieServices.getEnvironment();
MapGlobalResolver resolver = new MapGlobalResolver(droolsProvider.globals());
environment.set(EnvironmentName.GLOBALS, resolver);
The MapGlobalResolver is the default resolver anyway. By using this approach, the resolver will be pre-initialised with the correct globals. Personally, I am thinking of writing an InjectionResolver so that Guice will inject globals on demand, but that might not be for everyone's need.
Then loading is as simple as passing the correct environment in:
KieSession loadedKieSession = kieServices.getKieService().getStoreServices().loadKieSession(session.getId(), kieBase, ksConf, environment);
Where the objects are the corresponding config object that are needed to set up the Environment.

Having Trouble with ObjectInputStream/OutputStream

I am having trouble with my programs ability to save my Maps to a file. Here are my two methods for writing and reading my maps and arraylist.
Here is my read method:
private void getData() throws IOException, ClassNotFoundException {
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
if (f_Instructors.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Instructors)))) {
//Add theList back in
if (in.readObject() != null) {
TreeMap<Instructor, Set<Student>> read = null;
while(in.available() > 0) {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
}
if (read != null) {
for (Instructor key : read.keySet()) {
System.out.println(key);
Set<Student> values = read.get(key);
PSLTrackerInfo.addInstructor(key, values);
}
System.out.println("Instructors Found! Reading...");
} else {
System.out.println("No instructor data saved.1");
}
} else {
System.out.println("No instructor data saved.2");
}
in.close();
}
}
//Add times back in
if (f_Times.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Times)))) {
if (in.readObject() != null) {
TreeMap<Student, ArrayList<Date>> readTimes = null;
while(in.available() > 0) {
readTimes = (TreeMap<Student, ArrayList<Date>>) in.readObject();
}
if (readTimes != null) {
for (Student key : readTimes.keySet()) {
System.out.println(key);
ArrayList<Date> values = readTimes.get(key);
PSLTrackerInfo.addTimes(key, values);
}
System.out.println("Dates Found! Reading...");
} else {
System.out.println("No dates saved.");
}
} else {
System.out.println("No dates saved.");
}
in.close();
}
}
//Add newStudents back in
if (f_Students.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Students)))) {
if (in.readObject() != null) {
ArrayList<Student> readStudents = null;
while (in.available() > 0) {
readStudents = (ArrayList<Student>) in.readObject();
}
if (readStudents != null) {
PSLTrackerInfo.setTheList(readStudents);
}
System.out.println("New students found! Reading...");
} else {
System.out.println("No new students data saved.");
}
in.close();
}
}
}
And Here is my Writing method:
private void saveData() {
System.out.println("Saving Data...");
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
ObjectOutputStream out_Instructors = null;
ObjectOutputStream out_Students = null;
ObjectOutputStream out_Times = null;
try {
out_Instructors = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Instructors)));
out_Students = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Students)));
out_Times = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Times)));
out_Instructors.writeObject(PSLTrackerInfo.getMap());
out_Times.writeObject(PSLTrackerInfo.getTimes());
out_Students.writeObject(PSLTrackerInfo.getList());
out_Instructors.flush();
out_Students.flush();
out_Times.flush();
out_Instructors.close();
out_Students.close();
out_Times.close();
} catch (IOException ex) {
Logger.getLogger(PrivateLessonsTrackerGUI.class.getName())
.log(Level.SEVERE, null, ex);
}
System.exit(0);
}
Sorry if it is a little confusing I have 3 files to save 3 different objects, if there is a way to save it into one file let me know but I just was getting a lot of errors that I couldn't figure out how to solve so this is what I ended up doing. Thanks for any help given.
To EJP: I tried this
TreeMap<Instructor, Set<Student>> read = null;
try {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
} catch (EOFException e) {
System.out.println("Caught EOFException!");
}
And even when there was data in it when it was written to the file, I got an EOFException everytime.
readObject() doesn't return null unless you wrote a null. If you're using that as a test for end of stream, it is invalid. The correct technique is to catch EOFException.
You are calling it and throwing away the result if it isn't null, and then calling it again. The second call will throw EOFException if there isn't another object in the file. It won't give you the same result as the first call. It's a stream.
available() is also not a valid test for end of stream. That's not what it's for. See the Javadoc. Again, the correct technique with readObject() is to catch EOFException.

save image file in specific directory jsf primefaces project

I want to save byte[] file into a specific directory :
I get it from this method :
public void setUploadedPicture(UploadedFile uploadedPicture)
{
System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());
this.uploadedPicture = uploadedPicture;
}
and I access the byte[] with :
uploadedPicture.getContents()
I tested this link but no result
how to save it into a specific directory either inside my project or outside
thank you
*********EDIT**********
here is the code whic works but sometimes I have the error :
public void setUploadedPicture(UploadedFile uploadedPicture)
{
System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());
this.uploadedPicture = uploadedPicture;
InputStream inputStr = null;
try {
inputStr = uploadedPicture.getInputstream();
} catch (IOException e) {
e.printStackTrace();
}
//create destination File
String destPath = "C:\\"+uploadedPicture.getFileName();
File destFile = new File(destPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleFileUpload(FileUploadEvent event) {
//get uploaded file from the event
UploadedFile uploadedFile = (UploadedFile)event.getFile();
//create an InputStream from the uploaded file
InputStream inputStr = null;
try {
inputStr = uploadedFile.getInputstream();
} catch (IOException e) {
//log error
}
//create destination File
String destPath = "your path here";
File destFile = new File(destPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
//log error
}
}