Thursday, March 19, 2015

Image Picker

Imagepicker utility which pick all image URL used in site . Just give a URL and get list of images .
It use HTML Parser to parse html Tag nodes.
HTML Parser is a Java library used to parse HTML in either a linear or nested fashion. 
Primarily used for transformation or extraction.

Maven dependency

<dependency>
  <groupId>org.htmlparser</groupId>
  <artifactId>htmlparser</artifactId>
  <version>1.6</version>
</dependency>

or

download the jar




import java.util.ArrayList;
import java.util.List;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;

public class Imagepicker {
/**
* @author Rohan Kamat
* @version 1.0
* @Date Jan 11, 2015
*/
public static void main(String[] argv) throws ParserException {
Imagepicker img = new Imagepicker();
List<String> result = img
.imagelist("http://www.pixelofnature.com/portfolio/");
System.out.println(result);
}

public List<String> imagelist(String url) throws ParserException {
List<String> result = new ArrayList<String>();
Parser parser = new Parser(url);

                //check for img tag in html
NodeList list = parser.parse(new TagNameFilter("IMG"));
               
                //traverse the node to src attribute
for (SimpleNodeIterator iterator = list.elements(); iterator
.hasMoreNodes();) {
Tag tag = (Tag) iterator.nextNode();
System.out.println(tag.getAttribute("src"));
result.add(tag.getAttribute("src"));
}
return result;
}
}

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

}