All posts by Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 12 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.

JAVA : Daylight Saving Time (DST) Handling


Pre-Requisite : Java : Date and Time Handling Tutorial

Most of the United States practice of advancing clock during summer month in order to leverage an additional hour of natural light(saving heating power, illumination power, enhancing the mood, and so on).

When clocks change time

In United States Daylight Saving Time begins at 2:00 a.m. on the second Sunday in March and reverts to standard time on the first Sunday in November. In United States each time zone switches clocks at different time.

Daylight Saving Time on time zone

In United States , When Daylight Saving Time are being followed in EST then it’s become EDT. These names just are abbreviation and having different meaning in different continents.
Ex:

  • IST : Indian Standard Time
  • IST : Irish Standard Time
  • IST : Israel Standard Time

For United States (Follow Day Light Saving)

Standard Time Daylight Savings Time
CST : Central Standard Time (North America) CDT : Central Daylight Time
EST : Eastern Standard Time (North America) EDT : Eastern Daylight Time
PST : Pacific Standard Time (North America) PDT : Pacific Daylight Time

Complete List of timezone abbreviations

Note : The 3-letter abbreviations should be wholeheartedly avoided in favor of TZDB zone IDs. EST is not time zone such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight saving time (DST). Whenever need to set time zone in code in the code always use proper time zone name in the “continent/region” format.

Complete List of time zone with continent/region

Example of Daylight Saving Time with Time Zone

In this example cover all the case for applying Daylight Saving Time on different time zone. Here I have try to apply with abbreviation, continent / region and show with standard time and Daylight saving time.

package datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

public class DayLightSavingExample {

	public static void main(String[] args) {
	/**
	* DST = Daylight Saving Time (Begins Daylight Saving Time at 2:00 a.m.
	* on the second Sunday in March and reverts to standard time on the
	* first Sunday in November)
	*/
	SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'+|-hh:mm");
	String strWithDLS = "03/10/2019"; // MM/DD/YYYY
	String strWithOutDLS = "03/11/2019";
	try {
	     Date dateWithDLS = sourceFormat.parse(strWithDLS);
	     Date dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
		System.out.println("Default Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
		System.out.println("Default Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

		/**
		* Set time zone with EST (No difference in time) because 3 letter
		* time zone not consider DST (Day light saving time)
		*/
		sourceFormat.setTimeZone(TimeZone.getTimeZone("EST"));
		dateWithDLS = sourceFormat.parse(strWithDLS);
		dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
		System.out.println("EST Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
		System.out.println("EST Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

		/**
		* Set time zone with America/New_York (1 hour difference in time)
		* when you need to use day light saving always use with
		* continent/region format.
		*/
			sourceFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("America/New_York")));
dateWithDLS = sourceFormat.parse(strWithDLS);
dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
System.out.println("America/New_York Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
System.out.println(
"America/New_York Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

} catch (ParseException ex) {
			ex.printStackTrace();
}

	}

}

Output :


Default Timezone with Day Light Saving :2019-03-10T00:00:00Z+|-12:00
Default Timezone without Day Light Saving :2019-03-11T00:00:00Z+|-12:00
EST Timezone with Day Light Saving :2019-03-10T10:30:00Z+|-10:30
EST Timezone without Day Light Saving :2019-03-11T10:30:00Z+|-10:30
America/New_York Timezone with Day Light Saving :2019-03-10T10:30:00Z+|-10:30
America/New_York Timezone without Day Light Saving :2019-03-11T09:30:00Z+|-09:30

 

Here i have tried to cover all the points as developer prospects. If you know more ways to handle it and any issues related to date and time please suggest in comments.

Advertisements

Java 8+ Date Time Exmples


Pre-Requisite : Java Date and Time Tutorial

In this below example try to cover all possible cases and operations with date and time with Java 8+ APIs.

import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjusters;
import java.time.zone.ZoneRulesException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Java8DateTime {

	public static void main(String[] args) {
		//LocalDate lastDay_2014 = LocalDate.of(2014, 12, 32);
		//LocalTime lastDay_2014 = LocalTime.of(12, 12, 23,-1);
		currentDateTime();
		instantAPI();
		GregorianCalendarAPI();
		TimeZoneAPI();
		dateTimeFormattingAndParsing();
		localDateAPI();
		localDateTimeAPI();
		localTimeAPI();

		System.out.println("*********Set Date and Time Manually***************");
		LocalDateTime dateTimePoint=LocalDateTime.now();
		// Set Date and Time manually
		LocalDate datePoint = LocalDate.of(2012, Month.DECEMBER, 12);
		System.out.println("Local Date :" + datePoint);
		// Days after 1970
		datePoint = LocalDate.ofEpochDay(150);
		System.out.println("Local Date :" + datePoint);
		// set String
		LocalTime timePoint = LocalTime.parse("10:15:30");
		System.out.println("Local Time :" + timePoint);
		// Set hours and minutes
		timePoint = LocalTime.of(13, 18);
		System.out.println("Local Time :" + timePoint);

		// Retrieve values
		System.out.println("*********Get Date and Time Values***************");
		datePoint = dateTimePoint.toLocalDate();
		Month month = dateTimePoint.getMonth();
		int day = dateTimePoint.getDayOfMonth();
		int year = dateTimePoint.getYear();
		int hour = dateTimePoint.getHour();
		int minute = dateTimePoint.getMinute();
		int second = dateTimePoint.getSecond();
		System.out.println("Local Date :" + datePoint);
		System.out.printf("Local Date time Format : %d/%d/%d %d:%d:%d", day, month.getValue(), year, hour, minute,
				second);
		System.out.println();
		System.out.println("*********Operation On LocalDate***************");
		// Operation on Local Date
		// Period of 1 year 3 month 2 days
		Period period = Period.of(1, 3, 2);
		LocalDate startDatePoint = datePoint.minus(period);
		System.out.println("Local Date :" + startDatePoint);
		LocalDate endDatePoint = datePoint.plus(period);
		System.out.println("Local Date :" + endDatePoint);

		System.out.println("*********Diffrence of On LocalDate***************");
		// Difference of Date
		Period daysPeriod = Period.between(startDatePoint, endDatePoint);
		System.out.println("Days :" + daysPeriod.getDays());
		System.out.println("Months :" + daysPeriod.getMonths());
		System.out.println("Years :" + daysPeriod.getYears());
		// Another Way
		long days = ChronoUnit.DAYS.between(startDatePoint, endDatePoint);
		long months = ChronoUnit.MONTHS.between(startDatePoint, endDatePoint);
		long years = ChronoUnit.YEARS.between(startDatePoint, endDatePoint);
		System.out.println("Days :" + days);
		System.out.println("Months :" + months);
		System.out.println("Years :" + years);

		// Duration

		// A duration of 3 seconds and 5 nanoseconds
		Duration duration = Duration.ofSeconds(3, 5);
		// Duration oneDay = Duration.between(Temporal., yesterday);

	}

	private static void currentDateTime() {
		System.out.println("*********Current Date and Time***************");

		// Current Date and Time
		LocalDateTime dateTimePoint = LocalDateTime.now();
		System.out.println("Local Date Time :" + dateTimePoint);
		// Current Date
		LocalDate datePoint = LocalDate.now();
		System.out.println("Local Date :" + datePoint);
		// Current Time
		LocalTime timePoint = LocalTime.now();
		System.out.println("Local Time :" + timePoint);

		// Get Instant from java.util.Date
		Instant timestamp = new Date().toInstant();
		System.out.println("Current Timestamp = " + timestamp);

		// java.util.Calendar to Instant
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);
	}

	private static void instantAPI() {
		System.out.println("*****************Instant API*******************");
		// Date to Instant
		Instant timestamp = new Date().toInstant();
		System.out.println("Current Timestamp = " + timestamp);
		// Now we can convert Instant to LocalDateTime or other similar classes
		LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
		System.out.println("Date = " + date);

		// Calendar to Instant
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);

		// Date API to Legacy classes
		Date dt = Date.from(Instant.now());
		System.out.println(dt);

		// Instant from timestamp
		Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
		System.out.println("Specific Time = " + specificTime);

		// Duration example
		Duration thirtyDay = Duration.ofDays(30);
		System.out.println(thirtyDay);
	}

	private static void localDateAPI() {
		System.out.println("*****************Local Date API*******************");
		LocalDate today = LocalDate.now();

		System.out.println("Current Date=" + today);

		// Creating LocalDate by providing input parameters.
		// Here are chnaces of getting DateTimeException if pass as Invalidate
		// Date format
		LocalDate firstDay_2016 = LocalDate.of(2016, Month.JANUARY, 1);
		System.out.println("Specific Date=" + firstDay_2016);

		try {
			// Here with throw DateTimeException if pass as Invalidate Date
			// format
			LocalDate lastDay_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
			System.out.println("Specific Date=" + lastDay_2014);
		} catch (DateTimeException ex) {
			ex.printStackTrace();
		}

		// Current date in "Asia/Kolkata", you can get it from ZoneId
		LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in CST=" + todayKolkata);

		try
		{
		// Will throw java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		LocalDate todayIST = LocalDate.now(ZoneId.of("IST"));
		}
		catch(ZoneRulesException ex)
		{
			ex.printStackTrace();
		}

		// Getting date from the base date i.e 01/01/1970
		LocalDate dateFromBase = LocalDate.ofEpochDay(365);
		System.out.println("365th day from base date= " + dateFromBase);

        //Get 100 th day of year
		LocalDate hundredDay2014 = LocalDate.ofYearDay(2016, 100);
		System.out.println("100th day of 2014=" + hundredDay2014);

		//Other APIs and Operation on LocalDate

		// Get the Year, check if it's leap year
		System.out.println("Year " + today.getYear() + " is Leap Year? " + today.isLeapYear());

		// Compare two LocalDate for before and after
		System.out.println("Today is before 01/01/2017? " + today.isBefore(LocalDate.of(2017, 1, 1)));

		// Get LocalDateTime from LocalDate
		System.out.println("Current Time=" + today.atTime(LocalTime.now()));

		// plus and minus operations
		System.out.println("20 days after today will be " + today.plusDays(20));
		System.out.println("5 weeks after today will be " + today.plusWeeks(5));
		System.out.println("30 months after today will be " + today.plusMonths(30));

		System.out.println("20 days before today will be " + today.minusDays(20));
		System.out.println("5 weeks before today will be " + today.minusWeeks(5));
		System.out.println("30 months before today will be " + today.minusMonths(30));

		// TemporalAdjusters for adjusting the dates
		LocalDate firstDayOfMonth=today.with(TemporalAdjusters.firstDayOfMonth());
		System.out.println("First date of this month= " + firstDayOfMonth);

		LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
		System.out.println("Last date of this year= " + lastDayOfYear);

		Period period = today.until(lastDayOfYear);
		System.out.println("Period Format= " + period);
		System.out.println("Months remaining in the year= " + period.getMonths());

	}

	private static void localTimeAPI() {
		System.out.println("*****************Local Time API*******************");
		// Current Time
		LocalTime time = LocalTime.now();
		System.out.println("Current Time=" + time);

		// Creating LocalTime by providing input arguments
		LocalTime specificTime = LocalTime.of(12, 20, 25, 40);
		System.out.println("Specific Time of Day=" + specificTime);

		// Try creating time by providing invalid inputs
		// LocalTime invalidTime = LocalTime.of(25,20);
		// Exception in thread "main" java.time.DateTimeException:
		// Invalid value for HourOfDay (valid values 0 - 23): 25

		// Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
		LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Time in IST=" + timeKolkata);

		// java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		// LocalTime todayIST = LocalTime.now(ZoneId.of("IST"));

		// Getting date from the base date i.e 01/01/1970
		LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
		System.out.println("10000th second time= " + specificSecondTime);

	}

	private static void localDateTimeAPI() {
		System.out.println("*****************Local Date Time API*******************");
		// Current Date
		LocalDateTime today = LocalDateTime.now();
		System.out.println("Current DateTime=" + today);

		// Current Date using LocalDate and LocalTime
		today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
		System.out.println("Current DateTime=" + today);

		// Creating LocalDateTime by providing input arguments
		LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
		System.out.println("Specific Date=" + specificDate);

		// Try creating date by providing invalid inputs
		// LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28,
		// 25,1,1);
		// Exception in thread "main" java.time.DateTimeException:
		// Invalid value for HourOfDay (valid values 0 - 23): 25

		// Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
		LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in IST=" + todayKolkata);

		// java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		// LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));

		// Getting date from the base date i.e 01/01/1970
		LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
		System.out.println("10000th second time from 01/01/1970= " + dateFromBase);

	}

	private static void dateTimeFormattingAndParsing() {
		System.out.println("*****************Local DateTime Formatting API*******************");
		// Format examples
		LocalDate date = LocalDate.now();
		// default format
		System.out.println("Default format of LocalDate=" + date);
		// specific format
		System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
		System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

		LocalDateTime dateTime = LocalDateTime.now();
		// default format
		System.out.println("Default format of LocalDateTime=" + dateTime);
		// specific format
		System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
		System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));

		Instant timestamp = Instant.now();
		// default format
		System.out.println("Default format of Instant=" + timestamp);

		// Parse examples
		LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
				DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
		System.out.println("Default format after parsing = " + dt);

	}

	private static void GregorianCalendarAPI() {
		System.out.println("*****************Gregorian Calendar API*******************");
		// ZonedDateTime from specific Calendar
		ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
		System.out.println(gregorianCalendarDateTime);

		GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
		System.out.println(gc);
	}

	private static void TimeZoneAPI() {
		System.out.println("*****************Time Zone API*******************");
		// TimeZone to ZoneId
		ZoneId defaultZone = TimeZone.getDefault().toZoneId();
		System.out.println(defaultZone);

		TimeZone tz = TimeZone.getTimeZone(defaultZone);
		System.out.println(tz);

	}

}

Output


*********Current Date and Time***************
Local Date Time :2019-05-16T11:50:59.302
Local Date :2019-05-16
Local Time :11:50:59.303
Current Timestamp = 2019-05-16T06:20:59.303Z
2019-05-16T06:20:59.358Z
*****************Instant API*******************
Current Timestamp = 2019-05-16T06:20:59.369Z
Date = 2019-05-15T23:20:59.369
2019-05-16T06:20:59.373Z
Thu May 16 11:50:59 IST 2019
Specific Time = 2019-05-16T06:20:59.369Z
PT720H
*****************Gregorian Calendar API*******************
2019-05-16T11:50:59.387+05:30[Asia/Calcutta]
java.util.GregorianCalendar[time=1557987659387,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2019,MONTH=4,WEEK_OF_YEAR=20,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=136,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=50,SECOND=59,MILLISECOND=387,ZONE_OFFSET=19800000,DST_OFFSET=0]
*****************Time Zone API*******************
Asia/Calcutta
sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null]
*****************Local DateTime Formatting API*******************
Default format of LocalDate=2019-05-16
16::May::2019
20190516
Default format of LocalDateTime=2019-05-16T11:50:59.551
16::May::2019 11::50::59
20190516
Default format of Instant=2019-05-16T06:20:59.551Z
Default format after parsing = 2014-04-27T21:39:48
*****************Local Date API*******************
Current Date=2019-05-16
Specific Date=2016-01-01
java.time.DateTimeException: Invalid date 'February 29' as '2014' is not a leap year
Current Date in CST=2019-05-16
365th day from base date= 1971-01-01
    at java.time.LocalDate.create(Unknown Source)
    at java.time.LocalDate.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:160)
    at datetime.Java8DateTime.main(Java8DateTime.java:34)
java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
    at java.time.zone.ZoneRulesProvider.getProvider(Unknown Source)
    at java.time.zone.ZoneRulesProvider.getRules(Unknown Source)
    at java.time.ZoneRegion.ofId(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:173)
    at datetime.Java8DateTime.main(Java8DateTime.java:34)
100th day of 2014=2016-04-09
Year 2019 is Leap Year? false
Today is before 01/01/2017? false
Current Time=2019-05-16T11:50:59.619
20 days after today will be 2019-06-05
5 weeks after today will be 2019-06-20
30 months after today will be 2021-11-16
20 days before today will be 2019-04-26
5 weeks before today will be 2019-04-11
30 months before today will be 2016-11-16
First date of this month= 2019-05-01
Last date of this year= 2019-12-31
Period Format= P7M15D
Months remaining in the year= 7
*****************Local Date Time API*******************
Current DateTime=2019-05-16T11:50:59.620
Current DateTime=2019-05-16T11:50:59.620
Specific Date=2014-01-01T10:10:30
Current Date in IST=2019-05-16T11:50:59.620
10000th second time from 01/01/1970= 1970-01-01T02:46:40
*****************Local Time API*******************
Current Time=11:50:59.620
Specific Time of Day=12:20:25.000000040
Current Time in IST=11:50:59.620
10000th second time= 02:46:40
*********Set Date and Time Manually***************
Local Date :2012-12-12
Local Date :1970-05-31
Local Time :10:15:30
Local Time :13:18
*********Get Date and Time Values***************
Local Date :2019-05-16
Local Date time Format : 16/5/2019 11:50:59
*********Operation On LocalDate***************
Local Date :2018-02-14
Local Date :2020-08-18
*********Difference of On LocalDate***************
Days :4
Months :6
Years :2
Days :916
Months :30
Years :2

Above solutions are my search to perform all type of operations with date and time with java 8 API generally face while development. If you face other issue apart from it. Please mention in comments that will help with others.

[Solved] Could not transfer artifact org.springframework:XYZ from/to central (https://repo.maven.apache.org/maven2)


Generally this error message shows in pom.xml when create new project with dependencies or add new dependencies in pom.xml.

Reason to cause this error

There are several reason to cause this error as below because maven is unable to connect to Maven repository at http://repo1.maven.org/maven2.

  1. Proxy
  2. Network issue
  3. .lastUpdate file for dependency

Could not transfer artifact org.springframework:spring-expression:jar:5.1.6.RELEASE from/to central (https://repo.maven.apache.org/maven2): C:\Users\saurabh.gupta1\.m2\repository\org
 \springframework\spring-expression\5.1.6.RELEASE\aether-fa07bf3e-4fa1-4911-bcad-3319e4b2480e-spring-expression-5.1.6.RELEASE.jar-in-progress (The system cannot find the file 
 specified) org.eclipse.aether.transfer.ArtifactTransferException:
 

Solutions

There are few ways i find out to resolve this issue:

Maven Force Update of Snapshot/Releases

Follow below steps to to resolve this issue and clear all dependencies error in eclipse.

  1. Right click on project.
  2. Go to Maven
  3. Update project , the check the above option “Force update of Snapshot/Releases“.
  4. Click on Ok.
  5. If not fixed restart your eclipse.

Maven Force Update 1

Maven Force Update 2

Maven access through Proxy

Update your proxy configuration in maven settings.xml file and put it inside .m2 folder

C:\Users\USER NAME.m2

proxy settings


<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0                               
http://maven.apache.org/xsd/settings-1.0.0.xsd">

 <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>user name</username>  <!-- Put your user name here -->
      <password>password</password>   <!-- Put your password here -->
      <host>127.56.8.64</host>        <!-- Put the IP address of your proxy server here -->
      <port>80</port>                 <!-- Put your proxy server's port number here -->
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts> <!-- Do not touch this setting unless you know what you're doing. -->
    </proxy>  
  </proxies>
</settings>

You don’t need to touch , and sections, unless you really know what are these tags.

After updating this setting restart eclipse and follow the steps in Maven Force update of Snapshot/Releases.

Remove .lastUpdated file

If this problem is not resolved yet got to .m2/repository/ to dependency sub directory and remove .lastUpdate file inside of it or delete complete directory for this particular dependency and again follow the steps in Maven Force update of Snapshot/Releases.

For Example as for above issue directory location showing in exception as

C:\Users\saurabh.gupta1.m2\repository\org
\springframework\spring-expression\5.1.6.RELEASE

Above solutions are my research to resolve this issue if you find out or know other ways please suggest in comments.

[Solved] java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver


JDBC or Springboot or hibernate throw this exception when you mentioned driver as org.hsqldb.jdbcDriver in your JDBC code or XML configuration or data source configuration properties file but required database driver jar or dependencies is not added in class path.

This exception occurs by below methods :

  • The forName method in the class Class.

                 Class.forName(java.lang.String)

  • The findSystemClass method in the class ClassLoader.

                ClassLoader.findSystemClass()

  • The loadClass method in class ClassLoader.

                ClassLoader.loadClass(java.lang.String, boolean)

java.lang.ClassNotFoundException is Checked Exception which is subclass of  java.lang.ReflectiveOperationException. This  is thrown when application load a class by String name whose definition is not found.

Constructors

  • ClassNotFoundException(): Constructs a ClassNotFoundException with no detail message.
  • ClassNotFoundException(String s) : Constructs a ClassNotFoundException with the specified detail message.
  • ClassNotFoundException(String s, Throwable ex) : Constructs a ClassNotFoundException with the specified detail message and optional exception that was raised while loading the class.

 Difference between Class.forName() and ClassLoader.loadClass()

Example 1: ClassNotFoundException

Below is example of connecting with database and retrieve data from sql table. This will throw ClassNotFoundException because sql driver jar is not in classpath. After this example also mentioned solution.

package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ClassNotFoundException1 {

	public static void main(String[] args) {
		try {
			Class.forName("<strong>org.hsqldb.jdbcDriver</strong>");

			Connection con = DriverManager.getConnection("jdbc:hsqldb:hsql//localhost:3306/FacingIssuesOnITDB", "root", "");

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select name from employee");
			String dbtime;
			while (rs.next()) {
				dbtime = rs.getString(1);
				System.out.println(dbtime);
			}

			con.close();

		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
		}

	}

}

Output:

Connection Failed! Check output console
<pre><code>
<strong>java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver</strong>
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at org.springframework.util.ClassUtils.forName(ClassUtils.java:251)
	at org.springframework.jdbc.datasource.embedded.HsqlEmbeddedDatabaseConfigurer.getInstance(HsqlEmbeddedDatabaseConfigurer.java:48)
	at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseConfigurerFactory.java:43)
	... 54 common frames omitted
</code></pre>

Solutions:

For solving ClassNotFoundException by Class.ForName() method  considering above example to load MySQL driver same way you can follow for other classes and different DB drivers.

Solution in Eclipse :Follow below steps :

  • Right click your project folder and open up Properties.
  • From the right panel, select Java Build Path then go to Libraries tab.
  • Select Add External JARs to import the HSQLDB driver.
  • From the right panel, select Deployment Assembly.
  • Select Add…, then select Java Build Path Entries and click Next.
  • You should see the SQL driver on the list. Select it and click first.

Tomcat :

If directly running from tomcat. Just copy the HSQL-Connector.jar into Tomcat’s lib folder/directory, and then remove the jar from the webApp’s lib folder, and then, run the project.

Maven Springboot application

Add below dependency in your pom.xml file


<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
</dependency>

Summary :

  • Define what is ClassNotFoundException.
  • What are methods throws ClassNotFoundException?
  • Example for ClassNotFoundException.
  • How to fix ClassNotFoundException in Eclipse and Tomcat.
  • How to fix Springboot maven applications.

[Solved] java.sql.SQLSyntaxErrorException: unexpected token: XYZ


java.sql.SQLSyntaxErrorException with error message Unexpected token exception occurred when progress query has violated SQL Syntax or in technical terms SQLState class value is ’42’, or under vendor-specified conditions.

java.sql.SQLSyntaxErrorException is sub class of  SQLNonTransientException which is also sub class of SQLException.

Constructors

  • SQLSyntaxErrorException() : Constructs a SQLSyntaxErrorException object.
  • SQLSyntaxErrorException(String reason) : Constructs a SQLSyntaxErrorException object with a given reason.
  • SQLSyntaxErrorException(String reason, String SQLState) :Constructs a SQLSyntaxErrorException object with a given reason and SQLState.
  • SQLSyntaxErrorException(String reason, String SQLState, int vendorCode) : Constructs a SQLSyntaxErrorException object with a given reason, SQLState and vendorCode.
  • SQLSyntaxErrorException(String reason, String SQLState, int vendorCode, Throwable cause) : Constructs a SQLSyntaxErrorException object with a given reason, SQLState, vendorCode and cause.
  • SQLSyntaxErrorException(String reason, String SQLState, Throwable cause) : Constructs a SQLSyntaxErrorException object with a given reason, SQLState and cause.
  • SQLSyntaxErrorException(String reason, Throwable cause) : Constructs a SQLSyntaxErrorException object with a given reason and cause.
  • SQLSyntaxErrorException(Throwable cause): Constructs a SQLSyntaxErrorException object with a given cause.

java.sql.SQLSyntaxErrorException Example

In this below example try to execute below query while JDBC or upload default schema by Spring boot then it will throw exception “java.sql.SQLSyntaxErrorException: unexpected token: EMPLOYEE” because this query is using EMPLOYEE as required keyword TABLE in first line. That is violation of SQL syntax rule.


DROP EMPLOYEE IF EXISTS;
CREATE TABLE EMPLOYEE
(
    ID int  NOT NULL PRIMARY KEY,
    FIRST_NAME varchar(255),
    LAST_NAME varchar(255),
    ADDRESS varchar(255),
);

java.sql.SQLSyntaxErrorException Stacktrace


Caused by: java.sql.SQLSyntaxErrorException: unexpected token: EMPLOYEE
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:472) ~[spring-jdbc-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    ... 73 common frames omitted
Caused by: org.hsqldb.HsqlException: unexpected token: EMPLOYEE
    at org.hsqldb.error.Error.parseError(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.ParserBase.unexpectedToken(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.ParserDDL.compileDrop(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.ParserCommand.compilePart(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.ParserCommand.compileStatements(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.Session.executeDirectStatement(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    at org.hsqldb.Session.execute(Unknown Source) ~[hsqldb-2.3.6.jar:2.3.6]
    ... 76 common frames omitted

Solutions

Below is correct query to resolve this issue .

DROP TABLE IF EXISTS EMPLOYEE;
CREATE TABLE EMPLOYEE
(
ID int NOT NULL PRIMARY KEY,
FIRST_NAME varchar(255),
LAST_NAME varchar(255),
ADDRESS varchar(255),
);

References

https://docs.oracle.com/javase/7/docs/api/java/sql/SQLSyntaxErrorException.html

[Solved] Date Format : java.text.ParseException: Unparseable date: “yyyy-MM-ddThh:mm:ss.SSSZ”


SimpleDateFormat throw java.text.ParseException exception when passing date for parsing not match with formatting pattern.

java.text.ParseException is runtime unchecked exception which signals that an error has been reached unexpectedly while parsing.

Constructors

  • ParseException (String message, int errorOffset) : Constrcut a ParseException with the specified detail message and offset. A detail message is a String that describes this particular exception. where errorOffset : is the position where error occurred.

Methods

  • public int getErrorOffset() :Returns the position where the error was found.

Example SimpleDateFormat throw ParseException

In this example currentFormat is matching with date passed in sourceDate that’s what failing with parse exception.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

		} catch (ParseException ex) {
			ex.printStackTrace();
		}

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
java.text.ParseException: Unparseable date: "2019-02-12T11:29:10.761Z"
    at java.text.DateFormat.parse(Unknown Source)
    at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:21)

Solutions

To resolve this issue date format should be same as passing source date.

Correct Format for Date is yyyy-MM-dd’T’hh:mm.ss.SS’Z’

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

		} catch (ParseException ex) {
			ex.printStackTrace();
		}

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
java.text.ParseException: Unparseable date: "2019-02-12T11:29:10.761Z"
    at java.text.DateFormat.parse(Unknown Source)
    at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:21)

More Issues Solution

To solved Date Time same code , formatting  and issues solutions follow the link given below:

Java Date and Time Handling Tutorial

[Solved] Date Format : java.lang.IllegalArgumentException: Illegal pattern character ‘Z’ or ‘T’


SimpleDateFormat throw java.lang.IllegalArgumentException at runtime while parsing date format.

Follow link below to get in depth knowledge of IllegalArgumentException .

[Solved] java.lang.IllegalArgumentException: “ABC”

Example DateTime throwing IllegalArgumentexception

In this example target format is throwing IllegalArgumentException because of using illegal pattern character as Z and T.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-ddThh:mm:ss.SSSZ";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

		} catch (ParseException ex) {
			ex.printStackTrace();
		}

	}

}

Output :


Source Date :2019-02-12T11:29:10.761Z
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'T'
    at java.text.SimpleDateFormat.compile(Unknown Source)
    at java.text.SimpleDateFormat.initialize(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:17)

Solutions

SimpleDateFormat allow only some key characters only while using date time formatting. Here using characters Z and T for matching date time pattern in sourceDate that what throwing IllegalArgumentException . To resolve such issues for using  characters apart from formatting char in date format always use with ‘Z’ or ‘T’ (with single quote) as given below. Follow link to see complete list for formatting characters and date format.

Date Time Formatting Characters and Patterns

Correct Date Time Format
"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

		} catch (ParseException ex) {
			ex.printStackTrace();
		}

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
Target Date :02/43/2019 04:59:10 PM

More Issues Solution

To solved Date Time same code , formatting  and issues solutions follow the link given below:

Java Date and Time Handling Tutorial

 

[Solved] Date Format AM/PM : java.lang.IllegalArgumentException: Illegal pattern character ‘A’


SimpleDateFormat throw java.lang.IllegalArgumentException at runtime while parsing date format.

Follow link below to get in depth knowledge of IllegalArgumentException .

[Solved] java.lang.IllegalArgumentException: “ABC”

Example DateTime throwing IllegalArgumentexception

In this example target format is throwing IllegalArgumentException because of using invalid formatting char for display AM/PM.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss AM/PM";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

		} catch (ParseException ex) {
			ex.printStackTrace();
		}

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'A'
    at java.text.SimpleDateFormat.compile(Unknown Source)
    at java.text.SimpleDateFormat.initialize(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:19)

Solutions :

SimpleDateFormat allow only some key characters only while using date time formatting. Here for showing AM/PM should use character as as mentioned in below code in targetFormat. Follow link to see complete list for formatting characters and date format.

Date Time Formatting Characters and Patterns

Correct format to AM/PM
"MM/DD/YYYY hh:mm:ss a"

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

		} catch (ParseException ex) {
			ex.printStackTrace();
		}

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
Target Date :02/43/2019 04:59:10 PM

More Issues Solution

To solved Date Time same code , formatting  and issues solutions follow the link given below:

Java Date and Time Handling Tutorial

Window : How to Kill/Stop tomcat service from command line?


Generally, when run tomcat by eclipse or use embedded tomcat with spring and suddenly close eclipse. But in background tomcat is running. When you try to run tomcat again you will face below exception:

[Solved] Tomcat : java.net.BindException: Address already in use: bind

Solutions

There are two ways to kill tomcat process:

  • Manually kill tomcat process from command line
  • Create script to kill tomcat processes

Manually  kill Tomcat Process from Command line

  1. Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
  2. Run following commands to get all listening ports (If tomcat runnig on other ports apart from 8080)

netstat -aon | find /i "listening"

Apply port filter If you know port number


netstat -aon |find /i "listening" |find "8080"

As in below screen you will get PID and then  run the following command to kill the process

3 Copy PID from result set


taskkill /F /PID

Ex: taskkill /F /PID 13332

Kill Tomcat process from command line

Steps to kill Tomcat Process by script

  • Step 1: Copy below script in note pad and save it with extension as .bat

@ECHO OFF
netstat -aon |find /i "listening"

SET killPORT=
SET /P killPORT=Enter port: 
IF "%killPORT%"=="" GOTO Kill

netstat -aon |find /i "listening" | find "%killPORT%"

:Kill
SET killPID=
SET /P killPID=Enter PID to kill: 
IF "%killPID%"=="" GOTO Error

ECHO Killing %killPID%!
taskkill /F /PID %killPID%

GOTO End
:Error
ECHO No Process to kill!
:End

pause
  • Steps 2: Click  on saved batch file you will get list of all running processes on ports.
  • Step 3: Enter port which you want to kill. Script will return PID for same .
  • Step 4: Enter PID which you want to kill then your tomcat will stop.

Kill Tomcat process by script

JDBC : Function Execution Example


A SQL stored function is a set of PL/SQL statements you can call by name. Stored functions are very similar to procedures, except that a function returns a value to the environment in which it is called. User functions can be used as part of a SQL expression.

SQL stored function called a user function or user-defined function.
See Also :

Types of parameters of functions

  • IN: A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods.
  • OUT: A parameter whose value is supplied by the SQL statement it returns. You retrieve values from the OUT parameters with the getXXX() methods.\
  • INOUT: A parameter that provides both input and output values. You *bind variables with the setXXX() methods and retrieve values with the getXXX() methods.

Example :

In this example will focus on how to execute user defined function by JDBC instead of writing of user defined function.
Table and Function implementationn : Here is small function getAverageStudentAge based on student name.


Create Table
CREATE TABLE `facingissuesonitdb`.`student` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(25) NULL,
'age' INT,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC));

Insert Records  
INSERT INTO `facingissuesonitdb`.`student` (`id`, `name`,'age') VALUES ('1', 'Saurabh Gupta','25');
INSERT INTO `facingissuesonitdb`.`student` (`id`, `name`,'age') VALUES ('2', 'Rajesh Gupta','30');
INSERT INTO `facingissuesonitdb`.`student` (`id`, `name`,'age') VALUES ('3', 'Ramesh Gupta','35');

Create User defined function

USE `facingissuesonitdb`;
DROP function IF EXISTS `getAverageStudentAge`;

DELIMITER $$
USE `facingissuesonitdb`$$
CREATE FUNCTION getAverageStudentAge (name_prefix VARCHAR(25))
  RETURNS NUMERIC
   DETERMINISTIC
    BEGIN
     DECLARE avg_age NUMERIC;
        select avg(s.age) into avg_age from student as s where s.name like '%name_prefix%';
     RETURN avg_age;
    END$$

DELIMITER ;

Java code to execute user defined function by JDBC.

package procedure_functions;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

import connection.MyConnection;

public class FunctionTest {

public static void main(String[] args) {
try {
   Connection conn = MyConnection.getConnectionMain("MySql");

   CallableStatement stmt = conn.prepareCall("{?= call getAverageStudentAge(?)}");
   stmt.setString("Saurabh Gupta");
   stmt.registerOutParameter(1, Types.INTEGER);
   stmt.execute();

   System.out.println(stmt.getInt(1));
} catch (SQLException ex) {
	ex.printStackTrace();
}

}

}

Output:


MySql Connection created successfully !!
MySql Connection Creation end !!
25.

 

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

JAVA : Generate 15 Minute Time Interval AM/PM


In this program you can get list of in time interval with fixed difference Ex: 15 minute in AM and PM format.

Example

import java.util.ArrayList;
import java.util.List;

public class GenerateTimeInterval {

public static void main(String[] args) {
	int interval = 15; //minutes interval
	List timesList=new ArrayList() ; // time array
	String []ap = {"AM", "PM"}; // AM-PM
	String timeFormat;
	for(int h=0;h<24;h++)
	{
	for(int m=0;m<60;)
	{
		if(h<12)
		{
		timeFormat=String.format("%02d:%02d %s", h,m,"AM");
		}
		else
		{
		timeFormat=String.format("%02d:%02d %s", h,m,"PM");
		}
		timesList.add(timeFormat);
		m=m+interval;
		}

	}
	//To match the time
	timeFormat=String.format("%02d:%02d %s", 0,0,"AM");
	timesList.add(timeFormat);
	//print timings
	for(String time : timesList)
	{
		System.out.println(time);
	}

	}
}

Output


00:00 AM
00:15 AM
00:30 AM
00:45 AM
01:00 AM
01:15 AM
01:30 AM
01:45 AM
02:00 AM
02:15 AM
02:30 AM
02:45 AM
03:00 AM
03:15 AM
03:30 AM
03:45 AM
04:00 AM
04:15 AM
04:30 AM
04:45 AM
05:00 AM
05:15 AM
05:30 AM
05:45 AM
06:00 AM
06:15 AM
06:30 AM
06:45 AM
07:00 AM
07:15 AM
07:30 AM
07:45 AM
08:00 AM
08:15 AM
08:30 AM
08:45 AM
09:00 AM
09:15 AM
09:30 AM
09:45 AM
10:00 AM
10:15 AM
10:30 AM
10:45 AM
11:00 AM
11:15 AM
11:30 AM
11:45 AM
12:00 PM
12:15 PM
12:30 PM
12:45 PM
13:00 PM
13:15 PM
13:30 PM
13:45 PM
14:00 PM
14:15 PM
14:30 PM
14:45 PM
15:00 PM
15:15 PM
15:30 PM
15:45 PM
16:00 PM
16:15 PM
16:30 PM
16:45 PM
17:00 PM
17:15 PM
17:30 PM
17:45 PM
18:00 PM
18:15 PM
18:30 PM
18:45 PM
19:00 PM
19:15 PM
19:30 PM
19:45 PM
20:00 PM
20:15 PM
20:30 PM
20:45 PM
21:00 PM
21:15 PM
21:30 PM
21:45 PM
22:00 PM
22:15 PM
22:30 PM
22:45 PM
23:00 PM
23:15 PM
23:30 PM
23:45 PM
00:00 AM

JDBC : Stored Procedure Example


A SQL stored procedure (SP) is a collection SQL statements , SQL command logic, which is compiled and stored on the database and execute on the server. Stored procedures can also be cached and reused. The main purpose of stored procedures to hide direct SQL queries from the code and improve performance of database operations such as select, update, and delete data.

See Also :

Types of parameters of Stored Procedure:

  • IN: A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods.
  • OUT: A parameter whose value is supplied by the SQL statement it returns. You retrieve values from the OUT parameters with the getXXX() methods.\
  • INOUT: A parameter that provides both input and output values. You *bind variables with the setXXX() methods and retrieve values with the getXXX() methods.

Example :

In this example will focus on how to execute procedures by JDBC instead of writing of procedure.

Table and Procedure :  Here is small procedure to getStudentName based on student id.


Create Table
CREATE TABLE `facingissuesonitdb`.`student` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(25) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC));

Insert Records  
INSERT INTO `facingissuesonitdb`.`student` (`id`, `name`) VALUES ('1', 'Saurabh Gupta');
INSERT INTO `facingissuesonitdb`.`student` (`id`, `name`) VALUES ('2', 'Rajesh Gupta');
INSERT INTO `facingissuesonitdb`.`student` (`id`, `name`) VALUES ('3', 'Ramesh Gupta');

Create Stored procedure
USE `facingissuesonitdb`;
DROP procedure IF EXISTS `getStudentName`;

DELIMITER $$
USE `facingissuesonitdb`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getStudentName`(in student_id integer, out first_name varchar(25))
BEGIN
select name into  first_name from student where id=student_id;
END$$

DELIMITER ;

Java code to execute stored procedure by JDBC.

package procedure_functions;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import connection.MyConnection;

public class StoredProcedureTest {

	private static final String PROCEDURE_QUERY = "{call getStudentName(?,?)}";

	public static void main(String[] args) {
	 try {
             //to get connection code check blog for Connection according to your need.
	     Connection conn = MyConnection.getConnectionMain("MySql");
	     CallableStatement csmt = conn.prepareCall(PROCEDURE_QUERY);
	     csmt.setInt(1, 2);
	     // Because second parameter is OUT so register it
	    csmt.registerOutParameter(2, java.sql.Types.VARCHAR);
	    csmt.execute();
	     String firstName = csmt.getString(2);// for retrieving out parameter
											     // after execution
	     System.out.println(firstName);
	    } catch (SQLException ex) {
			ex.printStackTrace();
	   }
	}
}

Output


MySql Connection created successfully !!
MySql Connection Creation end !!
Rajesh Gupta

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

JDBC : Difference between executeQuery() Vs executeUpdate() Vs execute() method


executeQuery(), executeUpdate() and execute() are the methods of java.sql.Statement interface of JDBC API which are used to execute the SQL statements.

executeQuery() Vs executeUpdate() Vs execute()

executeQuery() executeUpdate() execute()
This method is use to execute the SQL statements which retrieve some data from database. This statement is used to execute SQL statements which update or modify database. This method can be use for any kind of SQL statements.
This method returns a ResultSet object which contains the result returned by query. This method returns an int value which represent number of rows affected by the query. This will be 0 for statement which are returning nothing. This method return a Boolean value. TRUE indicates that query returned a ResultSet object and FALSE indicate returned an int value or returned nothing.
This method is use to execute select query. This method is use to execute non select query. This method is use to execute select and non select queries.
Ex: SELECT Ex:
DML->INSERT , UPDATE and DELETEDDL-> CREATE, ALTER
Any Type of SQL statements.

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

[Solved] com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure


  • com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure.
  • java.net.ConnectException: Connection refused.
  • SQLException: Connection refused or Connection timeout

All above exceptions occurred while connecting with database or communication issues because of one or more following causes:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn’t accept TCP/IP connections.
  6. DB server has run out of connections.
  7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

Solutions:

To solve the one or the other, follow the following suggestions:

  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnf of MySQL DB.
  4. Start the DB.
  5. Verify if MySQL is started without the --skip-networking option.
  6. Restart the DB and fix your code accordingly that it closes connections in finally.
  7. Disable firewall and/or configure firewall/proxy to allow/forward the port.

For Example :

For my case this exception occurred because database was not started.


Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:172)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862)
    at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at connection.MyConnection.getConnectionMain(MyConnection.java:59)
    at procedure_functions.StoredProcedureTest.main(StoredProcedureTest.java:42)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:59)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:103)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:149)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:165)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:92)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:982)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:852)
    ... 7 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:173)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:66)
    ... 10 more

More on JDBC

Follow below links to know more posts on JDBC and solving JDBC issues :

[Solved] java.util.InputMismatchException


Pre-requisite :  Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.InputMismatchException” because using scanner.next(regex) but some words in test data  not matching regex “\W” for word as in “Sr. project Lead” in given example.

Test data in file


Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh
Nagar 34 "Project Lead"

Example

package scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerToReadInputFromFile {
	public static void main(String[] args) {
	try {
		// Decalare Scanner and intialize with File input object
		Scanner sc = new Scanner(
		new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
		while (sc.hasNextLine()) {
		   //System.out.println(sc.next(Pattern.compile("\\w+")));
			}
		} catch (FileNotFoundException ex) {
		    ex.printStackTrace();
		}
	}
}

Output


Saurabh
Gupta
36
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:17)

Solution
Always handle exception while using regular expressions. In this example pattern is not matching for ‘Sr Project Lead’ because word pattern allow on [A-Za-z0-1] char only.

JDBC: Steps to connect with Database


There are 5 steps to connect any java application with the database by using JDBC. They are as follows:

  1. Register the driver class
  2. Creating connection
  3. Creating statement
  4. Executing queries
  5. Closing connection

JDBC Steps for Connections

Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.


public static void forName(String className)throws
Class.forName("oracle.jdbc.driver.OracleDriver");

Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException

Ex: Connect with Oracle

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");

Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.


public Statement createStatement()throws SQLException
Statement stmt=con.createStatement();

Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.


public ResultSet executeQuery(String sql)throws SQLException
ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.


public void close()throws SQLException

 

See Also :

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

JDBC Tutorial

JDBC Sample Code

JDBC Issues and Solutions

JDBC Interview Questions And Answers

[Solved] java.util.NoSuchElementException


Pre-requisite :  Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.NoSuchElementException” because using scanner.next() two times without checking existence of element in file for second scanner.next() element.

Test data in file


Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh
Nagar 34 "Project Lead"

Example

package scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerToReadInputFromFile {
	public static void main(String[] args) {
	try {
		// Decalare Scanner and intialize with File input object
		Scanner sc = new Scanner(
		new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
		while (sc.hasNextLine()) {
		   System.out.println(sc.nextLine());
		   System.out.println(sc.next());
		   //System.out.println(sc.next(Pattern.compile("\\w+")));
			}
		} catch (FileNotFoundException ex) {
		    ex.printStackTrace();
		}
	}
}

Output


Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh

Nagar
 34 "Project Lead"
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:15)

Solution
Always use scanner.next() after checking scanner.hasNext()condition. If scanner.hasNext() returning true then only call scanner.next().

[Solved] java.lang.EnumConstantNotPresentException


Pre-requisite : Java: Enumeration Handling

This exception EnumConstantNotPresentException thrown when an application tries to access an enum constant by name and the enum type contains no constant with the specified name. This exception can be thrown by the API used to read annotations reflectively.

Example :

In this below example trying to read annotation by using reflection APIs. Here if api attempt to read an enum-valued member will result in a EnumConstantNotPresentException if the enum constant in the annotation is no longer present in the enum type. Compile everything and run ReadAnnotation. You will got C.

// TestEnum.java
public enum TestEnum {
    A, B, C;
}

// TestAnnotation.java
import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    TestEnum value();
}

// TestClass.java
@TestAnnotation(TestEnum.C)
public class TestClass {

}

// ReadAnnotation.java
public class ReadAnnotation {
    public static void main(String[] args) {
        System.out.println(TestClass.class.getAnnotation(TestAnnotation.class).value());
    }
}

To generate this exception, now remove the C from the TestEnum and recompile only TestEnum class preserving other classes as is. If you launch ReadAnnotation now, you will get:


Exception in thread "main" java.lang.EnumConstantNotPresentException: TestEnum.C
    at sun.reflect.annotation.EnumConstantNotPresentExceptionProxy.generateException(Unknown Source)
    at sun.reflect.annotation.AnnotationInvocationHandler.invoke(Unknown Source)
    at com.sun.proxy.$Proxy1.value(Unknown Source)
    at ReadAnnotation.main(ReadAnnotation.java:4)

References :

https://stackoverflow.com/questions/31261960/when-does-java-lang-enumconstantnotpresentexception-gets-thrown

Java : Enumeration handling


An enum is a data type (same as user defined classes)  which defines a variable with predefined constants. To access/assigned value to enum variable it must be equal to one of the values that have been predefined for it.

Points to remember:

  • The enum added in java  5.
  • The enum keyword is used to define enum type.
  • Each enum constant are by default public static final instance variable.
  • Two enumeration constants can be compared for equality by using == relational operators.
  • The name of enum type’s fields should be in UPPERCASE because they are constant.
  • Use enum types any time when you need to represent a fixed set of constants.
  • Semi colon is optional in side enum type if no any other member.
  • If constructor and methods used inside enum then semi colon required.
  • All enum implicitly extends java.lang.Enum class. Because java doesn’t allow extends of more than one parent class, so an enum can not extend anything else.
  • enum can implement many interfaces.
  • toString() method is overridden inside java.lang.Enum class which returns enum constant name.
  • enum constant can also use in switch case statement.

Implicit methods of java.lang.Enum

Below are implicit methods of enum class.

  • values() method can be used to return all values present inside enum.
  • ordinal() method return index of each enum constant, same as array index.
  • valuesOf() method returns the enum constant of specified string value, if exists.

In below examples you will se use of these methods.

enum Month{
JANNUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};

enum with constructor and method definition.

enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
	};

Example

public class EnumTest {
	enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
public void showMonthName() {
System.out.println("Month Name :"+this.monthName);
}
};
	public static void main(String[] args) {
		//values method return array of constants of type MonthDetail
		for(MonthDetail monthDetail:MonthDetail.values())
		{
			monthDetail.showMonthDetail();
		}

MonthDetail  month=MonthDetail.DECEMBER;
//two enumeration can be compared by == relational operators
if(month==MonthDetail.DECEMBER)
{
//call method of enum to getName of enumerated month
month.showMonthName();
}
}

Output


1 : January
2 : February
3 : March
4 : April
5 : May
6 : June
7 : July
8 : August
9 : September
10 : October
11 : November
12 : December

December

Enumeration with switch and case

As in switch case value always allow constant value and enumeration is constant so we can use case values as enumeration. You can refer below example where case values use as PLUS, MINUS, MULTIPLE and DIVIDE enum constant values.

package enm;

public class Calculator {
	public enum Operator {
		PLUS, MINUS, MULTIPLY, DIVIDE
	}
	public static double Calculate(int left, int right, Operator op) throws Exception {
		double result = 0.0;
		switch (op) {
		case PLUS:
			result = left + right;
			break;
		case MINUS:
			result = left - right;
			break;
		case MULTIPLY:
			result = left * right;
			break;
		case DIVIDE:
			result = (double) left / right;
			break;
		default:
			throw new Exception("Couldn't process operation: " + op);
		}
		return result;
	}

	public static void main(String[] args) {
		try {
			System.out.println(Operator.PLUS + " : " + Calculate(20, 10, Operator.PLUS));
			System.out.println(Operator.MINUS + " : " + Calculate(20, 10, Operator.MINUS));
			System.out.println(Operator.MULTIPLY + " : " + Calculate(20, 10, Operator.MULTIPLY));
			System.out.println(Operator.DIVIDE + " : " + Calculate(20, 10, Operator.DIVIDE));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}

Output


PLUS : 30.0
MINUS : 10.0
MULTIPLY : 200.0
DIVIDE : 2.0

Enumeration Exception

while using enumeration generally two types of exception need to handle.

[Solved] java.lang.IllegalArgumentException: No enum constant


Pre-requisite :  Java : Enumeration Handling

Below is example of enumeration by using all implicit methods of enumeration.
Here used wrong value of enumeration as “Saturday” while using month name here that’s why causing this issue.

package enm;

public class EnumTest {

	enum Month{JANNUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER};
	enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
	};
	public static void main(String[] args) {
		for(Month month:Month.values())
		{
	    //Add one because by default enum indexing start from 0
		System.out.println((month.ordinal()+1) +" : "+month.name());
		}
		//Every enum Class provide values method to get list of enums
		for(MonthDetail monthDetail:MonthDetail.values())
		{
			monthDetail.showMonthDetail();
		}

		try
		{
		MonthDetail mnth=MonthDetail.valueOf("Saturday");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Output


1 : JANNUARY
2 : FEBRUARY
3 : MARCH
4 : APRIL
5 : MAY
6 : JUNE
7 : JULY
8 : AUGUST
9 : SEPTEMBER
10 : OCTOBER
11 : NOVEMBER
12 : DECEMBER
1 : January
2 : February
3 : March
4 : April
5 : May
6 : June
7 : July
8 : August
9 : September
10 : October
11 : November
12 : December
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant enm.EnumTest.MonthDetail.Saturday
    at java.lang.Enum.valueOf(Enum.java:238)
    at enm.EnumTest$MonthDetail.valueOf(EnumTest.java:1)
    at enm.EnumTest.main(EnumTest.java:49)

Solutions:
Always use valid constant values to resolve this issue and while trying to call this enum.valueOf() method always handle exception so that any exception happen then your program will not terminate.

try {
 MonthDetail mnth=MonthDetail.valueOf("August");
} catch(Exception ex) {
ex.printStackTrace();
}

To learn more on Enumeration follow below link: Java : Enumeration Handling