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

 

Advertisements

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”

  1. In Eclipse IDE , goto to Help  –> Eclipse MarketPlace
  2. In search, put sonarlint 

Sonar_Lint

 

Sonar_Lint_1

 

Sonar_Lint_2

Once it is installed, it will ask for Re-Start.

3) Right click on any Java file and click on SonarQube –> Analyze

Sonar_Lint_Analyze

4) It will start analyzing and you will be able to see all Blocker/Major/Minor Issue in Sonar Lint Issues Tab

Sonar_Lint_Analyze1

 

Sonar_Lint_Analyze2

 

 

 

 

Sonar Qube Integration with Eclipse

Sonar Qube Integration with Eclipse

1) Download Sonar Qube Server 5.3 server –>  SonarQube 5.3

Note : Sonar Qube will work with JDK1.7

2)  Un-Zip and go to the path where it has been installed ( Based on your System Type i.e 32 bit or 64 bit).

For example–>   I:\Sonar_Qube\sonarqube-5.3\sonarqube-5.3\bin\windows-x86-32 

SonarQube

3)  Start –> Sonar.bat

SonarQube_Console

4) Hit   http://localhost:9000  on any browser to see if the server is up

SonarQube_Site

5) Download SonarQube in Eclipse.

URL –>    sonar – http://downloads.sonarsource.com/eclipse/eclipse/

Paste the above url in Eclipse Market Place.Click on 1st Option and Finish Button. After installation it will ask for restart of Eclipse.

Eclipse_MarketPlace

Eclipse_MarketPlace_Installation

6) Go to Window–>Preferences–>SonarQube–>Servers.

Check if Server is properly configured.

Eclipse_Server_Check

7) In your Project Service/Java Folder, open pom.xml and make the below entries.

<properties>
<project.build.sourceEncoding> UTF-8 </project.build.sourceEncoding>
     <sonar.host.url>http://localhost:9000</sonar.host.url> 
</properties>

8)

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>

<plugin>
                   <groupId>org.jacoco</groupId>
                   <artifactId>jacoco-maven-plugin</artifactId>
                   <version>0.7.0.201403182114</version>
                   <executions>
                         <execution>
                               <goals>
                                           <goal>prepare-agent</goal>
                              </goals>
                         </execution>
                    </executions>
                   <configuration>
                         <destFile>${sonar.jacoco.reportPath}</destFile>
                  </configuration>
       </plugin>
</plugins

9) Right Click on your Project –> Configure –> Associate with Sonar Qube

SonarQube_Associate

10)   Right Click on your Java Project pom.xml –> Run As –> Maven build

sonar_maven

11) Enter the below details and Click on Apply –>Run

clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Dmaven.test.failure.ignore=true sonar:sonar

 

sonar_maven_command

Note: If the build fails for the first time, please re build again with the above command.

12)  In Eclipse Console, you will be able to see some logs regarding maven build and sonar analysis.

Sonar_Build

Sonar_Build_1

13) Once Build is successfully. Go to Sonar Localhost site .You will be able to see Java Project got included in SonarQube Analysis.

Sonar_Site

Sonar_Site_Quality_gate

Click on Issues Tab, you will be able to see all the Java related compliance issue.

Sonar_Site_Issue

14) You can also view the Unit Test Cases Coverage, under

 Measures–>Project name–>Coverage

Sonar_Site_coverage

 

15) You can define Rules

Sonar_Site_rules

 

 

 STEPS  TO  INLCUDE  SONAR  RULE  DUMP

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

  1. Login as admin/admin

login

 

2. Click Quality Profile Menu

quality_profile

 

3) Click on Create –> Restore Profile

quality_profile

 

qualityprofile_create

Choose the Dump file

choose_file

 

4) Click on Restore

 

choose_dump

 

5) Once done, Set it as Default

set_default

 

set_default_1

 

6) Go to Home Page and click on Project

home_page_issues

 

 

Click on Issues

home_page_issue_1

You will see the new set of rules applied

dump_issues

 

dump_issues_1