WatchService in Java 7

                                                File change notifications

In JDK 7 release , the addition of File Change Notifications finally carved into NIO 2.0.The WatchService API lets you receive notification events upon changes in file under a Directory  i.e on creation, modification and deletion of file.

There are 3 events to watch for:

ENTRY_CREATE
ENTRY_DELETE
ENTRY_MODIFY
The steps involved are:

i) Create a WatchService object which consists of a queue to hold WatchKeys

WatchService watchService =FileSystems.getDefault().newWatchService();

ii) Get Path to the watchable directory

Path path= Paths.get(“C:\\User\\code\\watchservice\\”);

iii) We need to register the directory to this WatchService and need to specify the types of events

path.register((watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);

iv) Start a loop to listen to Events and Iterate through the keys

WatchKey key = watchService.take(); // this will return the keys

v) We will then call the pollEvents method to retrieve all the events for this WatchKey object

WatchEvent<?> event : key.pollEvents()

vi) Returns the event type

WatchEvent.Kind<Path> kind = watchEvent.kind();

vii) The reset method sets the WatchKey state back to “ready” and returns a boolean indicating if the WatchKey is still valid or not.This is the most import part of Watch Service functionality.

key.reset();

 

CODE:

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 java.nio.file.StandardWatchEventKinds;

public class WatchServiceJava7Feature {

public static void main(String[] args) throws Exception {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path= Paths.get(“C:\\User\\code\\watchservice\\”);
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
while(true)
{
WatchKey key = watchService.take(); // this will return the keys
for(WatchEvent<?> event : key.pollEvents())
{
WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
WatchEvent.Kind<Path> kind = watchEvent.kind();
switch(kind.name()) {
case “ENTRY_MODIFY”:
System.out.println(“Case Modify :Event on “+ event.context().toString() + ” is “+ kind);
break;
case “ENTRY_DELETE”:
System.out.println(“Case Delete :Event on “+ event.context().toString() + ” is “+ kind);
break;
case “ENTRY_CREATE”:
System.out.println(“Case Create :Event on “+ event.context().toString() + ” is “+ kind);
break;
}

}
key.reset();
}

}}

 

OUTPUT:

Case Create :Event on New Text Document.txt is ENTRY_CREATE
Case Delete :Event on New Text Document.txt is ENTRY_DELETE
Case Modify :Event on New Text Document (2).txt is ENTRY_MODIFY

 

 

 

How to get HTTP response for a URL in Java?

Response:

log4j: Threshold =”null”.
log4j: Level value for root is [info].
log4j: root level set to INFO
log4j: Class name: [org.apache.log4j.RollingFileAppender]
log4j: Setting property [maxFileSize] to [10000KB].
log4j: Setting property [maxBackupIndex] to [3].
log4j: Parsing layout of class: “org.apache.log4j.PatternLayout”
log4j: Setting property [conversionPattern] to [%d [%d{yyyy-MM-dd HH:mm:ss:SSS Z}] [%t] %-5p %c %L – %m %n].
log4j: setFile ended
log4j: Adding appender named [] to category [root].
Response–>STATUS 200

Code:

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public class HttpResponseCheck {
private static final Logger logger = HttpResponseCheckLogger.getLogger(HttpResponseCheck.class);

public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
// args[0] =http://hostname:port/xyz/zbc
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
// Read in all of the post results into a String.
String output = “”;
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println(“Response–>” + output);
}

catch (Exception e) {
System.out.println(“Exception” + e);

}}}

 

Find/Search Hard Coded string in Files under Directories and Sub-Directories

Many times we hard code some string in files which could lead to Production issue.We seems to ignore this minor changes.Below is the code which could help to find the File/Files  in which such hard code string is present as well as shows the line in which it occurs.

 

bat_file

Steps:

  1. Click on bat file.
  2. Insert the Source folder path ( where java files are present ) and press Enter
  3. Go to C://logs//searchString.log to check the logs

In log files , we will be able to see the below content :

 

log_files

 

Code:

  1. Create a mavenized Project and add jar file dependencies such as log4j , commons-logging and commons-io in pom.xml
  2. Pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.subhasish</groupId>
<artifactId>SearchString</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name>
<url>http://download.java.net/maven/2</url&gt;
</repository>
</repositories>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>attached</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>com.subhasish.ScanFiles</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<finalName>SEARCHSTRING</finalName>
</build>
</project>

3) ScanFiles.java

package com.subhasish

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.log4j.Logger;

public class ScanFiles {

private static final Logger logger = ScanFilesLogger.getLogger(ScanFiles.class);

private static void searchFiles(String folderPath, String searchString) throws IOException {
File folder = new File(folderPath);
List<File> files = (List<File>) FileUtils.listFiles(folder, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
if (folder.isDirectory()) {
File[] fList = folder.listFiles();
for (File file : files) {
if (!file.canRead()) {
file.setReadable(true);
}
String content = “”;
try(BufferedReader br = new BufferedReader(new FileReader(file));) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
logger.info(“File ::::: ” + file.getName());
logger.info(” ——————————————————————————————————————————————————————— “);
while ((line = br.readLine()) != null)
{

if (line.contains(searchString) && (!line.contains(“System.out.println”) && !line.contains(“logger.info”) && !line.contains(“logger.debug”) && !line.contains(“logger.error”) && !line.contains(“//”) && !line.contains(“/*”)))
{
logger.info(“Matched Line :::::”+line);
}}
} finally {
br.close();
}
logger.info(” ##############################################################################################################################################################################################”);
}
} else {
System.out.println(“Not a Directory!”);
}
System.out.println(“DONE”);
}
public static void main(String args[]) throws IOException{

if(args.length == 0)
{
System.out.println(” ::::::::::::::::::::::::::::::::::::::::::”);
System.out.println(” :::::::::: PATH cannot be empty ::::::::::”);
System.out.println(” ::::::::::::::::::::::::::::::::::::::::::”);

logger.info(” ::::::::::::::::::::::::::::::::::::::::::”);
logger.info(” :::::::::: PATH cannot be empty ::::::::::”);
logger.info(” ::::::::::::::::::::::::::::::::::::::::::”);
System.exit(0);
}
searchFiles(new File(args[0]).getAbsolutePath(),”\””);}}

 

4)  ScanFilesLogger.java

package com.subhasish

import org.apache.log4j.Logger;
import org.apache.log4j.Logger;

public class ScanFilesLogger {

public static Logger getLogger(Class className) {
return Logger.getLogger(className);
}
public static Logger getLogger(String name) {

return Logger.getLogger(name);
}
}

 

5) Run Maven Clean and Install.It will create a jar file as SEARCHSTRING.jar

6) Create a Batch File – SEARCHSTRING.bat

@echo off
set /p input=”Enter Path::”
echo “Please Note : Your logs file will be genrated in C drive ”
echo “#########################################################”
java -jar SEARCHSTRING.jar %input%
pause

7) Place the jar and bat file at one place and run the bat file.

 

Continue reading “Find/Search Hard Coded string in Files under Directories and Sub-Directories”