Spring Boot REST with XML ( Use Spring-Data-Rest to return response as XML )

Well with latest Spring IO Platform we can achieve this and with IO Platform we dont need to worry about version also.

CODE:

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.subu</groupId>
<artifactId>SpringBootExamples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.4.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Person.java

package com.subu;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.*;

@Entity
@XmlRootElement(name = “person”)
@Table(name=”person”)

public class Person implements Serializable{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Long id;

@XmlAttribute(name = “first-name”)
private String first_name;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getFirst_name() {
return first_name;
}

public void setFirst_name(String first_name) {
this.first_name = first_name;
}

public String getLast_name() {
return last_name;
}

public void setLast_name(String last_name) {
this.last_name = last_name;
}

public String getDate_of_birth() {
return date_of_birth;
}

public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}

@XmlAttribute(name = “last-name”)
private String last_name;

@XmlAttribute(name = “dob”)
private String date_of_birth;

}

 

Application.java

package com.subu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableScheduling
public class Application extends SpringBootServletInitializer{

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
private static Class<Application> applicationClass = Application.class;

}

 

PersonController.java

package com.subu;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {

@Autowired
private PersonRepository personRepository;

@RequestMapping(value = “/persons/{id}”, method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = “Accept=application/xml”)
public ResponseEntity<?> getPersonDetails(@PathVariable Long id, final HttpServletRequest request)throws Exception {
Person personResponse=personRepository.findPersonById(id);
return ResponseEntity.ok(personResponse);
}}

 

PersonRepository.java

package com.subu;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository<Person, Long> {

Person findPersonById(Long id);

}

JpaConfiguration.java

package com.subu;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.eclipse.persistence.config.BatchWriting;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = “com.subu”)
public class JpaConfiguration extends JpaBaseConfiguration {

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(final EntityManagerFactoryBuilder builder) {
final LocalContainerEntityManagerFactoryBean ret =
builder.dataSource(dataSource())
.packages(“com.subu”)
.properties(jpaProperties())
.persistenceUnit(“com.subu”)
.build();
return ret;
}

@Bean
public DataSource dataSource() {
// In classpath from spring-boot-starter-web
final Properties props = new Properties();
props.put(“driverClassName”, “com.mysql.jdbc.Driver”);
props.put(“jdbcUrl”, “jdbc:mysql://localhost:3306/master?createDatabaseIfNotExist=false”);
props.put(“username”, “root”);
props.put(“password”, “mysql”);
HikariConfig hc = new HikariConfig(props);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}

@Bean
public Map<String, String> jpaProperties() {
Map<String, String> props = new HashMap<>();
props.put(“eclipselink.weaving”, “false”);
props.put(“eclipselink.logging.level.sql”, “FINE”);
props.put(“eclipselink.logging.parameters”, “true”);
props.put(“javax.persistence.schema-generation.database.action”, “create”);
//props.put(“javax.persistence.sql-load-script-source”, “sql/import.sql”);
return props;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
final MultiTenantJpaTransactionManager transactionManager = new MultiTenantJpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}

@Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
return new EclipseLinkJpaVendorAdapter();
}

@Override
protected Map<String, Object> getVendorProperties() {
final Map<String, Object> ret = new HashMap<>();
ret.put(PersistenceUnitProperties.BATCH_WRITING, BatchWriting.JDBC);
return ret;
}
}

MultiTenantJpaTransactionManager.java

package com.subu;

import java.io.Serializable;
import javax.persistence.EntityManager;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class MultiTenantJpaTransactionManager extends JpaTransactionManager {

@Override
protected void doBegin(final Object transaction, final TransactionDefinition definition) {
super.doBegin(transaction, definition);
final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
.getResource(getEntityManagerFactory());
final EntityManager em = emHolder.getEntityManager();

}
}

SecurityConfig.java

 

package com.subu;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(“user1”).password(“user1”).roles(“USER”)
.and()
.withUser(“user2”).password(“secret2”).roles(“USER”);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated();
http.httpBasic();
http.csrf().disable();
}
}

EnableWebMvcSecurity.java

package com.subu;

public @interface EnableWebMvcSecurity {

}

 

TABLE:

tabletable1table2

 

OUTPUT :

xml

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

}}}

 

Reverse XML tags using java

Many times we need to reverse the xml tag

</Request>
</name>
</address>
<pincode>123456</pincode>
<area>ABC</area>
<flat>XYZ</flat>
<address>
<name>
<Request>

as below :

<Request>
<name>
<address>
<flat>XYZ</flat>
<area>ABC</area>
<pincode>123456</pincode>
</address>
</name>
</Request>

 

Steps:

 

reverserequest

  1. Create a xml with reverse request
  2. Click on ReverseXMLrequest.bat

 

      3. Enter the source file and destination file path

reverserequest_batch

4) The File with correct xml will be generated in destination path.

 

Code:

==================================

  1. Create a Mavenized project.
  2. Add dependencies jars like commons-io
  3. 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>ReverseXMLRequest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</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.ReverseXMLRequest</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>ReverseXMLRequest</finalName>
</build>
</project>

 

4) ReverseXMLRequest.java

package com.subhasish;

import org.apache.commons.io.input.*;
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import javax.xml.transform.*;
import javax.xml.parsers.*;
public class ReverseXMLRequest {

public static void main(String[] args) throws ParserConfigurationException,IOException,SAXException,TransformerException{
String ch;
String destinationPath=args[1];
String tempPath=”C://temp.xml”;
try(ReversedLinesFileReader fr = new ReversedLinesFileReader(new File(args[0]));)
{
Path path = Paths.get(tempPath);
Files.deleteIfExists(path);
Files.createFile(path);
do {
ch = fr.readLine();
Files.write(path, ch.getBytes(),StandardOpenOption.APPEND);

} while (ch != null);
}
catch(Exception e)
{
formatXML(tempPath,destinationPath);
}}

public static void formatXML(String path,String destinationPath) throws IOException
{
Path deletePath = Paths.get(path);
try
{
final InputSource src = new InputSource(new FileInputStream(new File(path)));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(“LS”);
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter(“format-pretty-print”,Boolean.TRUE);
LSOutput lsOutput = impl.createLSOutput();
lsOutput.setEncoding(“UTF-8”);
Writer stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);
writer.write(document, lsOutput);
String result = stringWriter.toString();
Path formattedpath = Paths.get(destinationPath);
Files.createFile(formattedpath);
Files.deleteIfExists(deletePath);
Files.write(formattedpath, result.getBytes(),StandardOpenOption.APPEND);
System.out.println(“DONE”);
} catch (Exception e)
{
Files.deleteIfExists(deletePath);
}
}}

 

5)  ReverseXMLrequest.bat

@echo off
set /p sourceinput=”Enter Source Path::”
set /p destinput=”Enter Destination Path::”
java -jar ReverseXMLRequest.jar %sourceinput% %destinput%
pause

 

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”