ResourceDateParser { public static Date getFromDate(String from, String to, String days) { if (days != null && !days.trim().equals("") && (to != null && !to.trim().equals("") || from != null && !from.trim().equals(""))) { throw new BadRequestException( "You can use either the to/from date parameters or the number of days parameter, but not both" ); } Date daysDate = null; if (days != null && !days.trim().equals("")) { long mills = 1000L * 60 * 60 * 24; int number = Integer.parseInt(days); daysDate = new Date(new Date().getTime() - (number * mills)); } Date fromDate = null; if (daysDate != null) { fromDate = daysDate; } else { fromDate = parseDateString(from); } return fromDate; } private  ResourceDateParser(); static Date getFromDate(String from, String to, String days); static Date parseDateString(String activeOn);  }
@Test(expected = BadRequestException.class) public void errorFromAndToPlusDays() { ResourceDateParser.getFromDate("2012/01/01", "2012/10/10", "3"); }
@Test(expected = BadRequestException.class) public void errorFromPlusDays() { ResourceDateParser.getFromDate("2012/01/01", null, "3"); }
@Test(expected = BadRequestException.class) public void errorToPlusDays() { ResourceDateParser.getFromDate(null, "2012/01/01", "3"); }
@Test public void onlyDays() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -3); int expected = cal.get(Calendar.DATE); Date from = ResourceDateParser.getFromDate(null, null, "3"); cal.setTime(from); assertEquals(expected, cal.get(Calendar.DATE)); }
@Test public void allEmpty() { assertNull(ResourceDateParser.getFromDate(null, null, null)); assertNull(ResourceDateParser.getFromDate("", "", "")); assertNull(ResourceDateParser.getFromDate(null, null, "")); assertNull(ResourceDateParser.getFromDate(" ", " ", " ")); assertNull(ResourceDateParser.getFromDate("", "", null)); }
@Test public void fromAndTo() { Date from = ResourceDateParser.getFromDate("2012-01-01", "2012-01-10", null); Calendar cal = Calendar.getInstance(); cal.setTime(from); assertEquals(1, cal.get(Calendar.DATE)); }
@Test(expected = NumberFormatException.class) public void nonNumberForDays() { ResourceDateParser.getFromDate(null, null, "ABC"); }