How to build a calendar view using data from ics file? - java

I am creating a PC program which is based on iCalendar format. I need to be able to get the data from a current ics file and display it as a calendar or at least something similar to calendar. I know how to get the data from ics file just don't have any idea how to easily use that data for displaying purposes.
Here is my starting code:
public void getCalendarData(File f) throws FileNotFoundException, IOException, ParserException
{
FileInputStream fin = new FileInputStream(f);
builder = new CalendarBuilder();
calendar = builder.build(fin);
}

One thing is ical4j, which is basically a utility that wraps the ICS format.
Another thing is a front end for a calendar/schedule :-)
But, lucky us, there's a nice JSF component with Primefaces, that you can use if a web interface is OK for you.
http://www.primefaces.org/showcase/ui/data/schedule.xhtml
Basically, what you need, is to just parse the data from ICS and feed the primefaces component data model (the link above has both the JSF and the managed bean example of how to use the component)
So you'd have to so something like this
private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");
#PostConstruct
private void loadIcs() {
eventModel = new DefaultScheduleModel();
CalendarBuilder builder = new CalendarBuilder();
try {
net.fortuna.ical4j.model.Calendar calendar = builder.build(this.getClass().getResourceAsStream("canada.ics"));
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component component = (Component) i.next();
//new event
Date start = SDF.parse(component.getProperty("DTSTART").getValue());
Date end = SDF.parse(component.getProperty("DTEND").getValue());
String summary = component.getProperty("SUMMARY").getValue();
eventModel.addEvent(new DefaultScheduleEvent(summary,
start, end));
System.out.println("added "+start+end+summary);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParserException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}

Not sure if you mean the actual GUI or getting the list of dates from an icalendar which is fairly complex given the RRULE properties. In ther first case, the choice is wide open (HTML, ...) in the later case there is an example here copied below :
// Reading the file and creating the calendar
CalendarBuilder builder = new CalendarBuilder();
Calendar cal = null;
try {
cal = builder.build(new FileInputStream("my.ics"));
} catch (IOException e) {
e.printStackTrace();
} catch (ParserException e) {
e.printStackTrace();
}
// Create the date range which is desired.
DateTime from = new DateTime("20100101T070000Z");
DateTime to = new DateTime("20100201T070000Z");;
Period period = new Period(from, to);
// For each VEVENT in the ICS
for (Object o : cal.getComponents("VEVENT")) {
Component c = (Component)o;
PeriodList list = c.calculateRecurrenceSet(period);
for (Object po : list) {
System.out.println((Period)po);
}
}

Related

doInBackground() stops and doesn't finish

I write a swing GUI application and I use a button. If I click on a button, my application needs to do some online request. I want to set a "Please wait" JPanel at this time. So I use the SwingWorker. It is all working. The doInBackground() method starts but it didn't finish.
I debugged the application and I see that if I create a new object, the application goes into a class FutureTask.java and call the method run(), after this it goes into ThreadPoolExecutor.java into the runWorker method and the thread stops there.
private void buttonBuchenActionPerformed(java.awt.event.ActionEvent evt) {
mainProg.showInfoWithoutButton(80000, "Please wait", mainProg.getPanel_first());
startPayment();
}
After a click on the button i change the Panel with the showInfoWithoutButton Methode. After the Panel is changed the startPayment() method starts.
public void startPayment() {
new SwingWorker<Void, Void>() {
#Override
public Void doInBackground() {
Calendar cal = Calendar.getInstance();
DateFormat formatDb = new SimpleDateFormat("yyyy-MM-dd");
Date date1;
try {
date1 = formatDb.parse(mainProg.getFreeRoom().getAbreiseBeds());
cal.setTime(date1);
cal.add(Calendar.DAY_OF_MONTH, -1);
} catch (ParseException ex) {
Logger.getLogger(EnterConfirmation.class.getName()).log(Level.SEVERE, null, ex);
}
String date = formatDb.format(cal.getTime());
try {
boolean paymentSuccess;
if(mainProg.getConfig().getString("terminal").equals("true")){
mainProg.getOpp().connectOpp();
paymentSuccess = mainProg.getOpp().startPayment(mainProg.getFreeRoom().getPriceGesamt(), mainProg);}
else paymentSuccess = true;
DBController db = new DBController();
db.initDBConnection();
//numberOfAvailbility is the unit.
String numberOfAvailbility = db.getQtyOfAvailbilityFromID(mainProg.getFreeRoom().getId());
if(paymentSuccess == true){
//----------------------------------
// HERE IT GOES TO FutureTask.java and the methode finish:
JsonNewBooking a = new JsonNewBooking(mainProg.getFreeRoom().getId(), 1, mainProg.getFreeRoom().getAnreiseBeds(), date, mainProg.getFreeRoom().getGuestnr(), mainProg.getBooking().getName(), mainProg.getBooking().getEmail(), mainProg.getBooking().getStreet(), mainProg.getBooking().getPlace(), mainProg.getBooking().getLand(), String.valueOf(mainProg.getFreeRoom().getPriceGesamt()));
//----------------------------------
String bookid = a.setBookingToBeds();
if(mainProg.getConfig().getString("terminal").equals("1"))
mainProg.getOpp().printReceipt(paymentSuccess);
if (!bookid.equals("null")) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date checkInDay = simpleDateFormat.parse(mainProg.getFreeRoom().getAnreiseBeds());
Date todayDate = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
if (checkInDay.compareTo(todayDate) == 0) {
System.out.println(bookid);
//ReturnKeyWithoutTerminal because was 100% paid already
gui.return.returnWithoutTerminal(mainProg, bookid);
mainProg.getFreeRoom().reset();
mainProg.getBooking().reset();
mainProg.getPanel_bookNow().resetAll();
mainProg.resetPanel();
mainProg.getBackToMainPanelTimer().stop();
} else {
mainProg.getFreeRoom().reset();
mainProg.getFreeRoom().reset();
mainProg.getPanel_bookNow().resetAll();
mainProg.resetPanel();
mainProg.getBackToMainPanelTimer().stop();
}
} catch (ParseException ex) {
Logger.getLogger(EnterConfirmation.class.getName()).log(Level.SEVERE, null, ex);
}
}
}else
mainProg.getOpp().printReceipt(paymentSuccess);
} catch (IOException ex) {
Logger.getLogger(EnterConfirmation.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}}.execute();
}
Normally the method should finish normally but it stops at the line where I create the object "a" (sorry for the bad name).
Maybe someone have an idea why it calls the class FutureTask.java and the ThreadPoolExecutor.java and stops the doInBackground method.

Export data generated in JPanel to excel

I have a Java Application that creates a JPanel menu and part of the program is to export data provided by the user inside JPanel to excel.
I want to create excel file and provide certain formatting inside my program.
I have tried using Apache POI, my code for the function is below. The function is called with a press of a button inside the JPanel when the application is running.
private static void processExcelInformation() throws FileNotFoundException
{
JOptionPane.showMessageDialog(panel, "stuck before workbook", "Display",
JOptionPane.WARNING_MESSAGE);
HSSFWorkbook workbook = new HSSFWorkbook(); // <---- I cannot seem to initialize new workbook
JOptionPane.showMessageDialog(panel, "created workbook", "Display",
JOptionPane.WARNING_MESSAGE); // <---- This message is not displayed when the application runs
HSSFSheet sheet = workbook.createSheet("Sample sheet");
JOptionPane.showMessageDialog(panel, "created sheet", "Display",
JOptionPane.WARNING_MESSAGE);
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) { // <---- This statement does not allow the application to run, I get an error
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
JOptionPane.showMessageDialog(panel, "stuck before xls", "Display",
JOptionPane.WARNING_MESSAGE);
FileOutputStream out =
new FileOutputStream(new File("new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
JOptionPane.showMessageDialog(panel, "Excel written", "Display",
JOptionPane.WARNING_MESSAGE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Check for comments where I have issues with my code.
Maybe someone can recommend me another way to complete my task or provide me a solution to my issues.
Thanks
Here's more to my code...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
soccerStock = new ArrayList<Soccer>();
childrenStock = new ArrayList<Children>();
miniSoccerStock = new ArrayList<MiniSoccer>();
tennisStock = new ArrayList<Tennis>();
universalStock = new ArrayList<Universal>();
try {
// processExcelInformation();
parseXMLInput();
initializeGrassChoices();
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calculator ex = new Calculator();
ex.setVisible(true);
}
});
}
public Calculator() {
initUI();
}
public final void initUI() {
initGrassRollChoices();
initPanel();
createMenu();
}
This is the button that calls processExcelInformation() function...
JMenuItem xls = new JMenuItem("Excel", null);
xls.setMnemonic(KeyEvent.VK_E);
xls.setToolTipText("Export Excel");
xls.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
processExcelInformation();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
When I call processExcelInformation() during compilation from main function it creates the excel file as asked. However, when I write my code to call processExcelInformation() function using a button I get an error when launching my application.
There is an open source package called Jexcel which might provide the tools you need. See this Source Forge site for the source packages. For tutorials and API docs you can look here.
Additional: I've just read some reviews. Seems JExcel doesn't enjoy a very good rep and doesn't support xlsx format.
Looking at your code I can see that there may be a problem with the for-loop you've indicated. You haven't mentioned what the error is, but I suspect you cannot simply treat an array as a collection. I'd be inclined to try something more traditional like this:
for (int i = 0; i < objArr.length; i++){
...
}
Take a look at JExcel. It´s pretty easy to use if you don´t need overly complicated spreadsheets and there are a lot examples and HowTos if you ask our friend Google.

Finding the cluster that an instance got assigned to with Weka

Im using an EM clusterer with an AddCluster Filter in order to see what instances are getting assigned to the different clusters after training. Below is the code that I'm using. I'm faily sure that I am applying the filter correctly but once I have the new Instances I still dont know how to get the cluster info from them. Im sure its just a simple getBlah() call but I'm just not locating it. Thanks in advance.
public Cluster()
{
clusterer = new EM();
filter = new AddCluster();
try
{
clusterer.setMaxIterations(100);
clusterer.setNumClusters(20);
filter.setClusterer(clusterer);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void buildCluster(String fileName)
{
try
{
DataSource source = new DataSource(fileName);
inst = source.getDataSet();
filter.setInputFormat(inst);
inst = AddCluster.useFilter(inst, filter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
I think you should use "Dictionary" Class. Here is my example code:
Enumeration clusteredInst = data_to_use.enumerateInstances();<br>
Dictionary<Integer, ArrayList<Instance>> clusteredSamples = new ashtable<>();
while (clusteredInst.hasMoreElements()) {<br>
Instance ins = (Instance) clusteredInst.nextElement();<br>
int clusterNumb = em.clusterInstance(ins);<br>
ArrayList<Instance> cls = null;<br>
cls = clusteredSamples.get(clusterNumb);<br>
if (cls != null) {<br>
cls.add(ins);<br>
} else {<br>
cls = new ArrayList<>();<br>
cls.add(ins);<br>
//you add elements to dictionary using put method<br>
//put(key, value)<br>
clusteredSamples.put(clusterNumb, cls);<br>
}
}
And you also can retrieval your data from dictionary by call it's Key.

Online Java-Code analyser

Does somebody know if there is a online code analyser for java. I would like to be able to check some small pieces of code.
Ex: this method has this warning: (Null Dereference)
private XMLGregorianCalendar asXMLGregorianCalendar(Date data) {
DatatypeFactory dateformat = null;
try {
dateformat = DatatypeFactory.newInstance();
} catch (MyException e) {
///
}
if (data == null) {
return null;
} else {
GregorianCalendar gregorianCal = new GregorianCalendar();
gregorianCal.setTimeInMillis(data.getTime());
return dateformat.newXMLGregorianCalendar(gregorianCal );
}
}
My new version is :
private XMLGregorianCalendar asXMLGregorianCalendar(Date data) throws ComponentBlockingException {
if (data == null) {
return null;
}
DatatypeFactory dateformat = null;
try {
dateformat = DatatypeFactory.newInstance();
} catch (MyException e) {
////
}
GregorianCalendar gregorianCal = new GregorianCalendar();
gregorianCal.setTimeInMillis(data.getTime());
return dateformat.newXMLGregorianCalendar(gregorianCal );
}
}
I think the second way should be ok.
I am not sure about any available online code anlayzer tool but let me try to help you with your code analysis.
If due to some reason following try block hits an an exception
try {
dateformat = DatatypeFactory.newInstance();
}
then your dateformat will remain null. So the following statement
return dateformat.newXMLGregorianCalendar(gregorianCal );
is prone to null pointer exception. And hence i believe you are getting static code anlayzer error.
You have to make sure dateformat is initialized or non-null in all the case before code reaches the line where you are doing the return.
Hope it helps!

Is there a cleaner way to write this polling loop?

I am writing automated test cases in Selenium/WebDriver in java. I have the following code implemented to poll for existing WebElements, but as I am not an expert in Java I was wondering if there is a cleaner way to write this method:
/** selects Business index type from add split button */
protected void selectBusinessLink() throws Exception
{
Calendar rightNow = Calendar.getInstance();
Calendar stopPolling = rightNow;
stopPolling.add(Calendar.SECOND, 30);
WebElement businessLink = null;
while (!Calendar.getInstance().after(stopPolling))
{
try
{
businessLink = findElementByLinkText("Business");
businessLink.click();
break;
}
catch (StaleElementReferenceException e)
{
Thread.sleep(100);
}
catch (NoSuchElementException e)
{
Thread.sleep(100);
}
catch (ElementNotVisibleException e)
{
Thread.sleep(100);
}
}
if (businessLink == null)
{
throw new SystemException("Could not find Business Link");
}
}
This particular line is what makes me think the code is a little dirty:
while (!Calendar.getInstance().after(stopPolling))
You can do something like this
long t = System.currentMillis(); // actual time in milliseconds from Jan 1st 1970.
while (t > System.currentMillis() - 30000 ) {
...
How about using the System time in millis?
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
long stopPollingTime = calendar.getTimeInMillis();
while (System.currentTimeMillis() < stopPollingTime) {
System.out.println("Polling");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}

Categories