I have a jtable that can be edite and then saved (updated) to a text file.
User select a line (that contains a book record) and request to borrow that book,
I use this method to update, But now when update, the old data is not deleted.
user_AllBooks uAllBooks = new user_AllBooks();
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == borrowButton) {
borrowInitialize(bTable.getSelectedRow());
}
public void borrowInitialize(int row) {
if (uAllBooks.getValueAt(row, 3).equals("Yes")) {
JOptionPane.showMessageDialog(null, "This Book Was Borrowed");
} else {
uAllBooks.setValueAt("Yes", row, 3);
uAllBooks.fireTableRowsUpdated(row, row);
uAllBooks.updateFiles(uAllBooks.bData);
}
}
...
}
public class user_AllBooks extends AbstractTableModel {
...
public void updateFiles(ArrayList<BookInformation> data) {
PrintWriter Bpw = null;
try {
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , true));
for (BookInformation bookinfo : data) {
String line = bookinfo.getBookID()
+ " " + bookinfo.getBookName()
+ " " + bookinfo.getBookDate()
+ " " + bookinfo.getBorrowStatus();
Bpw.println(line);
}
Bpw.close();
} catch (FileNotFoundException e1) {
} catch (IOException ioe) {
}
}
...
}
My BookInformation Class:
public class BookInformation {
private String BookName;
private String BookDate;
private String BookID;
private String BorrowStatus;
public String getBookName() {
return BookName;
}
public void setBookName(String book_name) {
this.BookName = book_name;
}
public String getBookDate() {
return BookDate;
}
public void setBookDate(String book_date) {
this.BookDate = book_date;
}
public String getBookID() {
return BookID;
}
public void setBookID(String Book_id) {
this.BookID = Book_id;
}
#Override
public String toString() {
return BookID + " " + BookName + " "
+ BookDate + " " + BorrowStatus + "\n";
}
public String getBorrowStatus() {
return BorrowStatus;
}
public void setBorrowStatus(String borrowStat) {
BorrowStatus = borrowStat;
}
}
Thanks.
Change this line
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , true));
to
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , false));
The second parameter (boolean) changes whether it should append the text file (add to the end of it) or just rewrite everything.
Source: Javadoc constructor summary for FileWriter:
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Related
I'm currently learning to develop a simple blockchain program that reads sample data from .txt and creates a new block for every 10 transactions. I was wondering if the given sample data was 23 lines of transactions, is there a way to make a new block that consist of the last 3 transactions ?
Current Output
Block[header=Header[index=0,currHash=51aa6b7cf5fb821189d58b5c995b4308370888efcaac469d79ad0a5d94fb0432, prevHash=0, timestamp=1654785847112], tranx=null]
Block[header=Header[index=0,currHash=92b3582095e2403c68401448e8a34864e8465d0ea51c05f11c23810ec36b4868, prevHash=0, timestamp=1654785847385], tranx=Transaction [tranxLst=[alice|bob|credit|1.0, alice|bob|debit|2.0, alice|bob|debit|3.0, alice|bob|credit|4.0, alice|bob|debit|5.0, alice|bob|credit|6.0, alice|bob|debit|7.0, alice|bob|debit|8.0, alice|bob|debit|9.0, alice|bob|debit|10.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614519, prevHash=0, timestamp=1654785847386], tranx=Transaction [tranxLst=[alice|bob|credit|11.0, alice|bob|credit|12.0, alice|bob|debit|13.0, alice|bob|debit|14.0, alice|bob|credit|15.0, alice|bob|credit|16.0, alice|bob|credit|17.0, alice|bob|debit|18.0, alice|bob|credit|19.0, alice|bob|credit|20.0]]]
What I want
Block[header=Header[index=0,currHash=51aa6b7cf5fb821189d58b5c995b4308370888efcaac469d79ad0a5d94fb0432, prevHash=0, timestamp=1654785847112], tranx=null]
Block[header=Header[index=0,currHash=92b3582095e2403c68401448e8a34864e8465d0ea51c05f11c23810ec36b4868, prevHash=0, timestamp=1654785847385], tranx=Transaction [tranxLst=[alice|bob|credit|1.0, alice|bob|debit|2.0, alice|bob|debit|3.0, alice|bob|credit|4.0, alice|bob|debit|5.0, alice|bob|credit|6.0, alice|bob|debit|7.0, alice|bob|debit|8.0, alice|bob|debit|9.0, alice|bob|debit|10.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614519, prevHash=0, timestamp=1654785847386], tranx=Transaction [tranxLst=[alice|bob|credit|11.0, alice|bob|credit|12.0, alice|bob|debit|13.0, alice|bob|debit|14.0, alice|bob|credit|15.0, alice|bob|credit|16.0, alice|bob|credit|17.0, alice|bob|debit|18.0, alice|bob|credit|19.0, alice|bob|credit|20.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614520, prevHash=0, timestamp=1654785847387], tranx=Transaction [tranxLst=[alice|bob|credit|21.0, alice|bob|credit|22.0, alice|bob|debit|23.0]]]
my code:
Client app
public static void main(String[] args) throws IOException {
homework();
}
static void homework() throws IOException {
int count = 0;
Transaction tranxLst = new Transaction();
Block genesis = new Block("0");
System.out.println(genesis);
BufferedReader bf = new BufferedReader(new FileReader("dummytranx.txt"));
String line = bf.readLine();
while (line != null) {
tranxLst.add(line);
line = bf.readLine();
count++;
if (count % 10 == 0) {
Block newBlock = new Block(genesis.getHeader().getPrevHash());
newBlock.setTranx(tranxLst);
System.out.println(newBlock);
tranxLst.getTranxLst().clear();
}
}
bf.close();
}
Transaction class
public class Transaction implements Serializable {
public static final int SIZE = 10;
/**
* we will comeback to generate the merkle root ie., hash of merkle tree
* merkleRoot = hash
*/
private String merkleRoot = "9a0885f8cd8d94a57cd76150a9c4fa8a4fed2d04c244f259041d8166cdfeca1b8c237b2c4bca57e87acb52c8fa0777da";
// private String merkleRoot;
public String getMerkleRoot() {
return merkleRoot;
}
public void setMerkleRoot(String merkleRoot) {
this.merkleRoot = merkleRoot;
}
/**
* For the data collection, u may want to choose classic array or collection api
*/
private List<String> tranxLst;
public List<String> getTranxLst() {
return tranxLst;
}
public Transaction() {
tranxLst = new ArrayList<>(SIZE);
}
/**
* add()
*/
public void add(String tranx) {
tranxLst.add(tranx);
}
#Override
public String toString() {
return "Transaction [tranxLst=" + tranxLst + "]";
}
}
Block class
public class Block implements Serializable {
private Header header;
public Header getHeader() {
return header;
}
private Transaction tranx;
public Block(String previousHash) {
header = new Header();
header.setTimestamp(new Timestamp(System.currentTimeMillis()).getTime());
header.setPrevHash(previousHash);
String blockHash = Hasher.sha256(getBytes());
header.setCurrHash(blockHash);
}
/**
* getBytes of the Block object
*/
private byte[] getBytes() {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);) {
out.writeObject(this);
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Transaction getTranx() {
return tranx;
}
/**
* aggregation rel
*/
public void setTranx(Transaction tranx) {
this.tranx = tranx;
}
/**
* composition rel
*/
public class Header implements Serializable {
private int index;
private String currHash, prevHash;
private long timestamp;
// getset methods
public String getCurrHash() {
return currHash;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void setCurrHash(String currHash) {
this.currHash = currHash;
}
public String getPrevHash() {
return prevHash;
}
public void setPrevHash(String prevHash) {
this.prevHash = prevHash;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
#Override
public String toString() {
return "Header [index=" + index + ", currHash=" + currHash + ", prevHash=" + prevHash + ", timestamp="
+ timestamp + "]";
}
}
#Override
public String toString() {
return "Block [header=" + header + ", tranx=" + tranx + "]";
}
}
enter code here
Instead of using a counter in the conditional statement, try ForLoop.
static void homework() throws IOException {
Transaction tranxLst = new Transaction();
Block genesis = new Block("0");
System.out.println(genesis);
BufferedReader bf = new BufferedReader(new FileReader("dummytranx.txt"));
String line = bf.readLine();
while (line != null) {
for (int i = 0; i < 10; i++) {
tranxLst.add(line);
line = bf.readLine();
if (line == null) {
break;
}
}
Block newBlock = new Block(genesis.getHeader().getPrevHash());
newBlock.setTranx(tranxLst);
System.out.println(newBlock);
tranxLst.getTranxLst().clear();
}
bf.close();
}
I need to format the I/O text, which comes from a .txt file. I am able to print it, but I can't separate it in the different categories.
public class Main {
public static void main(String[] args) throws Exception {
class Recipe implements java.io.Serializable {
private String name, ingredients, steps;
public Recipe(String name, String ingredients, String steps) {
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
}
public String toString(){
return "dishName: " + name + " ingredients: " + ingredients + " steps: ";
}
}
Scanner input = null;
try {
//Choose the file that you will use.
input = new Scanner (new BufferedReader(new FileReader ("Root/src/recipes.txt")));
while ( input.hasNext() ) {
System.out.println(input.nextLine());
}
//Read your input and create the Objects Recipe
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null){
input.close();
}
} finally {
if (input != null){
input.close();
}
}
}
}
}
I found this great Java Bean that allows you to send an html email including attachments via a managed java bean. It works as described when I use it directly form an Xpage.
However, I would like to use this in the backend in a scheduled agent. The problem I have run into is when I try to pass a document to the java bean. The bean is expecting (I think) an XSP document, which I don't have when in the back end, so it throws an error.
I thought I would just send the UNID of the document that I want and then change it so it would work with this bean, however, when I try to set the UNID I get an error:
Unknown member 'setUNID' in Java class 'com.scoular.utls.Email'
I am confused. Seems like this has something to do with a wrapped document, but don't understand.
Here is the faces-config:
<faces-config>
<managed-bean>
<managed-bean-name>Email</managed-bean-name>
<managed-bean-class>com.scoular.utls.Email</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>debugMode</property-name>
<value>true</value>
</managed-property>
</managed-bean>
</faces-config>
Here is a button I am using to test calling the method:
//Need to get email document
var emlView = database.getView("xpViewEmailsAll");
var emlDoc = emlView.getFirstDocument();
if (emlDoc != null) {
//try{
var subject = ""
var senderEmail = supEml
var senderName = supNme
Email.setSendTo("John");
Email.setSubject("subject");
Email.setSenderEmail("John#gmal.com");
Email.setUNID = emlDoc.getUniversalID();
Email.setSenderName("Sender");
//Email.setBackEndDocument(emlDoc);
Email.setFieldName("Body");
Email.send();
//}catch(e){
//print(e.getMessage());
//}
}
And here is the bean:
package com.scoular.utls;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.Stream;
import com.ibm.commons.util.NotImplementedException;
import com.ibm.domino.xsp.module.nsf.NotesContext;
import com.ibm.xsp.model.FileRowData;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.model.domino.wrapped.DominoRichTextItem;
import com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder;
import com.ibm.xsp.persistence.PersistedContent;
public class Email {
private ArrayList<String> sendTo;
private ArrayList<String> ccList;
private ArrayList<String> bccList;
private String senderEmail;
private String senderName;
private String subject;
private DominoDocument document;
private String fieldName;
private String bannerHTML;
private String footerHTML;
private String unid;
private boolean debugMode = false;
private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
// -------------------------------------------------------------------------
public Email() {
this.subject = "";
this.sendTo = new ArrayList<String>();
this.ccList = new ArrayList<String>();
this.bccList = new ArrayList<String>();
}
// -------------------------------------------------------------------------
public String getSendTo() {
if (this.isDebugMode()) {
System.out.println("getSendTo() : " + this.sendTo.toString());
}
return this.sendTo.toString().replace("[", "").replace("]", "");
}
public void setSendTo(final String sendTo) {
this.sendTo.add(sendTo);
}
// -------------------------------------------------------------------------
public String getCcList() {
if (this.isDebugMode()) {
System.out.println("getCcList() : " + this.ccList.toString());
}
return this.ccList.toString().replace("[", "").replace("]", "");
}
public void setCcList(final String ccList) {
this.ccList.add(ccList);
}
// -------------------------------------------------------------------------
public String getBccList() {
if (this.isDebugMode()) {
System.out.println("getBccList() : " + this.bccList.toString());
}
return this.bccList.toString().replace("[", "").replace("]", "");
}
public void setBccList(final String bccList) {
this.bccList.add(bccList);
}
// -------------------------------------------------------------------------
public String getSenderEmail() {
return this.senderEmail;
}
public void setSenderEmail(final String senderEmail) {
this.senderEmail = senderEmail;
}
// -------------------------------------------------------------------------
public String getSenderName() {
return this.senderName;
}
public void setSenderName(final String senderName) {
this.senderName = senderName;
}
// -------------------------------------------------------------------------
public String getSubject() {
return this.subject;
}
public void setSubject(final String subject) {
this.subject = subject;
}
// -------------------------------------------------------------------------
public boolean isDebugMode() {
return this.debugMode;
}
public void setDebugMode(final boolean debugMode) {
this.debugMode = debugMode;
}
// -------------------------------------------------------------------------
private Session getCurrentSession() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentSession() : null;
}
// -------------------------------------------------------------------------
private Database getCurrentDatabase() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentDatabase() : null;
}
// -------------------------------------------------------------------------
public void send() throws NotesException, IOException, Exception {
Session session = getCurrentSession();
Database database = getCurrentDatabase();
if (null != session && null != database && null != this.sendTo && null != this.subject
&& null != this.senderEmail) {
try {
if (this.isDebugMode()) {
System.out.println("Started send()");
}
session.setConvertMime(false);
Document emailDocument = database.createDocument();
MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body");
if (null != emailRoot) {
MIMEHeader emailHeader = emailRoot.createHeader("Reply-To");
emailHeader.setHeaderVal(this.getSenderEmail());
emailHeader = emailRoot.createHeader("Return-Path");
emailHeader.setHeaderVal(this.getSenderEmail());
final String fromSender = (null == this.getSenderName()) ? this.getSenderEmail() : "\""
+ this.getSenderName() + "\" <" + this.getSenderEmail() + ">";
emailHeader = emailRoot.createHeader("From");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("Sender");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("To");
emailHeader.setHeaderVal(this.getSendTo());
if (!this.ccList.isEmpty()) {
emailHeader = emailRoot.createHeader("CC");
emailHeader.setHeaderVal(this.getCcList());
}
if (!this.bccList.isEmpty()) {
emailHeader = emailRoot.createHeader("BCC");
emailHeader.setHeaderVal(this.getBccList());
}
emailHeader = emailRoot.createHeader("Subject");
emailHeader.setHeaderVal(this.getSubject());
MIMEEntity emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild) {
final String boundary = System.currentTimeMillis() + "-" + this.document.getDocumentId();
emailHeader = emailRootChild.createHeader("Content-Type");
emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
MIMEEntity emailChild = emailRootChild.createChildEntity();
if (null != emailChild) {
final String contentAsText = this.document.getRichTextItem(this.fieldName)
.getContentAsText();
Stream stream = session.createStream();
stream.writeText(contentAsText);
emailChild.setContentFromText(stream, "text/plain; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
emailChild = emailRootChild.createChildEntity();
stream = session.createStream();
stream.writeText(this.getHTML());
emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
stream.recycle();
stream = null;
}
// add embedded images....
final List<FileRowData> embeddedImages = this.getEmbeddedImagesList();
if (null != embeddedImages && !embeddedImages.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Images...");
}
for (FileRowData embeddedImage : embeddedImages) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && embeddedImage instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) embeddedImage)
.getPersistentName();
String cid = ((AttachmentValueHolder) embeddedImage).getCID();
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("inline; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = this.getEmbeddedImageStream(persistentName);
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, embeddedImage.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Embedded Image : " + persistentName);
}
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Image failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Embedded Images");
}
}
// add attachments....
final List<FileRowData> attachments = this.getDocument().getAttachmentList(this.getFieldName());
if (null != attachments && !attachments.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Attachments...");
}
for (FileRowData attachment : attachments) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && attachment instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) attachment)
.getPersistentName();
String cid = ((AttachmentValueHolder) attachment).getCID();
EmbeddedObject eo = this.getDocument().getDocument().getAttachment(
persistentName);
if (null != eo) {
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = eo.getInputStream();
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, attachment.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Attachment : " + persistentName);
}
}
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Adding Attachment failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Attachments");
}
}
}
}
emailDocument.send();
session.setConvertMime(true);
if (this.isDebugMode()) {
System.out.println("Completed send()");
}
} catch (NotesException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with NotesException" + e.getMessage());
}
throw e;
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with IOException" + e.getMessage());
}
throw e;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with Exception" + e.getMessage());
}
throw e;
}
}
}
// -------------------------------------------------------------------------
public DominoDocument getDocument() {
return this.document;
}
public void setDocument(final DominoDocument document) {
this.document = document;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
// -------------------------------------------------------------------------
public List<FileRowData> getEmbeddedImagesList() throws NotesException {
if (null != document && null != fieldName) {
return document.getEmbeddedImagesList(fieldName);
}
return null;
}
// -------------------------------------------------------------------------
private InputStream getEmbeddedImageStream(final String fileName) throws NotesException, IOException {
if (null != document && null != fieldName && null != fileName) {
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
final PersistedContent pc = drti.getPersistedContent(FacesContext.getCurrentInstance(), fieldName,
fileName);
if (null != pc) {
return pc.getInputStream();
}
}
}
return null;
}
// -------------------------------------------------------------------------
public String getHTML() {
StringBuffer html = new StringBuffer();
html.append(getBannerHTML());
html.append(getBodyHTML());
html.append(getFooterHTML());
return html.toString();
}
// -------------------------------------------------------------------------
public String getBannerHTML() {
return this.bannerHTML;
}
public void setBannerHTML(final String bannerHTML) {
this.bannerHTML = bannerHTML;
}
// -------------------------------------------------------------------------
public String getBodyHTML() {
if (null != document && null != fieldName) {
if (this.isDebugMode()) {
System.out.println("Started getBodyHTML()");
}
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
try {
String html = drti.getHTML();
if (null != html) {
final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName);
if (null != fileRowDataList) {
final Matcher matcher = imgRegExp.matcher(html);
while (matcher.find()) {
String src = matcher.group();
final String srcToken = "src=\"";
final int x = src.indexOf(srcToken);
final int y = src.indexOf("\"", x + srcToken.length());
final String srcText = src.substring(x + srcToken.length(), y);
for (FileRowData fileRowData : fileRowDataList) {
final String srcImage = fileRowData.getHref();
final String cidImage = ((AttachmentValueHolder) fileRowData).getCID();
if (srcText.endsWith(srcImage)) {
final String newSrc = src.replace(srcText, "cid:" + cidImage);
html = html.replace(src, newSrc);
if (this.isDebugMode()) {
System.out.println("CID referenced image: " + srcText + " with CID:"
+ cidImage);
}
}
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed getBodyHTML() : " + html);
}
return html;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed getBodyHTML() : " + e.getMessage());
}
}
}
}
return null;
}
public void setBodyHTML(final String bodyHTML) throws NotImplementedException {
if (this.isDebugMode()) {
System.out.println("Method setBodyHTML(string) is not permitted");
}
throw new NotImplementedException();
}
// -------------------------------------------------------------------------
public String getFooterHTML() {
return this.footerHTML;
}
public void setFooterHTML(final String footerHTML) {
this.footerHTML = footerHTML;
}
public String getUnid() {
return unid;
}
public void setUnid(final String unid) {
this.unid = unid;
}
// -------------------------------------------------------------------------
} // end EmailBean
The Email.setUNID statement is wrong. Try:
Email.setUnid(emlDoc.getUniversalID());
My arraylist<"obj"> becomes null after trying to write to a file.
In WriteToFile class arraylist info becomes null after executing the last line
writer.write(info.get(i).getIpadd().toString()+"\n");
It works on the first instance when i am writing another list to file but does not when i run it the 2nd instance. I dun understand why its happening. Below is the whole code and the stack trace.
WriteToFile Class:
public class WriteToFile {
public WriteToFile(ArrayList<Information> info,String location)
{
FileWriter writer=null;
try
{
writer = new FileWriter(location);
System.out.println(info.size());
for(int i=0;i<info.size()-1;i++)
{
writer.write(info.get(i).getDate().toString()+",");
writer.write(info.get(i).getAccount().toString()+",");
writer.write(info.get(i).getStatus().toString()+",");
writer.write(info.get(i).getIpadd().toString()+"\n");
System.out.println(info.get(i).getAccount());
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StackTrace:
java.lang.NullPointerException
at WriteToFile.<init>(WriteToFile.java:17)
at Gen_Report.<init>(Gen_Report.java:45)
at Gen_Report.main(Gen_Report.java:57)
main:
public class Gen_Report {
public Gen_Report()
{
// TODO Auto-generated constructor stub
//locate file and read all text from .log file to .csv
//file is found.so read text from it and extract all date/time, email add ,accepts and rejects,ip add, delete
Date date=new Date();
String[] dateTokens=date.toString().split(" ");
String dateString=dateTokens[2]+dateTokens[1]+dateTokens[5]+"_"+dateTokens[3].substring(0, 2)+dateTokens[3].substring(3,5)+dateTokens[3].substring(6, 8);
String logFileLocation = "/Users/gundu_87/Documents/workspace/GenFLRReport/";
ReaderFromLog rfl = new ReaderFromLog(logFileLocation+"radsecproxy.log");
//include duplicates
WriteToFile wtf = new WriteToFile(rfl.log,logFileLocation+dateString+"_FLRlogduplicates.txt");
//exclude duplicates
RemoveDuplicatesInList rdil = new RemoveDuplicatesInList(logFileLocation+dateString+"_FLRlogduplicates.txt");
for(int i=0;i<rdil.log.size();i++)
{
System.out.println(rdil.log.get(i).getAccount());
}
wtf = new WriteToFile(rdil.log,logFileLocation+dateString+"_FLRlog.txt");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen_Report gr= new Gen_Report();
}
}
Information class:
public class Information {
private String ipadd;
private String status;
private String account;
private String date;
public String getIpadd() {
return ipadd;
}
public void setIpadd(String ipadd) {
this.ipadd = ipadd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReaderFromLog class
public class ReaderFromLog {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public ReaderFromLog(String logFileLocation) {
// TODO Auto-generated constructor stub
File logFile = new File(logFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Access-Accept for user"))
{
newUser.setStatus("Accept");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
else if(line.contains("Access-Reject for user"))
{
newUser.setStatus("Reject");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
}while(s1.hasNextLine());
}
}
RemoveDuplicate class:
public class RemoveDuplicatesInList {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public RemoveDuplicatesInList(String duplicateFileLocation)
{
// TODO Auto-generated constructor stub
File logFile = new File(duplicateFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
boolean sameAccount=false;
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Accept"))
{
newUser.setStatus("Accept");
String[] sb=line.split(",");
sameAccount=false;
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
else if(line.contains("Reject"))
{
newUser.setStatus("Reject");
String[] sb=line.split(",");
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
}while(s1.hasNextLine());
}
}
Check value of
info.get(i).getIpadd()
if value of this is null then .toString(0 will give you NullPointerException
My goal: save one ArrayList to a .dat file, after read this file and in the end print this array.
To save the ArrayList, "equipas" is one ArrayList< Equipa>, I use this function:
saveMyFile("Equipas.dat", (Object) equipas);
To read:
public static ArrayList<Equipa> readMyFile(String s){
ArrayList<Equipa> novo = new ArrayList<Equipa>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(s));
novo = (ArrayList<Equipa>) ois.readObject();
ois.close();
}
catch(IOException er) { System.out.println(er.getMessage()); }
catch(ClassNotFoundException er) { System.out.println(er.getMessage()); }
return novo;}
In this read function, I have one Compilation Warning: "…uses unchecked or unsafe operations. Recompile with - Xlint:unchecked for details."
To save:
public static void saveMyFile(String s, Object o)
{
try {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(s));
oos.writeObject(o);
oos.flush();
oos.close();
}
catch(IOException e) { System.out.println(e.getMessage()); }
}
Finally, I want to print the ArrayList's info:
ArrayList<Equipa> cena = new ArrayList<Equipa>();
cena=(ArrayList<Equipa>) readMyFile("Equipas.dat");
for(Equipa e:cena)
e.toString();
Error when I try to run:
" writing aborted; java.io.NotSerializableException: Equipa"
Equipa havs the Serializable:
import java.util.*;
import java.io.*;
public class Equipa implements Serializable
{
private String nome;
private Carro carro;
private ArrayList<Piloto> pilotos;
private double tempoDecorrido;
private int pontos;
private boolean desistiu;
private int voltaDesistencia;
private Piloto piloto;
/**
* Constructor for objects of class Equipa
*/
public Equipa()
{
this.nome = "NA";
this.carro = null;
this.pilotos = new ArrayList<Piloto>();
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
this.piloto = null;
}
public Equipa(String nome, Carro carro, ArrayList<Piloto> pilotos)
{
this.nome = nome;
this.carro = carro;
//this.pilotos = new ArrayList<Piloto>(pilotos);
this.pilotos = pilotos;
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
//this.piloto = pilotos.get(0);
}
public Equipa (Equipa e)
{
this.nome = e.getNome();
this.carro = e.getCarro();
this.pilotos = e.getPilotos();
this.tempoDecorrido = e.getTempoDecorrido();
this.pontos = e.getPontos();
this.desistiu = e.getDesistiu();
this.voltaDesistencia = e.getVoltaDesistencia();
//this.piloto = e.getPiloto();
}
/** Getters */
public String getNome()
{
return this.nome;
}
public Carro getCarro()
{
return this.carro;
}
public ArrayList<Piloto> getPilotos()
{
return new ArrayList<Piloto>(this.pilotos);
}
public double getTempoDecorrido()
{
return this.tempoDecorrido;
}
public int getPontos()
{
return this.pontos;
}
public boolean getDesistiu()
{
return this.desistiu;
}
public int getVoltaDesistencia()
{
return this.voltaDesistencia;
}
public Piloto getPiloto()
{
return this.piloto;
}
/** Setters */
public void setNome(String nome)
{
this.nome = nome;
}
public void setCarro(Carro carro)
{
this.carro = carro;
}
public void setPilotos(ArrayList<Piloto> pilotos)
{
this.pilotos = new ArrayList<Piloto>(pilotos);
}
public void setTempoDecorrido(double tempoDecorrido)
{
this.tempoDecorrido = tempoDecorrido;
}
public void setPontos(int pontos)
{
this.pontos = pontos;
}
public void setDesistiu(boolean desistiu)
{
this.desistiu = desistiu;
}
public void setVoltaDesistencia(int voltaDesistencia)
{
this.voltaDesistencia = voltaDesistencia;
}
public void setPiloto(Piloto piloto)
{
this.piloto = piloto;
}
/** Outros Métodos */
public Equipa clone()
{
return new Equipa(this);
}
public boolean equals(Equipa e)
{
if(this.nome == e.getNome())
return true;
else
return false;
}
public String getStringPilotos()
{
String s = new String();
for(Piloto p: this.pilotos)
s = (s + ", " + p.getNome());
return s;
}
public String toString()
{
return new String("Nome da equipa: " + nome + "; Categoria do carro: " + carro.getClass().getName() + "; Marca e modelo: " + carro.getMarca() + " " + carro.getModelo() + "; Pilotos: " + getStringPilotos())+"\n";
}
Implementing Serializable means that serialization is permitted, but not necessarily that it is possible. For it to work, everything referenced by Equipa must also be either primitive or Serializable (and so on, recursively). Is this the case?
Warning in the read function is the result of generics in java. You won't be able to suppress it, unless you use #SuppressWarnings("unchecked") to ignore it.
If you are sure you are reading an ArrayList<Equipa>, you can ignore it without any problem.
With the Equipa code, I can try to point to the Serializable problem: make sure that Carro and Piloto classes are also Serializables. You can add the code of theses classes if you are not sure.
The only type-safer way would be do a custom serialization, using writeObject(OutputStream) and readObjectInputStream say on a class ArrayListOfEquipa maybe using Equipa[] (ArrayList.toArray()).
Not really attractive, if the warning would be the only reason.