I'm creating a GUI, and I use a method "getStudentInfo()" of the Student object return data type to retrieve information from the JTextFields and storing them into the "student" object.
public Student getStudentInfo() {
Student student = new Student();
String name = jtfName.getText();
student.setName(name);
String idNumber = jtfIDNumber.getText();
student.setIdNumber(idNumber);
String address = jtfAddress.getText();
student.setAddress(address);
String phoneNumber = jtfPhoneNumber.getText();
student.setPhoneNumber(phoneNumber);
String major = jtfMajor.getText();
student.setMajor(major);
return student;
}
Then, in a different class, I create an "Add" button that, when clicked, is supposed to add the "student" object into an ArrayList, and then write the ArrayList into a binary file.
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
File studentFile = new File(FILENAME);
ArrayList<Student> studentList = new ArrayList<Student>();
studentList.add(text.getStudentInfo());
try {
FileOutputStream fos = new FileOutputStream(studentFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
}
catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
But when I run the program and I write a student's info and add it to the binary file, then I go to add another student, it overwrites the previous student's info completely. Any help would be greatly appreciated.
In the actionPerformed method of your class, AddButtonListener, you have the following line of code:
FileOutputStream fos = new FileOutputStream(studentFile);
This constructor will open the file so bytes are written to the beginning of your file. Since you reopen this file each time the button is clicked, you are replacing the file contents with new data. Instead, use the constructor with the boolean parameter for appending bytes rather than overwriting...
FileOutputStream fos = new FileOutputStream(studentFile, true);
You can check out this constructor's details in the java documentation...
FileOutputStream constructor documentation
Related
I need to create the Structure and Template progrmatically through java code.I used following code snippets.
Structure:
public void createStructure(String userName,long userId){
log_.info("Inside create structure ");
long structureId=115203;
DDMStructure ddmStructure=DDMStructureLocalServiceUtil.createDDMStructure(structureId);
ddmStructure.setName("MigrationStructure");
ddmStructure.setDescription("This Structure created programatically");
ddmStructure.setUserId(userId);
ddmStructure.setUserName(userName);
File fXmlFile = new File("D:/FilesDataMigration/structure.xml");
try {
Document document = SAXReaderUtil.read(fXmlFile);
ddmStructure.setDocument(document);
DDMStructureLocalServiceUtil.addDDMStructure(ddmStructure);
}catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log_.info("Inside create structure done");
}
Template:
public void createTemplate(String userName,long userId){
log_.info("Inside create template ");
long templateId=12504;
DDMTemplate ddmTemplate=DDMTemplateLocalServiceUtil.createDDMTemplate(templateId);
ddmTemplate.setName("MigrationTemplate");
ddmTemplate.setDescription("This Template created programatically");
ddmTemplate.setUserId(userId);
ddmTemplate.setUserName(userName);
try {
BufferedReader br = new BufferedReader(new FileReader("D:/FilesDataMigration/template.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String script = sb.toString();
ddmTemplate.setScript(script);
DDMTemplateLocalServiceUtil.addDDMTemplate(ddmTemplate);
}catch(IOException e){
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log_.info("Inside create template done");
}
The above snippets are executing properly with out any exceptions But unable to see in the content section of Control Panel.Suggest me if anything wrong
There are couple of issues with your code:
You are not setting all the required properties, like groupId, companyId, classNameId, structureKey, dates etc.
There isn't any setName and setDescription method for DDMStructure or DDMTemplate accepting String argument (Liferay 6.2 GA2). Instead, there are only setNameMap and setDescriptionMap methods for both accepting Map<Locale, String>.
Use dynamic ids (structureId and templateId) in place of hard-coded ids, as following:
DDMStructure ddmStructure = DDMStructureUtil.create(CounterLocalServiceUtil.increment());and
DDMTemplate ddmTemplate = DDMTemplateUtil.create(CounterLocalServiceUtil.increment());
For classNameId, you can get it using it's value, like:
ClassName className = ClassNameLocalServiceUtil.getClassName("com.liferay.portlet.journal.model.JournalArticle");
long classNameId = className.getClassNameId();
Also, better to use update over populated object in place of adding:
DDMStructureUtil.update(ddmStructure);
and
DDMTemplateUtil.update(ddmTemplate);
Additionally, if you have access to the ThemeDisplay object, you can get groupId, companyId, userId, userFullName from it. Also, set new Date() for createDate and modifiedDate properties.
I'm using Wicket (not sure if it matters) but I'm using Workbook to create an excel file for a user to download. But I'm not sure how exactly to do this. What I would like to happen is the user clicks the button, a log is created and a prompt is given to the user to open (and save to temp files) or to save to their computer. The file is then deleted from the server side, or maybe it is stored in the User's session and deleted at end of session.
Can someone point me in the right direction? If I can have the file not saved in the session at all, that'd be create and have it just have it sent to the client using FileOutputStream somehow..
here is my current code:
private void excelCreator()
{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("SSA User ID " + currentSSAIDSelection2.getSsaUserId()));
Iterator<AuditLogEntry> auditLogEntrys = logList.iterator();
int i = 0;
while (auditLogEntrys.hasNext())
{
final AuditLogEntry auditLogEntry = auditLogEntrys.next();
Row row = sheet.createRow(i);
row.createCell(0).setCellValue(auditLogEntry.getTimeStamp());
row.createCell(1).setCellValue(auditLogEntry.getSourceName());
row.createCell(2).setCellValue(auditLogEntry.getCategory());
row.createCell(3).setCellValue(auditLogEntry.getSsaAdmin());
row.createCell(4).setCellValue(auditLogEntry.getAction());
i++;
}
try
{
FileOutputStream output = new FileOutputStream("ssaUserIDAccess.xls");
workbook.write(output);
output.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
You would have to create a DownloadLink with the temporary file as input. The temporary File must be deleted after download (file.delete())).
Alternatively you can try this:
IResourceStream stream = new ByteArrayResourceStream(data, "application/vnd.ms-excel");
RequestCycle.get().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(stream, filename).setContentDisposition(ContentDisposition.ATTACHMENT));
In this case data is the byte[] content of your workbook which can be for example retrieved with output.toByteArray().
In case anyone runs into this problem here is my solution. There wasn't a lot of straight forward answers on this but this is my solution:
My excelCreator method handles the creation of the excel Sheet, and returns it as a file.
private File excelCreator()
{
Workbook workbook = new HSSFWorkbook();
File excelfile = new File("userIDAccess.xls");
logList = getServer().findAuditLogs(getUserId(), null);
Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("User ID " + getUserId()));
Iterator<AuditLogEntry> auditLogEntrys = logList.iterator();
int i = 0;
while (auditLogEntrys.hasNext())
{
final AuditLogEntry auditLogEntry = auditLogEntrys.next();
Row row = sheet.createRow(i);
row.createCell(0).setCellValue(auditLogEntry.getTimeStamp());
row.createCell(1).setCellValue(auditLogEntry.getSourceName());
row.createCell(2).setCellValue(auditLogEntry.getCategory());
row.createCell(3).setCellValue(auditLogEntry.getSsaAdmin());
row.createCell(4).setCellValue(auditLogEntry.getAction());
i++;
}
try
{
FileOutputStream output = new FileOutputStream(excelfile);
workbook.write(output);
output.close();
}catch(Exception e)
{
e.printStackTrace();
}
return excelfile;
}
IModel excelFileModel = new AbstractReadOnlyModel()
{
public Object getObject()
{
return excelCreator();
}
};
I created an IModel to capture the file created inside my excelCreator() method and returned.
auditDownloadlink = new DownloadLink("auditDownloadlink", excelFileModel);
I pass the I.D. of the download link, and then pass the imodel.
finally,
I call,
auditDownloadlink.setDeleteAfterDownload(true);
auditDownloadlink.setCacheDuration(Duration.NONE);
This deletes the file after it is created. And the cache setting is a setting to make sure it is compatible with all browsers (That's how I interpreted it, but you may not need it).
The Imodel creates the File on the fly so it doesn't have to be stored anywhere, and then the file is deleted once it is downloaded.
Hope this helps someone!
You could create a Resource to do this, and make a ResourceLink.
public class ExcelProducerResource extends AbstractResource
{
public ExcelProducerResource()
{
}
#Override
protected ResourceResponse newResourceResponse( Attributes attributes )
{
final String fileName = getFileName();
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
resourceResponse.setCacheDuration( Duration.NONE );
resourceResponse.setFileName( fileName );
resourceResponse.setWriteCallback( new WriteCallback()
{
#Override
public void writeData( Attributes attributes ) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
writeToStream( outputStream );
outputStream.close();
}
} );
return resourceResponse;
}
void writeToStream(OutputStream outputStream) throws IOException
{
//.. do stuff here :)
}
String getFileName()
{
//.. do stuff here :)
}
}
I developed RssFeed Application using LWUIT j2me(java) for 2 xml files, now I want to show those 2 xml files on LWUIT Tabs.
That means, when my application runs, default tab will be displayed (on that tab my first Rss xml file Titles should be displayed), and when the user click on tab2 my second Rss xml titles should be displayed.
I am able to display the same titles of one rss files on both the tabs, how to control my flow to achieve my task?
Here my code:
public class XMLMidlet extends MIDlet implements ActionListener {
public XMLMidlet() {
Display.init(this);
news = new Vector();
m_backCommand = new Command("Back");
cmdExit = new Command("EXIT");
cmdDetails = new Command("Details");
}
public void startApp() {
//RssFeed URL's
String urls[] = {"http://topnews-23.rss",
"http://topstory-12.rss"};
for(int i=0;i<urls.length;i++){
ParseThread myThread = new ParseThread(this,urls[i]);
//this will start the second thread
myThread.getXMLFeed(urls[i]);
}
}
//method called by the parsing thread
public void addNews(News newsItem,String url) {
try{
news.addElement(newsItem);
form1 = new Form();
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
form1.addComponent(tabs);
form1.show();
}
catch(Exception e){
e.printStackTrace();
}
}
You should move below code
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
form1 = new Form();
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
from addNews method to constructor XMLMidlet. addNews method should use url parameter to differ for which list the newsItem is directed.
Update
Below is how I think you should implement addNews method:
public void addNews(News newsItem, String url) {
if (url.endsWith("topnews-20.rss")) {
myNewsList.addElement(newsItem);
} else if (url.endsWith("topstory-25.rss")) {
newsList.addElement(newsItem);
}
}
serRenderer does not need to be called from addNews and form1.show() should be moved to startApp.
I am trying to read a file of tokens, here is my code:
public class Prac1 {
public static void main(String[] args) {
try{ //File file = new File();
BufferedReader reader = null;
HashMap<String,String> symbolTable = new HashMap<String,String>();
//reader = new BufferedReader(new FileReader(file));
Scanner scan = new Scanner(
new BufferedReader(
new FileReader("/Users/Documents/Lab1/testCase1.txt")));
while(scan.hasNext()){
String i= scan.next();
System.out.println("test--->"+i);
}
}catch(Exception e){
}
}
}
*The file reads tokens but at the beginning and at the end of output it gives garbage value.*I want to eliminate these values.
Change your text preferences to plain text.
In Mac go to text -> preferences -> plain text option
Then create a new text file and it should work!
I tried the demo code in demo project but I can't add new item successfully.
It just add new new NULL group and NULL item.
Please give me an simple example code to add new item (text and image).
Thank you!
Oh sorry! I forgot it. This is the first time I participate in this site.
I use C#. And the code is:
objectListView1.BeginUpdate();
objectListView1.AddObject(new string [] {"Hello","dfdsF" });
objectListView1.EndUpdate();
and
objectListView1.BeginUpdate();
OLVListItem item = new OLVListItem(new string [] {"Hello","dfdsF" });
objectListView1.Items.Add(item);
objectListView1.EndUpdate();
It's so different form ListView and EXListView which I can define a text or a image when creating new item. But in ObjectListView, I don't understand OBJECT?
I get ObjectListView anh it's demo code form here http://nchc.dl.sourceforge.net/project/objectlistview/objectlistview/v2.5/ObjectListViewFull-2.5.0.zip
I will show you what to do to add items. Try to create a class, then make getters and setters for the properties you want to show on your ObjectListView.
SetObjects method takes a List<T>:
public Form1()
{
InitializeComponent();
this.objectListView1.SetObjects(haha.GET());
}
Now this is my class, I called it haha, I've two properties in it (Name and Detail):
class haha
{
string name;
string detail;
public haha(string name , string detail)
{
this.name = name;
this.detail = detail;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Detail
{
get { return detail; }
set { detail = value; }
}
static internal List<haha> GET()
{
haha item = new haha("zeko", "dunno");
haha xx = new haha("sheshe", "dunno");
haha ww = new haha("murhaf", "dunno");
haha qq = new haha("soz", "dunno");
haha ee = new haha("HELLO", "dunno");
List<haha> x = new List<haha>();
x.Add(item);
x.Add(xx);
x.Add(ww);
x.Add(qq);
x.Add(ee);
return x;
}
}
Now
change ShowGroups in ObjectListView to false
then add the columns that you want; I've added two columns, one for Name and one for Detail
and as in the picture when you add a column, see the AspectName and write exactly the same name of its property that you want to show from your class
Here's the result:
If you want to use AddObject(), which takes an object, I'd write this:
private void button1_Click(object sender, EventArgs e)
{
haha newObject = new haha("memo","zezo");
objectListView1.AddObject(newObject);
}
Happy coding :)
The best thing is to use an entity class. Then make a list of items and add this list to your ObjectListView.
myObjectListView.SetObjects(myListofEntityItems);
But before you do that, you have to setup the columns in your designer. Just add a column, and in the field AspectName enter the exact name of the attribute of your entity item.