/** 
 * Simple Dates, with Exception handling
 */

import java.lang.*;  // Integer
import java.util.*;
import java.util.zip.DataFormatException;

/**
 * @author Uwe Assmann
 * @date 2013-04-28
 * @url http://docs.oracle.com/javase/tutorial/essential/regex/index.html
 */


public class DateWithException {
    int day = 0; // initialized to 0, i.e., with a wrong postcondition
    /**
       Parse a day from a string in german date format.
       Use user-defined exceptions for error handling.
    */
    public int parse(String d) throws DataFormatException {
	if (d.equals(""))   throw new DateInvalid(); // precondition
 	if (d.length() < 10)  throw new DateTooShort(); // invariant
 	if (d.matches("\\d\\d.\\d\\d.\\d\\d\\d\\d")) {
	    // Format: 01.01.2018
 	    if (d.length() < 10)  throw new DateTooShort(); // invariant
	    day = Integer.parseInt(d.substring(0,2));
	    if (day < 1 || day > 31) throw new DayTooLarge(); // postcondition
	} else if (d.matches("\\d\\d.\\s\\d\\d.\\s\\d\\d\\d\\d")) {
	    // Format: 01. 01. 2018
	    day = Integer.parseInt(d.substring(0,2));
	    if (day < 1 || day > 31) throw new DayTooLarge(); // postcondition
	} else {
	    // ... fill in other format recognitions...
	}
 	if (d.length() < 10)  throw new DateTooShort(); // invariant
	if (day < 1 || day > 31) throw new DateWrong(d); // postcondition
	return day;
    }
    public int wrapperToShowExceptionHandler (String d)  throws DataFormatException {
	try {
 	    return this.parse(d);
	} catch (DateWrong ex) {
	    System.out.println("This is the wrapper's exception handler: Date WRONG"+ex.toString());
	    return 0;
	} catch (DataFormatException ex) {
	    //
	    System.out.println("This is the wrapper's exception handler: "+ex.toString());
	    return 0;
	}
    }
    // Main program. 
    public static void main(String args[]) {
	try {
	    DateWithException date = new DateWithException();
//   	    int resultDay = date.parse("31.12.2013"); 
//   	    int resultDay = date.parse("31. 12. 2013"); 
 	    int resultDay = date.wrapperToShowExceptionHandler("32.12 .2013"); 
	    System.out.println("Date parsed: "+resultDay);
	} catch (DataFormatException ex) {
	    System.out.println(ex.toString());
	}
    }
}

/**
   DateInvalid is an Exception class. An Exception object is allocated by
   calling the constructor fof the superclass super(String s).
   A return statement is not necessary in a constructor.
*/
class DateInvalid extends DataFormatException {
    public DateInvalid() {
	super("The given date string is empty");
    }
};
class DateTooShort extends DataFormatException {
    public DateTooShort() {
	super("The given date string is too short");
    }
};
class DayTooLarge extends DataFormatException {
    public DayTooLarge() {
	super("The given day must be in the range of 1..31");
    }
};
class DateWrong extends DataFormatException {
    public DateWrong(String day) {
	super("Date format wrong: "+day);
    }
};
