Wednesday, 28 March 2018

Checkstyle in eclipse tutorial

In this post, you are going to learn
a.   What is Checkstyle
b.   How to install checkstyle eclipse plugin
c.   How to check the code with Checkstyle
d.   How to open Checkstyle violations window?
e.   How to open Checkstyle violations chart?

What is Checkstyle
Checkstyle is an open source code analysis tool, it helps java programmers to write code as per standards.

You can go through below link, to explore all the checks performed by checkstyle.

How to install Checkstyle eclipse plugin?
Open Eclipse.

Help -> Install new Software.

Work with below url.


Press the button Next. Follow the steps in the user interfae and
Install Check style plugin.

Restart the eclipse.

How to check the code with Checkstyle?
Right click on the project -> Checkstyle -> Check Code with Checkstyle


Now you can see all the violatons of the code in ‘Checkstyle Violations’ window.

How to open Checkstyle violations window?
Window -> Show view -> Other

Search for checkstyle.
Select ‘Checkstyle violations’ and press OK.

Now you can see all the violations in ‘Checkstyle Violations’ window.

How to open Checkstyle violations chart?
You can see all the cheskstyle violation in graphical view using ‘Checkstyle violations chart.

Window -> Show View -> Other

Search for checkstyle.
Select ‘Checkstyle violations chart’ and press OK button.

Now you can able to see the below kind of graph.


You may like


Previous                                                    Next                                                    Home

Hamcrest: emptyCollectionOf: Check the emptiness of collection

By using ‘emptyCollectionOf’ method, you can create a matcher that is used to check whether collection is empty or not.

Ex
List<Integer> tempList = Arrays.asList();
assertThat("empty must be empty", tempList, emptyCollectionOf(Integer.class));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.emptyCollectionOf;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  List<Integer> tempList = Arrays.asList();
  assertThat("empty must be empty", tempList, emptyCollectionOf(Integer.class));

 }
}



Previous                                                 Next                                                 Home

Tuesday, 27 March 2018

Working with PMD in Eclipse

In this post, you are going to learn.
a.   What is PMD?
b.   Languages supported by PMD
c.   What can I do with PMD?
d.   What are the features of PMD?
e.   Install PMD Eclipse plugin
f.    Configure PMD in Eclipse
g.   Find the bugs using PMD
h.   How to generate reports using PMD?

What is PMD?
PMD stands for 'Programming Mistake Detector', it is an open source static source code analyzer.

Languages supported by PMD
At the time of writing this article, PMD supports below languages.

a.   Java
b.   JSP
c.   JavaScript
d.   Salesforce.com Apex and Visualforce
e.   PLSQL
f.    Apache Velocity
g.   XML and Maven POM
h.   XSL

What can I do with PMD?
By using PMD, you can identify the common programming flaws done by the developers.

For example, you can identify,

a.   Unused variables
b.   empty try/catch/finally/switch blocks
c.   unnecessary object creations
d.   duplicated code
e.   dead code (unused local variables, private methods, parameters) etc.,

What are the features of PMD?
a.   Supporting 8 languages (Java, JSP, JavaScript, Salesforce.com Apex and Visualforce, PLSQL, Apache Velocity, XML and Maven POM, XSL).
b.   Many ready-to-use built-in rules.
c.   Custom rules can be written in Java
d.   Custom rules can be written using XPath expression that query the AST of the sources
e.   Many output formats
f.    Many integrations into IDEs, build tools

Install PMD Eclipse plugin
Open Eclipse.

Help -> Install New Software.


Work with below url.


Select ‘PMD for Eclipse 4’ and press Next. Follow the next steps in the GUI.

Once installation is successful, restart the eclipse.

Configure PMD in Eclipse
Window -> preferences -> PMD

It opens window like below.
Find the bugs using PMD
Right click on the project -> PMD -> Check Code.
Now, you can able to see all the violations in ‘Violations overview’ Section.
By any chance 'Violations Overview' is not opened, then you can open by going through below path.
Window->Show View->Other->PMD->Violations Overview

How to generate reports using PMD?
Right click on the project -> PMD -> Generate Reports

Now you can see the generated reports in 'reports' folder inside the project folder.

You can always selects the reports format by changing the report format.
Window -> Preferences -> PMD -> Reports.
Reference

You may like


Previous                                                    Next                                                    Home

Monday, 26 March 2018

Hamcrest: empty: Check emptiness of collection

By using ‘empty’ method, you can create a matcher that is used to check whether collection is empty or not.

Ex
List<Integer> tempList = Arrays.asList();
assertThat("tempList must be empty", tempList, empty());

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  List<Integer> tempList = Arrays.asList();
  assertThat("empty must be empty", tempList, empty());

 }
}




Previous                                                 Next                                                 Home

Pretty print xml string in java

In this post, I am going to show you how can we convert the xml string in pretty print format.

Input
<?xml version=\"1.0\"?><!-- Represents Books information in store --><books><book id=\"1\"><name>Let Us C</name><author>Yashwant Kanetkar</author><price>245.00</price></book><book id=\"2\"><name>Let Us C++</name><author>Yashwant Kanetkar</author><price>252.00</price></book><book id=\"3\"><name>Java The Complete Reference</name><author>Herbert Schildt</author><price>489.00</price></book><book id=\"4\"><name>HTML5 Black Book</name><author>Kogent Learning Solutions</author><price>485.00</price></book></books>"
                 
XMLUtil.java
package com.sample.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XMLUtil {

 public static String getPrettyString(String xmlData, int indent) throws Exception {
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  transformerFactory.setAttribute("indent-number", indent);

  Transformer transformer = transformerFactory.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  StringWriter stringWriter = new StringWriter();
  StreamResult xmlOutput = new StreamResult(stringWriter);

  Source xmlInput = new StreamSource(new StringReader(xmlData));
  transformer.transform(xmlInput, xmlOutput);

  return xmlOutput.getWriter().toString();
 }
}

Test.java
package com.sample.util;

public class Test {

 public static void main(String args[]) throws Exception {
  String xmlData = "<?xml version=\"1.0\"?><!-- Represents Books information in store --><books><book id=\"1\"><name>Let Us C</name><author>Yashwant Kanetkar</author><price>245.00</price></book><book id=\"2\"><name>Let Us C++</name><author>Yashwant Kanetkar</author><price>252.00</price></book><book id=\"3\"><name>Java The Complete Reference</name><author>Herbert Schildt</author><price>489.00</price></book><book id=\"4\"><name>HTML5 Black Book</name><author>Kogent Learning Solutions</author><price>485.00</price></book></books>";
  
  String str = XMLUtil.getPrettyString(xmlData, 2);
  
  System.out.println(str);
 }
}


Output
<?xml version="1.0" encoding="UTF-8"?><!-- Represents Books information in store --><books>
  <book id="1">
    <name>Let Us C</name>
    <author>Yashwant Kanetkar</author>
    <price>245.00</price>
  </book>
  <book id="2">
    <name>Let Us C++</name>
    <author>Yashwant Kanetkar</author>
    <price>252.00</price>
  </book>
  <book id="3">
    <name>Java The Complete Reference</name>
    <author>Herbert Schildt</author>
    <price>489.00</price>
  </book>
  <book id="4">
    <name>HTML5 Black Book</name>
    <author>Kogent Learning Solutions</author>
    <price>485.00</price>
  </book>
</books>

You may like



Hamcrest: hasSize: Checks the size of collection

By using ‘hasSize’ method, you can create a matcher that checks the size of collection.

Ex
List<Integer> employeeAges = Arrays.asList(24, 45, 32);
assertThat("Size of the collection must be equal to 3", employeeAges, hasSize(3));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {

  List<Integer> employeeAges = Arrays.asList(24, 45, 32);
  assertThat("Size of the collection must be equal to 3", employeeAges, hasSize(3));

 }
}




Previous                                                 Next                                                 Home

Saturday, 24 March 2018

Convert xml document to string

In this post, I am going to show, how can you convert an xml document to plain string.

Approach1: Using StringBuilder

Approach2: Using javax.xml package

I am going to use ‘books.xml’ file to demonstrate the examples.

books.xml
<?xml version="1.0"?>
<!-- Represents Books information in store -->
<books>
 <book id="1">
  <name>Let Us C</name>
  <author>Yashwant Kanetkar</author>
  <price>245.00</price>  
 </book>
 <book id="2">
  <name>Let Us C++</name>
  <author>Yashwant Kanetkar</author>
  <price>252.00</price>  
 </book>
 <book id="3">
  <name>Java The Complete Reference</name>
  <author>Herbert Schildt</author>
  <price>489.00</price>  
 </book>
 <book id="4">
  <name>HTML5 Black Book</name>
  <author>Kogent Learning Solutions</author>
  <price>485.00</price>  
 </book> 
</books>

Approach 1: Using StringBuilder
Below statements convert the xml file to string in java.

BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilePath)));
String line;
StringBuilder sb = new StringBuilder();

while ((line = br.readLine()) != null) {
         sb.append(line.trim());
}

Find the below working application.

XMLUtil.java
package com.sample.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class XMLUtil {

 public static String getXMLString(String xmlFilePath) {
  if (xmlFilePath == null || xmlFilePath.isEmpty()) {
   throw new IllegalArgumentException("xmlFilePath can't be null or empty");
  }

  try (BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilePath)))) {
   String line;
   StringBuilder sb = new StringBuilder();

   while ((line = br.readLine()) != null) {
    sb.append(line.trim());
   }

   return sb.toString();
  } catch (IOException e) {
   throw new RuntimeException(e);
  }

 }
}

Test.java
package com.sample.util;

import java.io.IOException;

public class Test {

 public static void main(String args[]) throws IOException {
  String xmlFilePath = "C:\\Users\\krishna\\books.xml";
  
  String xmlStr = XMLUtil.getXMLString(xmlFilePath);
  
  System.out.println(xmlStr);
 }
}


Output
xml : <?xml version="1.0"?><!-- Represents Books information in store --><books><book id="1"><name>Let Us C</name><author>Yashwant Kanetkar</author><price>245.00</price></book><book id="2"><name>Let Us C++</name><author>Yashwant Kanetkar</author><price>252.00</price></book><book id="3"><name>Java The Complete Reference</name><author>Herbert Schildt</author><price>489.00</price></book><book id="4"><name>HTML5 Black Book</name><author>Kogent Learning Solutions</author><price>485.00</price></book></books>

Approach2: Using javax.xml package


XMLUtil.java
package com.sample.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class XMLUtil {

 public static String getXMLString(String xmlFilePath) {
  if (xmlFilePath == null || xmlFilePath.isEmpty()) {
   throw new IllegalArgumentException("xmlFilePath can't be null or empty");
  }
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

  try (InputStream iStream = new FileInputStream(new File(xmlFilePath))) {
   Document document = documentBuilderFactory.newDocumentBuilder().parse(iStream);

   StringWriter stringWriter = new StringWriter();

   Transformer transformer = TransformerFactory.newInstance().newTransformer();

   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

   transformer.transform(new DOMSource(document), new StreamResult(stringWriter));

   String output = stringWriter.toString();

   String result = output.replaceAll("\n|\r", "");

   return result;
  } catch (Exception e) {
   throw new RuntimeException(e);
  }

 }
}

Test.java
package com.sample.util;

import java.io.IOException;

public class Test {

 public static void main(String args[]) throws IOException {
  String xmlFilePath = "C:\\Users\\krishna\\books.xml";
  
  String xmlStr = XMLUtil.getXMLString(xmlFilePath);
  
  System.out.println(xmlStr);
 }
}

Output
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Represents Books information in store --><books> <book id="1">  <name>Let Us C</name>  <author>Yashwant Kanetkar</author>  <price>245.00</price>   </book> <book id="2">  <name>Let Us C++</name>  <author>Yashwant Kanetkar</author>  <price>252.00</price>   </book> <book id="3">  <name>Java The Complete Reference</name>  <author>Herbert Schildt</author>  <price>489.00</price>   </book> <book id="4">  <name>HTML5 Black Book</name>  <author>Kogent Learning Solutions</author>  <price>485.00</price>   </book> </books>

Use below statement, to remove all the spaces.
String result = output.replaceAll("\n|\r|\\s+", "");


In my next post, I am going to show you how to convert a string to xml document.

You may like