Wednesday, February 18, 2015

Quartz -The Job Scheduling Library

Quartz -The Job Scheduling Library

 Quartz is a open source job scheduling library can be integrated with any Java applications.

 The application jobs to executed periodically or  at given moments .


 Job Scheduling:-scheduled to run a job when Trigger occurs
 Job Execution:-Jobs can be any Java class that implements Job interface













Maven dependency


<dependency>
  <groupId>org.quartz-scheduler</groupId>
  <artifactId>quartz</artifactId>
  <version>2.1.5</version>
</dependency>

or
download the jar

quartz-2.1.5.jar






Program to demonstrate Job Scheduling using Quartz


import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.Date;
import org.quartz.CronTrigger;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzDemo {


//
public static void StartCronEngine(Scheduler scheduler, Date startTime,
JobDetail job, String Triggername, String Triggergroupname,
String cronexpression) {
try {
CronTrigger trigger = newTrigger()
.withIdentity(Triggername, Triggergroupname)
.startAt(startTime)
.withSchedule(cronSchedule(cronexpression)).build();
scheduler.scheduleJob(job, trigger);
scheduler.start();
} catch (Exception e) {
e.printStackTrace();
}

}

public static void pauseJob(JobKey jobKey, Scheduler scheduler) {
try {
scheduler.pauseJob(jobKey);
} catch (SchedulerException e) {
String msg = "Could not pause Quartz Scheduler job: " + jobKey;
throw new RuntimeException(msg, e);
}
}

public static void resumeJob(JobKey jobKey, Scheduler scheduler) {
try {
scheduler.resumeJob(jobKey);
} catch (SchedulerException e) {
String msg = "Could not resume Quartz Scheduler job: "
+ jobKey.getName();
throw new RuntimeException(msg, e);
}
}

public static boolean deleteJob(JobKey jobKey, Scheduler scheduler) {
try {
return scheduler.deleteJob(jobKey);
} catch (SchedulerException e) {
String msg = "Could not obtain Quartz Scheduler JobDetails";
throw new RuntimeException(msg, e);
}
}

public void startEngine() throws Exception {
try {
SchedulerFactory factory = new StdSchedulerFactory();
Date startTime = DateBuilder.nextGivenSecondDate(null, 15);
JobDetail job = JobBuilder.newJob(Enginejob.class)
.withIdentity(new JobKey("jobname", "jobgroup")).build();
StartCronEngine(factory.getScheduler(), startTime, job,
"trriger name", "trriger group name", "0/20 * * * * ?");
} catch (Exception e) {
e.printStackTrace();

}
}

public void pauseEngine() throws Exception {
try {
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
pauseJob(new JobKey("jobname", "jobgroup"), scheduler);
} catch (Exception e) {
e.printStackTrace();
}

}

public void resumeEngine() throws Exception {
try {
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
resumeJob(new JobKey("jobname", "jobgroup"), scheduler);
scheduler.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public void deleteEngine() throws Exception {
try {
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
deleteJob(new JobKey("jobname", "jobgroup"), scheduler);
} catch (Exception ex) {
ex.printStackTrace();
}
}

}

Monday, February 16, 2015

Program Task execution time -Spring StopWatch


Stop watch allows us to measure elapsed time or execution time of different task

improving the readability of application code and   measuring performance and execution time of important piece of codes specially methods or loops which executes most of the time.

TaskCompletionHistory  has three method task , task1, task2

program will demonstrate  time taken by each methods and summary (detail description)


import org.springframework.util.StopWatch;

public class TaskCompletionHistory {


public static void main(String[] args) throws Exception {

// create the new StopWatch by springframework
StopWatch watch = new StopWatch("-- Task Completion History --");
// starts StopWatch with specified task name
watch.start("time taken by function task");
task();
task1();
task2();
watch.stop();
// prints the short Summary of taks function
System.out.println("total task info" + watch.shortSummary());

// prints the detail of taks function

System.out.println(watch.prettyPrint());
}

public static void task() throws Exception {

Thread.sleep(100);
}

public static void task1() throws Exception {

Thread.sleep(200);
}

public static void task2() throws Exception {

Thread.sleep(300);
}
}





OUTPUT:-

Date Time Util And Date Parser


Java provides the Date class,Calendar class available in java.util package, this class encapsulates the current date and time.

Java 1.8 supports Date Time API which contains LocalDate ,Month, ZoneId, Instant, DateTimeFormatter, Period,Duration and many more in java.time package.


Demonstration on time util for java developers. this blog contains list of methods.

1)adding years,months,days,hours,minutes,seconds to current date
2)converting date of one format to another
3)parsing date


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;

public class TimeUtil {

java.util.Date date = new java.util.Date();
java.sql.Timestamp currentdate = new java.sql.Timestamp(date.getYear(),
date.getMonth(), date.getDate(), date.getHours(),
date.getMinutes(), date.getSeconds(), 0);

/**
* add years for current date
*
* @param addyears
* @return
*/
public Timestamp addyearsfromnow(int addyears) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentdate.getTime());
cal.add(Calendar.YEAR, addyears);
Timestamp later = new Timestamp(cal.getTime().getTime());
return later;
}

/**
* add months for current date
*
* @param addmonths
* @return
*/
public Timestamp addmonthsfromnow(int addmonths) throws Exception {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentdate.getTime());
cal.add(Calendar.MONTH, addmonths);
Timestamp later = new Timestamp(cal.getTime().getTime());
return later;
}

/**
* add days for current date
*
* @param adddays
* @return
*/
public Timestamp adddaysfromnow(int adddays) throws Exception {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentdate.getTime());
cal.add(Calendar.DATE, adddays);
Timestamp later = new Timestamp(cal.getTime().getTime());
return later;
}

/**
* add hours for current date
*
* @param addhours
* @return
*/
public Timestamp addhoursfromnow(int addhours) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentdate.getTime());
cal.add(Calendar.HOUR, addhours);
Timestamp later = new Timestamp(cal.getTime().getTime());
return later;
}

/**
* add minutes for current date
*
* @param addminute
* @return
*/
public Timestamp addminutefromnow(int addminutes) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentdate.getTime());
cal.add(Calendar.MINUTE, addminutes);
Timestamp later = new Timestamp(cal.getTime().getTime());
return later;
}

/**
* add seconds for current date
*
* @param addseconds
* @return
*/
public Timestamp addsecondfromnow(int addseconds) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentdate.getTime());
cal.add(Calendar.SECOND, addseconds);
Timestamp later = new Timestamp(cal.getTime().getTime());
return later;
}

/**
* format Timestamp by SimpleDateFormat to string
*
* @param date
* @param dateformat
* @return
*/
public String format(Timestamp date, String dateformat) {
DateFormat formatter = new SimpleDateFormat(dateformat);
String dateinstring = formatter.format(date);
return dateinstring;
}

/**
* format Date by SimpleDateFormat to string
*
* @param date
* @param dateformat
* @return
*/
public String format(Date date, String dateformat) {
DateFormat formatter = new SimpleDateFormat(dateformat);
String dateinstring = formatter.format(date);
return dateinstring;
}

/**
* convert Timestamp to string
*
* @param date
* @param dateformat
* @return
*/
public Timestamp StringtoTimestamp(String string) {
Timestamp ts = Timestamp.valueOf(string);
return ts;
}

/**
* convert java date string to string sql Timestamp by string formatter
*
* @param dateString
* @param formatter
* @return
* @throws ParseException
*/
public static java.sql.Timestamp convertJavaDateToSqlTimestamp(
String dateString, String formatter) throws ParseException {

DateFormat format = new SimpleDateFormat(formatter);
Date dateutil = null;
dateutil = format.parse(dateString);
int year = dateutil.getYear();
int month = dateutil.getMonth();
int day = dateutil.getDate();
int hour = dateutil.getHours();
int minute = dateutil.getMinutes();
int second = dateutil.getSeconds();
java.sql.Timestamp timestamp = new java.sql.Timestamp(year, month, day,
hour, minute, second, 0);
return timestamp;
}

/**
* convert java date string to string sql date
*
* @param dateString
* @param formatter
* @return
* @throws ParseException
*/
public static java.sql.Date fromJavaDateToSqlDate(String dateString,
String formatter) throws ParseException {
DateFormat format = new SimpleDateFormat(formatter);
Date dateutil = null;
dateutil = format.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(dateutil);
java.sql.Date date = new java.sql.Date(cal.getTime().getTime());
return date;
}

/**
* parse date by different format
*
* @param dateString
* @return
*/
public Date parse(String dateString) {
String[] formatStrings = "yyyy-MM-dd hh:mm:ss,yyyy-MM-dd hh:mm,yyyy-MM-dd hh,MM/dd/yyyy hh:mm:ss,MM/dd/yyyy hh:mm,MM/dd/yyyy hh"
.split(",");
for (String formatString : formatStrings) {
try {
return new SimpleDateFormat(formatString).parse(dateString);
} catch (ParseException e) {
System.out.println("not able to parse by this format::"
+ formatString);
}
}
return null;
}

/**
* parse by specific format
*
* @param dateString
* @param format
* @return
* @throws ParseException
*/
public Date parse(String dateString, String format) throws ParseException {
return new SimpleDateFormat(format).parse(dateString);
}

/**get todaydate .this work in java 1.8
*
* @return
*/
public Date gettodaydate(){
LocalDate today = LocalDate.now();
return today;
}

/**get todaydate by zoneid .this work in java 1.8
*
* @return
*/
public Date gettodaydatebylocale(){
LocalDate Kolkatadate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
return Kolkatadate;
}

}

Friday, February 13, 2015

SOLR CRUD IN JAVA


Solr is an open source enterprise search platform built on Apache Lucene, it easy to run a full-featured search .

Solr search on index. instead of searching the text directly.

This type of index is called an inverted index, index data structure storing a mapping from content such as word or numbers in database or documents.

An index consists of one or more Documents, and a Document consists of one or more Fields.




Maven dependency

<dependency>
  <groupId>org.apache.solr</groupId>
  <artifactId>solr-solrj</artifactId>
  <version>4.7.2</version>
</dependency>

or
download the jar
solr-solrj-4.7.2.jar



Program to demonstrate Crud operation on solr:-


import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;


/**
 * @author  Rohan Kamat
 *
 */
public class SolrCrud{
private HttpSolrServer server = null;

public SolrCrud() throws Exception {
server = getSolrConnectionObject();
}



//connection object of solr
public HttpSolrServer getSolrConnectionObject() throws Exception {
HttpSolrServer solrCon = null;
try {
if (solrCon == null) {
solrCon = new HttpSolrServer("http://localhost:8983/solr");
solrCon.setParser(new XMLResponseParser());
solrCon.setSoTimeout(5000);
solrCon.setConnectionTimeout(5000);
}
} catch (Exception exc) {
System.out.println( "Problem in Solr Connection: "
+ exc.getMessage());
exc.printStackTrace();
}
return solrCon;
}



//query from solr
public QueryResponse query(String query)
throws Exception {
ModifiableSolrParams solrParams = new ModifiableSolrParams();
solrParams.set("q", query);
return server.query(solrParams);
}

//add document in solr
public void add(String id, String name) throws Exception {
// add solr document
SolrInputDocument document = new SolrInputDocument();
document.addField("id", id);
document.addField("name", name);
server.add(document);
server.commit();
}


    //delete a document from solr
public void delete(String id) throws Exception {
server.deleteByQuery("id:" + id);
server.commit();
}

public static void main(String[] args) throws Exception {
SolrCrud scrud=new SolrCrud();
try {
            //add document in solr
scrud.add("0", "name0");
scrud.add("1", "name1");
scrud.add("2", "name2");

//query document in solr
scrud.query("name1");

//delete document in solr
scrud.delete("1");
} catch (SolrException solrEx) {
solrEx.printStackTrace();

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

}

Sunday, February 8, 2015

parse outlook .ics file in java to fetch list of events with start date and end date

 iCalendar data files are plain text files with the extension .ics
 iCalendar data has the MIME content type text/calendar.

 Files with .ics extension which contain calendaring and scheduling information consistent with this MIME content type.

These calendar files allow different users to store calendar information within a text file .



Maven dependency

<dependency>
<groupId>org.mnode.ical4j</groupId>
<artifactId>ical4j</artifactId>
<version>1.0.4</version>
</dependency>

or can use

ical4j-1.0.4.jar




Program to Parse .ics file in java to fetch list of events with start date and  end date



import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Version;

public class ParseIcsFile {

public static void main(String args[]) throws Exception {
ParseIcsFile cusr = new ParseIcsFile();
File file = new File("Rohan_Calendar.ics");
String result = cusr.getCalInfoFromIcs(file);
System.out.println(result);
}

public String getCalInfoFromIcs(File file) throws Exception {

net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
calendar.getProperties().add(
new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
calendar.getProperties().add(Version.VERSION_2_0);
calendar.getProperties().add(CalScale.GREGORIAN);

FileInputStream fin = new FileInputStream(file);
CalendarBuilder builder = new CalendarBuilder();
calendar = builder.build(fin);
List result = new ArrayList<String>();

for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Map<String, String> calenderinfo = new HashMap<String, String>();
Component component = (Component) i.next();

for (Iterator j = component.getProperties().iterator(); j.hasNext();) {
try {
String startdate = null, enddate = null, event = null;
Property property = (Property) j.next();
if ("DTSTART".equals(property.getName())) {
startdate = property.getValue();
calenderinfo.put("startDate",
modifyDateLayoutOfIcs(startdate));
}
if ("DTEND".equals(property.getName())) {
enddate = property.getValue();
calenderinfo.put("endDate",
modifyDateLayoutOfIcs(enddate));
}
if ("SUMMARY".equals(property.getName())) {
event = property.getValue();
calenderinfo.put("event", event);
}

if (!calenderinfo.isEmpty()) {
if (calenderinfo.get("event") != null) {
result.add(calenderinfo);
}
}

} catch (Exception ex) {

}
}
}
return result.toString();
}

private String modifyDateLayoutOfIcs(String inputDate) {
try {

SimpleDateFormat inDateFormat = new SimpleDateFormat("yyyyMMdd");
java.util.Date fromDate = inDateFormat.parse(inputDate);

SimpleDateFormat outDateForm = new SimpleDateFormat("dd-MMM-yyyy");
return outDateForm.format(fromDate);
} catch (Exception e) {
return inputDate;
}

}

}