How to monitor file changes using java.nio JDK 7 API (WatcherService example)


If you want to monitor files under a directory, you can use the following source code.

This program will monitor files for the events such as MODIFY,CREATE and DELETE.

(Don’t forget this program requires JDK 7.0)

package watcherserviceexamplejdk7;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKind.*;

/**
*
* @author tunatore
*/
public class WatcherServiceExampleJDK7 {

public static void main(String[] args) throws IOException, InterruptedException {
monitorFilesInDirectory("C:\\directoryname");
}

public static void monitorFilesInDirectory(String directory) {

try {
//create a WatcherService object for monitoring directories
WatchService watchService = FileSystems.getDefault().newWatchService();
//getting the path object for the directory given by users
Path path = Paths.get(directory);
//register the events to be notified by the program
path.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
while (true) {
//infinite loop will take events
WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//getting the type of the event
WatchEvent.Kind<?> kind = watchEvent.kind();
//getting the file name from the WatchEvent object
Path file = (Path) watchEvent.context();
System.out.println("Filename --> " + file + " Event type --> " + kind.name());
}
//reset the current event and wait for other events
key.reset();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Here is an example output for the program;

processes taken in the following order

1. Created a file named abc.txt (under the directory)
2. Modified abc.txt

3. Deleted abc.txt file

Filename –> New Text Document.txt Event type –> ENTRY_CREATE
Filename –> New Text Document.txt Event type –> ENTRY_DELETE
Filename –> abc.txt Event type –> ENTRY_CREATE

Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_DELETE

BUILD STOPPED (total time: 1 minute 57 seconds)

Download Source Code

Advertisements

How to use <h:dataTable> JSF component


Use the following 2 classes to generate the content for h:dataTable  JSF UI component

package content;

/**
*
* @author tunatore
*/
public class Employee {

private int employeeID;
private String employeeName;
private String employeeSurname;
private String employeePhoneNumber;

/**
* @return the employeeID
*/
public int getEmployeeID() {
return employeeID;
}

/**
* @param employeeID the employeeID to set
*/
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}

/**
* @return the employeeName
*/
public String getEmployeeName() {
return employeeName;
}

/**
* @param employeeName the employeeName to set
*/
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

/**
* @return the employeeSurname
*/
public String getEmployeeSurname() {
return employeeSurname;
}

/**
* @param employeeSurname the employeeSurname to set
*/
public void setEmployeeSurname(String employeeSurname) {
this.employeeSurname = employeeSurname;
}

/**
* @return the employeePhoneNumber
*/
public String getEmployeePhoneNumber() {
return employeePhoneNumber;
}

/**
* @param employeePhoneNumber the employeePhoneNumber to set
*/
public void setEmployeePhoneNumber(String employeePhoneNumber) {
this.employeePhoneNumber = employeePhoneNumber;
}

}
package content;

import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

/**
*
* @author tunatore
*/
@ManagedBean(name = "EmployeeGenerator")
@RequestScoped
public class EmployeeGenerator {

private List<Employee> employees = new ArrayList<Employee>();

public EmployeeGenerator() {

Employee e1 = new Employee();
e1.setEmployeeID(1);
e1.setEmployeeName("Tuna");
e1.setEmployeeSurname("Tore");
e1.setEmployeePhoneNumber("12345678");

Employee e2 = new Employee();
e2.setEmployeeID(2);
e2.setEmployeeName("James");
e2.setEmployeeSurname("Gosling");
e2.setEmployeePhoneNumber("2222222222");

Employee e3 = new Employee();
e3.setEmployeeID(3);
e3.setEmployeeName("Linus");
e3.setEmployeeSurname("Torvalds");
e3.setEmployeePhoneNumber("3333333333");

Employee e4 = new Employee();
e4.setEmployeeID(4);
e4.setEmployeeName("Bill");
e4.setEmployeeSurname("Gates");
e4.setEmployeePhoneNumber("44444444");

Employee e5 = new Employee();
e5.setEmployeeID(5);
e5.setEmployeeName("Larry");
e5.setEmployeeSurname("Ellison");
e5.setEmployeePhoneNumber("555555555");

Employee e6 = new Employee();
e6.setEmployeeID(6);
e6.setEmployeeName("Tim");
e6.setEmployeeSurname("Berners-Lee");
e6.setEmployeePhoneNumber("66666666");

employees.add(e1);
employees.add(e2);
employees.add(e3);
employees.add(e4);
employees.add(e5);
employees.add(e6);

}

public List<Employee> getEmployees() {

return employees;
}
}

index.html content

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>JSF <h:dataable> example</title>
</h:head>
<h:body>
<h:dataTable cellpadding="4" border="1" bgcolor="cyan" value="#{EmployeeGenerator.employees}" var="employee">
<f:facet name="header">
<h:outputText value="Emlpoyee <h:datatable> Example" />
</f:facet>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee ID"/>
</f:facet>
<h:outputText value="#{employee.employeeID}"/>
</h:column>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee Name"/>
</f:facet>
<h:outputText value="#{employee.employeeName}"/>
</h:column>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee Surname"/>
</f:facet>
<h:outputText value="#{employee.employeeSurname}"/>
</h:column>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee Phone"/>
</f:facet>
<h:outputText value="#{employee.employeePhoneNumber}"/>
</h:column>
</h:dataTable>

</h:body>
</html>

Use this url for accessing the index.xhtml page

http://localhost:8080/JSFhdatatableExample/faces/index.xhtml

The output of the program;

Download source

An Error Occurred: java.util.ArrayList cannot be cast to javax.faces.component.UIComponent solution


If you get the following exception when you try to bind the JSF Components to the ArrayList

just change the binding attribute of the component to value attribute such as the following solution

wrong –> <h:dataTable bgcolor=”red” binding=”#{EmployeeGenerator.employees}” var=”employee”

this works –> <h:dataTable bgcolor=”red” value=”#{EmployeeGenerator.employees}” var=”employee”

An Error Occurred: java.util.ArrayList cannot be cast to javax.faces.component.UIComponent – Stack Trace java.lang.ClassCastException: java.util.ArrayList cannot be cast to javax.faces.component.UIComponent at com.sun.faces.application.ApplicationImpl.createComponentApplyAnnotations(ApplicationImpl.java:1912) at com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:1132) at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.createComponent(ComponentTagHandlerDelegateImpl.java:497) at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:157) at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98) at

How to use <x:parse> tag of JSTL for parsing XML documents


If you want to parse a XML document, you can use x:parse tag like the following example;

Before using this example don’t forget to include standard.jar and jstl.jar inside lib folder.

Here is the content for the XML file used in this example

<?xml version="1.0" encoding="UTF-8"?>
<SERVERCONFIG>
<SERVERS>
<SERVER NAME="server1" ENABLED="Y">
<IP>10.1.2.1</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>12345</PASSWORD>
<DESCRIPTION>Application Server1</DESCRIPTION>
</SERVER>
<SERVER NAME="server2" ENABLED="Y">
<IP>10.1.2.2</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>54321</PASSWORD>
<DESCRIPTION>Application Server1</DESCRIPTION>
</SERVER>
<SERVER NAME="server3" ENABLED="N">
<IP>10.1.2.3</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>012345</PASSWORD>
<DESCRIPTION>Application Server3</DESCRIPTION>
</SERVER>
<SERVER NAME="server4" ENABLED="Y">
<IP>10.1.2.4</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>0123456</PASSWORD>
<DESCRIPTION>Application Server4</DESCRIPTION>
</SERVER>
<SERVER NAME="server5" ENABLED="N">
<IP>10.1.2.5</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>01234567</PASSWORD>
<DESCRIPTION>Application Server5</DESCRIPTION>
</SERVER>
</SERVERS>
</SERVERCONFIG>

And the JSP page for processing XML content

index.jsp file

<%--
Document   : index
Created on : 16.Eyl.2011, 11:35:25
Author     : tunatore
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body style="background-color: aliceblue">
<center>
<h1>&lt;x:parse&gt; example</h1>
<!--c:import var="server" url="http://localhost:8080/JSTLxparseTagExample/servers.xml"/>-->
<c:import var="server" url="servers.xml"/>
<x:parse xml="${server}" var="output"/>
<table>
<tr>
<td align="center"><b> Getting the first server's information using XPath evaluation of &lt;x:out&gt; tag </b></td>
</tr>
<tr>
<td align="center">
<table border="2">
<tr><td><b>IP:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/IP" /></b></td></tr>
<tr><td><b>USERNAME:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/USERNAME" /></b></td></tr>
<tr><td><b>PASSWORD:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/PASSWORD" /></b></td></tr>
<tr><td><b>DESCRIPTION:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/DESCRIPTION" /></b></td></tr>
</table>
</td>
</tr>
<tr>
<td align="center"><b> Getting all servers using &lt;x:forEach&gt; tag  </b></td>
</tr>
<tr>
<td align="center">
<table border="2">
<x:forEach select="$output/SERVERCONFIG/SERVERS/SERVER"  >
<tr><td><b>SERVER--></b></td><td><b><x:out select="@NAME" /></b></td></tr>
<tr><td><b>IP:</b></td><td><b><x:out select="IP" /></b></td></tr>
<tr><td><b>USERNAME:</b></td><td><b><x:out select="USERNAME" /></b></td></tr>
<tr><td><b>PASSWORD:</b></td><td><b><x:out select="PASSWORD" /></b></td></tr>
<tr><td><b>DESCRIPTION:</b></td><td><b><x:out select="DESCRIPTION" /></b></td></tr>
</x:forEach>
</table>
</td>
</tr>
</table>
</center>
</body>
</html>

And this is the output for the program;

Download sample project

javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/xpath/VariableStack solution


If you get the following exception while using JSTL parse tag you should download the xalan-2.7.1.jar and put into the lib folder.
You can download the xalan-2.7.1.jar from here http://www.findjar.com/jar/mule/dependencies/maven2/xalan/xalan/2.7.1/xalan-2.7.1.jar.html

org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/xpath/VariableStack
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

root cause
javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/xpath/VariableStack
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:865)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:794)
org.apache.jsp.index_jsp._jspService(index_jsp.java:99)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Warning: Cannot read drop down range Unrecognized token 43 Exception


If you get the exception mentioned while using the JExcel API for reading the content of Microsoft Files;

Warning: Cannot read drop down range Unrecognized token 43 Exception

Try to add the following lines of code before getting the first sheet of the Excel Document.

//Warning:  Cannot read drop down range Unrecognized token 43
WorkbookSettings workbooksetting = new WorkbookSettings();
workbooksetting.setCellValidationDisabled(true);
Workbook workbook = Workbook.getWorkbook(new File("C:\\yourexcelfile.xls"),workbooksetting);

However, I think this is a temporary solution for the problem, it is better if you take care of the Excel document’s format before reading it using the JExcel API.

How to get an Oracle table as a XML Document using XMLType


Here is the table creation script;

CREATE TABLE EMPLOYEE
(
ID               NUMBER,
EMPLOYEENAME     VARCHAR2(20 BYTE),
EMPLOYEESURNAME  VARCHAR2(20 BYTE),
GENDER           VARCHAR2(20 BYTE),
SALARY           VARCHAR2(5 BYTE),
EMPLOYEEID       VARCHAR2(20 BYTE)
)

And lets enter some data inside it;

INSERT INTO EMPLOYEE (
ID, EMPLOYEENAME, EMPLOYEESURNAME,
GENDER, SALARY, EMPLOYEEID)
VALUES ( 1, 'tuna' , 'tore' ,
'M',  '1000', 1)
INSERT INTO EMPLOYEE (
ID, EMPLOYEENAME, EMPLOYEESURNAME,
GENDER, SALARY, EMPLOYEEID)
VALUES ( 2, 'linus' , 'torvalds' ,
'M',  '1000', 2)
INSERT INTO EMPLOYEE (
ID, EMPLOYEENAME, EMPLOYEESURNAME,
GENDER, SALARY, EMPLOYEEID)
VALUES ( 3, 'bill' , 'gates' ,
'M',  '1000', 3)

By using XMLType Oracle build-in function we can convert the whole table and get the data inside as a XML document in the following example;

SELECT
XMLTYPE
(
CURSOR
(
SELECT * FROM EMPLOYEE
)
)
FROM
DUAL;

Here is the result;

<?xml version="1.0"?>
<ROWSET>
<ROW>
<ID>1</ID>
<EMPLOYEENAME>tuna</EMPLOYEENAME>
<EMPLOYEESURNAME>tore</EMPLOYEESURNAME>
<GENDER>M</GENDER>
<SALARY>1000</SALARY>
<EMPLOYEEID>1</EMPLOYEEID>
</ROW>
<ROW>
<ID>2</ID>
<EMPLOYEENAME>linus</EMPLOYEENAME>
<EMPLOYEESURNAME>torvalds</EMPLOYEESURNAME>
<GENDER>M</GENDER>
<SALARY>1000</SALARY>
<EMPLOYEEID>2</EMPLOYEEID>
</ROW>
<ROW>
<ID>3</ID>
<EMPLOYEENAME>bill</EMPLOYEENAME>
<EMPLOYEESURNAME>gates</EMPLOYEESURNAME>
<GENDER>M</GENDER>
<SALARY>1000</SALARY>
<EMPLOYEEID>3</EMPLOYEEID>
</ROW>
</ROWSET>