Using getText() with LocalDate Java - java

I'm making a GUI in java for a todo list and i want to write a todo type object in a file. A todo object has name, description and a date that determinds this to be done. With GUI a user can add as many todo objects he wants with them be written to a file. I'm having trouble getting the date from user from a JTextField using getText() and parsing it in a LocalDate type object in order to be written in the file.
Code I'm running now:
//registration method
public void RegularObligationRegister(RegularObligations R) throws IOException {
try {
objOutObligations.writeObject(R);
JOptionPane.showMessageDialog(null, "Save Success");
System.out.println(R);
objOutObligations.flush();
} catch (FileNotFoundException ex) {
System.out.println("Error with specified file . . .");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//actionperformed method
#Override
public void actionPerformed(ActionEvent ae) {
.
.
.
if (ae.getSource().equals(REntryObligationSave)) {
RegularObligations R = new RegularObligations(RegularEntry_TextObligationName.getText(),
RegularEntry_TextObligationDescription.getText(),
LocalDate.parse(RegularEntry_TextObligationDeadline.getText()));
try {
this.RegularObligationRegister(R);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
RegularEntry_TextObligationName.setText(null);
RegularEntry_TextObligationDescription.setText(null);
RegularEntry_TextObligationDeadline.setText(null);
}

You need to make sure that your text must be valid LocalDate.parse() method to parse. You need to specify your text format for the LocalDate. For ex: (dd MMM uuuu). Then you should pass your text and formatter to the LocalDate.parse() method as parameter. The example below will help you to parse a String similar to : "31 Dec 2018" as a LocalDate
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM uuuu");
LocalDate.parse(RegularEntry_TextObligationDeadline.getText(),formatter));
You can check DateTimeFormatter to customize your datetype as a text DateTimeFormatter

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.

SonarQube complains: Either log or rethrow this exception

I am running SonarQube 5 for code quality check after integrating the code with Maven.
Sonar is complaining that I should:
Either log or rethrow this exception.
in following piece of code:
public static Date convertStringtoDate(String stringDate) {
stringDate = StringUtils.trimToNull(stringDate);
SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy");
Date date = null;
if (stringDate != null) {
try {
date = dfm.parse(stringDate);
} catch (Exception e) {
logger.info("Cannot convert String to Date: ",convertStringtoDate(e.getMessage()));
}
}
return date;
}
What am I missing here?
First of all, is this behaviour correct? Seems a bit weird that you are trying to call convertStringtoDate on the exception message as well.
Secondly, I had the same problem with Sonar recently. Seems like you need to pass the whole exception as a parameter to the logger, instead of e.getMessage() for Sonar to realize you are logging the exception.
Try this instead:
public static Date convertStringtoDate(String stringDate){
stringDate = StringUtils.trimToNull(stringDate);
SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy");
Date date = null;
if(stringDate!=null){
try {
date = dfm.parse(stringDate);
} catch (Exception e) {
logger.info("Cannot convert String to Date: ", e);
}
}
return date;
}

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

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

Cannot convert my String to Date

i was searching how to convert a string to a date, so i've found some examples on stacko. . So i used SimpleDateFormat and tried to parse but my compiler (Gradle from AndroidStudio) send me this error : Unhandled exception : java.text.ParseException.
There is my code :
public static int compareDate(String sdate1, String sdate2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
Date date1 = simpleDateFormat.parse(sdate1); // there is the error
[...]
}
Why is there an error? Someone can explain that to me?
I'm a beginner in java and i'm sorry for my bad english, and i hope someone can help me on this.
Thanks
The parse method throws a ParseException. You need to insert a catch block or your method should throw ParseException in order to get rid of the error:
public static int compareDate(String sdate1, String sdate2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
try {
Date date1 = simpleDateFormat.parse(sdate1);
} catch (ParseException e) { // Insert this block.
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OR
public static int compareDate(String sdate1, String sdate2) throws ParseException{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
Date date1 = simpleDateFormat.parse(sdate1);
}

Face error with XMLGregorianCalendar

I am working on a Java web base project, where I am using web service to access date and update the date, my screen has a date field, which I need to update with the data acquired form the web service, but the web service date is of type XMLGregorianCalendar.
This is what I have:
public class Testing {
/**
* #param args
*/
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
try {
date = (Date)df.parse("5-5-2012");
System.out.println("Date Date" + date);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(date);
System.out.println(""+gregory);
XMLGregorianCalendar calendar =null;
try {
calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregory);
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
calendar.setTimezone( DatatypeConstants.FIELD_UNDEFINED );
someDoa.setdate(calendar);
}
}
But the result is:
SEVERE: Servlet.service() for servlet default threw exception
javax.xml.ws.soap.SOAPFaultException: java.lang.IllegalArgumentException: Incorrect Offset :Incorrect Offset :needs a leading +/- sign

Categories