Search This Blog

Showing posts with label Jenkins. Show all posts
Showing posts with label Jenkins. Show all posts

Friday, April 5, 2019

Postman integration with Jenkins

Postman contains a full-featured testing sandbox that lets you write and execute JavaScript based tests for your API. You can then hook up Postman with your build system using Newman, the command line collection runner for Postman.
Newman allows you to run and test a Postman Collection. Newman and Jenkins are a perfect match. Let's review these topics to set up this operation.
Note: We are using Ubuntu as a target OS as in most cases your CI server would be running on a remote Linux machine.

Installation

Install NodeJS and npm. Newman is written in NodeJS and we distribute the official copy through npm. Install nodejs and npm for Linux.
Install Newman globally, to set up Newman as a command line tool in Ubuntu.
$ npm install -g newman

Run a collection in Postman

We assume you already have a Postman Collection with some tests. Run the collection in the Postman app. Here's an example of the output in Postman’s collection runner.
collection runner
Some of the tests are failing intentionally in the screenshot so we can show you the instructions for troubleshooting.

Run a collection using Newman

Run this collection inside Newman, using the command below. If everything is set up nicely, you should see the output below.
terminal output from collection run

Set up Jenkins

Jenkins exposes an interface at http://localhost:8080.
jenkins interface
Create a new job by clicking on the “New Item” link on the left sidebar > Select a “Freestyle Project” from the options > Name your project.
new Jenkins job
Add a build step in the project. The build step executes a Shell command.
execute shell command
Here is the command:
$ newman jenkins_demo.postman_collection --exitCode 1
Note here that we are using the Newman command parameter “exitCode” with the value 1. This denotes that Newman is going to exit with this code that will tell Jenkins that everything did not go well.
Click the Save button to finish creating the project.
source code management

Troubleshooting

Run this build test manually by clicking on the “Build Now” link in the sidebar.
run build
Jenkins indicates that the build has failed with a red dot in the title. We can check why with the console output from Newman.
build failed message
Click the “Console Output” link in the sidebar to see what Newman returned.
console output
Fix these tests inside Postman and then try again.
collection runner view
You can move on once you see green pass icons for all your tests like the screenshot above.
console output for all tests pass
Jenkins indicates that the build succeeded with a blue ball.

Configure frequency of runs

To set up the frequency with which Jenkins runs Newman, click on “Configure project” in the main project window and then scroll down.=. The syntax for setting the frequency is H/(30) * * * *.
build triggers
Note: 30 can be replaced with another number.
Jenkins will now run Newman at your desired frequency and will tell you whether the build failed or succeeded. In a bigger setup, Newman will be part of your build process and probably not the entire process. You can set up notifications and customize Jenkins as per your needs.
You can use a wide variety of other configurations to make your collection more dynamic. 

Wednesday, March 7, 2018

Postman Integration with Jenkins

  • Newman
Postman contains a full-featured testing sandbox that lets you write and execute JavaScript based tests for your API. You can then hook up Postman with your build system using Newman, the command line collection runner for Postman. Newman allows you to run and test a Postman Collection.
Newman and Jenkins are a perfect match. Let’s start setting this up. We are using Ubuntu as a target OS as in most cases your CI server would be running on a remote Linux machine.

Installation

  1. Install NodeJS and npm. Newman is written in NodeJS and we distribute the official copy through npm. Install nodejs and npm for Linux.
  2. Install Newman globally, to set up Newman as a command line tool in Ubuntu.
$ npm install -g newman

Run a collection in Postman

We are assuming that you already have a Postman Collection with some tests. Run the collection in the Postman app. This is what the output looks like in Postman’s collection runner.
collection runner
Some of my tests are failing intentionally in the screenshot so we can show you the instructions for troubleshooting.

Run a collection using Newman

Run this collection inside Newman, using the command below. If everything is set up nicely, you should see the output below.
terminal output from collection run

Set up Jenkins

Jenkins exposes an interface at http://localhost:8080.
jenkins interface
Create a new job by clicking on the “New Item” link on the left sidebar > Select a “Freestyle Project” from the options > Name your project.
new Jenkins job
Add a build step in the project. The build step executes a Shell command.
execute shell command
The command is:
$ newman jenkins_demo.postman_collection --exitCode 1
Note here that we are using the Newman command parameter “exitCode” with the value 1. This denotes that Newman is going to exit with this code that will tell Jenkins that everything did not go well.
Click the Save button to finish creating the project.
source code management

Troubleshooting

Run this build test manually by clicking on the “Build Now” link in the sidebar.
run build
Jenkins indicates that the build has failed with a red dot in the title. We can check why with the console output from Newman.
build failed message
Click on the “Console Output” link in the sidebar to see what Newman returned.
console output
Fix these tests inside Postman and then try again.
collection runner view
You can move on once you see green pass icons for all your tests like the screenshot above.
console output for all tests pass
Jenkins indicates that the build succeeded with a blue ball.

Configure frequency of runs

To set up the frequency with which Jenkins runs Newman, click on “Configure project” in the main project window and then scroll down.=. The syntax for setting the frequency is H/(30) * * * *.
build triggers
Note: 30 can be replaced with another number
Jenkins will now run Newman at your desired frequency and will tell you whether the build failed or succeeded. In a bigger setup, Newman will be part of your build process and probably not the entire process. You can set up notifications and customize Jenkins as per your needs.
You can use a wide variety of other configurations to make your collection more dynamic.

Thursday, June 25, 2015

Bitnami Jenkins Usage Steps

Jenkins, previously known as Hudson, is an open source continuous integration server. Built with Java, it provides over 400 plugins to support building and testing virtually any project. It supports SCM tools including CVS, Subversion, Git, Mercurial, Perforce and Clearcase, and can execute Apache Ant and Apache Maven based projects as well as arbitrary shell scripts and Windows batch commands. It also can monitor executions of remote tasks.
Please, take a look to the Quick Start Guide to know the basic use of this Stack.

How to start/stop the servers?

Graphical tool
The native installers include a graphical tool to manage the servers easily. You can find the "manager-windows.exe", "manager-osx" or "manager-linux" tool in your installation directory. Using this tool, you can Start, Stop or Restart the servers and check the log files. You can click on the icon to start it.
manager-servers.png

manager-osx.png










win_platform.png
On Windows: You can also start the Manager tool from shortcuts: Start -> Program Files -> Bitnami Stack -> Manager tool
Command line tool
If you prefer, you can use the "ctlscript.sh" utility from the command line. This script is in the installation directory.
linux_platform.png
On Virtual Machines and Cloud images:
$ sudo /opt/bitnami/ctlscript.sh start
A native installer on Linux:
$ cd ~/application-version
$ ./ctlscript.sh start
mac_platform.png

On OS X: You can start the Manager tool from the installation directory or you can use the "ctlscript.sh" utility from a Terminal.
host:~ user$ cd /Applications/application-version
host:~ user$ ./ctlscript.sh start

Where is JENKINS_HOME variable pointing to?

We define JENKINS_HOME in your installation directory in the apache-tomcat/conf/Catalina/localhost/jenkins.xml file. By default it is pointing to apps/jenkins/jenkins_home.
Notice that the installation directory is /opt/bitnami in the Bitnami virtual appliances and Bitnami Amazon Images.

How to start with Git and Jenkins?

Jenkins application is running as "tomcat" user so it is necessary to configure this user in case you want to access to a private repository. If you use a public repository is not necessary to configure the Tomcat user.
Configure Tomcat user to have access to the Git repository
Previous versions of Jenkins require to create the Tomcat user folder:
$ sudo mkdir /home/tomcat
$ sudo mkdir /home/tomcat/.ssh
Then copy the private key to access to the repository into the "/home/tomcat/.ssh" folder:
$ sudo cp /path/to/id_rsa /home/tomcat/.ssh
And change the permissions
$ sudo chown -R tomcat:tomcat /home/tomcat
It is also necessary to save the hostname of your repository into the "known_hosts" file:
$ sudo su tomcat -c "/opt/bitnami/git/bin/git ls-remote -h git@YOUR_REPOSITORY.git HEAD"
The authenticity of host 'ec2-xx-yy-zz.compute-1.amazonaws.com (xx.yy.zz)' can't be established. 
ECDSA key fingerprint is e5:xx:9d:yy:ff:89:55:47:aa:fd:b5:ee:0a:pp:6f:8d.
Are you sure you want to continue connecting (yes/no)? yes
Configure Git repository in Jenkins 
Before creating the first Job, it is necessary to configure the Git user and email that Jenkins will use to clone the repository. You can configure these options in "Manage Jenkins" -> "Configure System" -> "Git plugin" section
configuring-jenkins-git-2a.jpg
Then create a new Job in Jenkins and specify the Git repository.
create-job-jenkins-3.jpg
And run the Build. If everything was properly configured, Jenkins will checkout the code from the Git repository.

How to upgrade Jenkins?

If you want to upgrade Jenkins keeping your data, you just need to download the latest jenkins.war file, copy it in your apache-tomcat/webapps directory and restart Tomcat. It is recommended to create a backup of the previous jenkins.war file. You may want to revert to the previous version if you find any issues after upgrading.
Upgrading only Jenkins
On Linux and OSX you can execute the following steps to perform the above (notice that the installation directory is /opt/bitnami in the Bitnami virtual appliances and Bitnami Amazon Images):
 
$ cd
## Stop the server
$ ./ctlscript.sh stop
 
## Copy your previous .war file in case you need to restore it
$ cp apache-tomcat/webapps/jenkins.war apps/jenkins/jenkins.war.bak
 
## Remove jenkins all files to force Tomcat to deploy the new jenkins.war file
$ rm -r apache-tomcat/webapps/jenkins
$ rm -r apache-tomcat/webapps/jenkins.war
$ rm -r apache-tomcat/work/Catalina/localhost/jenkins
 
## Donwload the new version of jenkins
$ mv jenkins.war apache-tomcat/webapps/
 
## Start the server
$ ./ctlscript.sh start
On Windows you can stop the servers from the Start Menu entry or using the graphical tool that you can find in your installation directory. Using the file explorer go to where you installed the Bitnami Jenkins Stack. Copy the jenkins.war file from the apache-tomcat/webapps directory to apps/jenkins. Download the latest jenkins.war file and copy it in apache-tomcat/webapps. Now just start the server from the Start Menu or using the graphical tool.
Upgrading all the components
Alternatively to the process above, you can download a new Bitnami Jenkins Stack. You can install it to a different location (remember to stop the previous install so there are no port conflicts) and point it to your previous JENKINS_HOME path by editing the file  apache-tomcat/conf/Catalina/localhost/jenkins.xml.
If you are using a Bitnami virtual appliance or AMI you can start a new image with the latest jenkins version and move the content of /opt/bitnami/apps/jenkins/jenkins_home in your current installation to the new installation. Then restart the server.

How to enable SSL in Jenkins?

You can configure Apache Tomcat to enable SSL connections for accessing to the application using the HTTPS protocol. It is necessary to specify the Apache SSL certificate. If you do not have the cert you can create following these steps in the section below.
Check that you have the certificate file at "/installdir/apache-tomcat/conf/ssl/tomcat.cert.pem" and the certificate key file at "/installdir/apache-tomcat/conf/ssl/tomcat.key.pem".
To enable SSL you should uncomment the following line in the /installdir/apache-tomcat/conf/server.xml file:
8443
" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" disableUploadTimeout="true" acceptCount="100" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile="conf/myKeystore" keystorePass="your_password" SSLCertificateFile="installdir/apache-tomcat/conf/ssl/tomcat.cert.pem" SSLCertificateKeyFile="installdir/apache-tomcat/conf/ssl/tomcat.key.pem"/>
Then restart the Apache server and try to access at "https://localhost:8443".

How to create a SSL certificate for Jenkins?

You can find a detailed guide in the official Apache Tomcat documentation at http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html

Wednesday, May 6, 2015

Restart Jenkins from Web Interface

Navigate to:
  • [jenkins_url]/safeRestart. – This will restart Jenkins after the current builds have completed.
  • [jenkins_url]/restart – This will force a restart. Builds will not wait to complete.

Friday, April 10, 2015

Retry Logic in TestNG to re-run failed test-cases | TestNG | Jenkins

1| Assume you have a class file with 10 Methods [@Test]
2| Lets say one got failed due to Network issue
3| The class file, RetryAnalyzer will make the failed test-case to re-run with desired count; But, it display errors for all the test failures during re-run.
4| You are ought to add a Listener class, RetryTestListener; it will print the failure only once.
5| If the test got passed in the final count, failure exception won't be thrown in the console.


Test Class

@BeforeTest
public void setUp()
 {
 driver = new FirefoxDriver();
 baseUrl = "https://www.google.co.in";
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }

@Test(retryAnalyzer=RetryAnalyzer.class)
public void test01() throws Exception
 {
 driver.get(baseUrl + "/");
 String save = driver.findElement(By.id("als")).getText();
 System.out.println(save);
        // Assert.fail();
 Assert.assertEquals(save, "qwerty");
 }

**************************************************************

RetryAnalyzer.java

Create a Java class, 'RetryAnalyzer' inside the same package and paste the following snippet with minor edits.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class RetryAnalyzer implements IRetryAnalyzer  {
private int count = 0;
private int maxCount = 4; // set your count to re-run test
protected Logger log;
private static Logger testbaseLog;

static {
    PropertyConfigurator.configure("test-config/log4j.properties");
    testbaseLog = Logger.getLogger("TestclassName");
}

public RetryAnalyzer()
{
    testbaseLog.trace( " ModeledRetryAnalyzer constructor " + this.getClass().getName() );
    log = Logger.getLogger("TestclassName");
}

@Override
public boolean retry(ITestResult result) {
    testbaseLog.trace("running retry logic for  '"
            + result.getName()
            + "' on class " + this.getClass().getName() );
        if(count < maxCount) {                    
                count++;                                   
                return true;
        }
        return false;
}
}

******************************************************

RetryTestListener.java

import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import testng.TestCase;
import java.util.HashSet;
import java.util.Set;

/**
 * Listens for failed tests that need to be rerun.
 */
public class RetryTestListener extends TestListenerAdapter  {
    private static final  Logger logger = Logger.getLogger(RetryTestListener.class);
    private static int count = 1;
    private static final int maxCount = 7;

    @Override
    public void onTestFailure(ITestResult tr) {  
        tr.setAttribute("retry.count", count);
        tr.setAttribute("retry.maxCount", maxCount);
        boolean cond = false;
        if(count < maxCount) {
            count++;
            try  {
                if(TestCase.driver == null)  {
                    tr.setStatus(ITestResult.SKIP);
                    return;
                }
              
                 cond = true;
                if(cond)  {
                    tr.setAttribute("retry", true);
                }
            } catch(Exception e)  {
                logger.error("COULD NOT RETRY TESTCASE: "+e.getMessage());
            }

        } else  {
            logger.error("Number of retries expired.");
            tr.setStatus(ITestResult.FAILURE);
            // reset count
            count = 1;
        }
        super.onTestFailure(tr);
    }

    @Override
    public void onTestSuccess(ITestResult tr) {
        super.onTestSuccess(tr);
        count = 1;
    }
   
   
    @Override
    public void onFinish(ITestContext context) {
        for (int i = 0; i < context.getAllTestMethods().length; i++) {
            if (context.getAllTestMethods()[i].getCurrentInvocationCount() == 2) {
                if (context.getFailedTests().getResults(context.getAllTestMethods()[i]).size() == 2
                        || context.getPassedTests().getResults(context.getAllTestMethods()[i]).size() == 1) {
                    context.getFailedTests().removeResult(context.getAllTestMethods()[i]);
                }
            }
        }
       
    }
   
    private Set findDuplicates(Set listContainingDuplicates) {
        Set toRemove = new HashSet();
        Set testSet = new HashSet();
       
        for(ITestResult test : listContainingDuplicates)  {
            if (!testSet.add(test.getMethod())) {
                toRemove.add(test.getMethod());
            }   
        }
        return toRemove;
       
    }
}

Custom Groovy Script to display your details on Jenkins Build

pattern = ~/^.*\b("NEW-TC|NEW-TC)\b.*$/
def map = [:]
manager.build.logFile.eachLine { line ->
matcher = pattern.matcher(line)
if(matcher.matches()) {
       ownClass = matcher.group(0)
        sunClass = matcher.group(1)
        map[ownClass] = sunClass
}
}
if(map.size() > 0) {
   summary = manager.createSummary("notepad.png")
   summary.appendText("NEWLY ADDED TEST CASES !!!!", false, true, false, "black")
   map.each{ k, v -> summary.appendText("${k}", false) }
summary.appendText("", false)
}

pattern2 = ~/^.*\b("DEL-TC|DEL-TC)\b.*$/
def map2 = [:]
manager.build.logFile.eachLine { line ->
matcher2 = pattern2.matcher(line)
if(matcher2.matches()) {
       ownClass = matcher2.group(0)
        sunClass = matcher2.group(1)
        map2[ownClass] = sunClass
}
}
if(map2.size() > 0) {
   summary2 = manager.createSummary("notepad.png")
   summary2.appendText("DELETED TEST CASES !!!!", false, true, false, "black")
   map2.each{ k, v -> summary2.appendText("${k}", false) }
summary2.appendText("", false)
}

Java Code to compare the test-cases in xml for Jenkins and to modify the test-cases

CompareXml.Java

******************************
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;

public class CompareXml
{
    public static String readFile(String path, Charset encoding) throws IOException
    {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

    public static String stripNonValidXMLCharacters(String in)
    {
        StringBuffer out = new StringBuffer(); // Used to hold the output.
        char current; // Used to reference the current character.

        if (in == null || ("".equals(in)))
            return ""; // vacancy test.
        for (int i = 0; i < in.length(); i++) {
            current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
            if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF))
                || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF)))
                out.append(current);
        }
        return out.toString();
    }


    public static HashMap parse_xml(String xml_file) throws ParserConfigurationException, SAXException, IOException {
        HashMap xml_data = new HashMap();
        System.out.println(xml_file);

        String content = readFile(xml_file, Charset.defaultCharset());
        content = stripNonValidXMLCharacters(content);
        PrintWriter out = new PrintWriter(xml_file);
        out.println(content);
        out.close();
        InputStream inputStream= new FileInputStream(xml_file);
        Reader reader = new InputStreamReader(inputStream,"UTF-8");
        InputSource is = new InputSource(reader);
        is.setEncoding("UTF-8");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);

        //File fXmlFile = new File(xml_file);
        //DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        //DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        //Document doc = dBuilder.parse(new InpputSource(new InputStreamReader(fXmlFile, "UTF-8")));
        doc.getDocumentElement().normalize();
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("method");
        System.out.println("----------------------------");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                String[] parts = eElement.getAttribute("signature").split("@");
                xml_data.put(temp, parts[0]);
            }
        }
        return xml_data;
    }

    public static void compare_xmls() throws Exception
    {

            String currentBuild = System.getProperty("CURRENT_BUILD");
            String previousBuild = "";
            int prev_build_test = Integer.parseInt(currentBuild);
            prev_build_test = prev_build_test - 1;
            previousBuild = String.valueOf(prev_build_test);
            System.out.println("Current Build : "+currentBuild);
            System.out.println("Previous Build : "+previousBuild);

            String path = "/var/lib/jenkins/jobs//builds//testng/testng-results.xml";

            String currentPath = path.replace("", currentBuild);
            String prevPath = path.replace("", previousBuild);


            HashMap xml_data = new HashMap();
            HashMap xml_data2 = new HashMap();
            HashMap final_xml_data = new HashMap();
            HashMap diff_xml_data = new HashMap();
            String usrdir = System.getProperty("user.dir");

            xml_data = parse_xml(currentPath);
            xml_data2 = parse_xml(prevPath);

            System.out.println("First Hashmap Size : "+ xml_data.size());
            System.out.println("Second Hashmap Size : "+ xml_data2.size());

            int temp1=0;
            for (int itr = 0; itr < xml_data.size(); itr++) {
                if (!xml_data2.containsValue(xml_data.get(itr))) {
                    final_xml_data.put(temp1, xml_data.get(itr));
                    temp1 = temp1 +1;
                }
            }
            System.out.println("Newly Added TCs Hashmap Size : "+ final_xml_data.size());

            int temp2 = 0;
            for( String s : xml_data2.values())
            {
                if (!xml_data.containsValue(s)) {
                    diff_xml_data.put(temp2, s);
                    temp2 = temp2 + 1;
                }
            }

            System.out.println("Deleted TCs Hashmap Size : " + diff_xml_data.size());

            HashSet final_xml_data_values = new HashSet();
            final_xml_data_values.addAll(final_xml_data.values());

            HashSet diff_xml_data_values = new HashSet();
            diff_xml_data_values.addAll(diff_xml_data.values());

            System.out.println("Newly Added Test-Cases Below : ");
            for (String str : final_xml_data_values){
                System.out.println("NEW-TC : " + str);
            }

            System.out.println("\n\n********************************");
            for (String str : diff_xml_data_values){
                System.out.println("DEL-TC : " + str);
            }

            System.out.println("Deleted Test-Cases Below : ");

    }
        public static void main(String args[]) throws Exception {
                compare_xmls();
    }

}





*******************************************************************************

ModifyXml.java

****************************

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.xml.parsers.DocumentBuilder;
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;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ModifyXml
{
    public static String readFile(String path, Charset encoding) throws IOException
    {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

    public static String stripNonValidXMLCharacters(String in)
    {
        StringBuffer out = new StringBuffer(); // Used to hold the output.
        char current; // Used to reference the current character.

        if (in == null || ("".equals(in)))
            return ""; // vacancy test.
        for (int i = 0; i < in.length(); i++) {
            current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
            if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF))
                || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF)))
                out.append(current);
        }
        return out.toString();
    }

    public static void parse_xml(String xml_file, String... test_names) throws Exception
    {
        String content = readFile(xml_file, Charset.defaultCharset());
        content = stripNonValidXMLCharacters(content);
        PrintWriter out = new PrintWriter(xml_file);
        out.println(content);
        out.close();
        InputStream inputStream = new FileInputStream(xml_file);
        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        InputSource is = new InputSource(reader);
        is.setEncoding("UTF-8");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);

        // File fXmlFile = new File(xml_file);
        // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        // Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("test-method");
        System.out.println("----------------------------");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                String status = eElement.getAttribute("status");
                String name = eElement.getAttribute("name");
                for (String test_name : test_names) {
                    if (name.equalsIgnoreCase(test_name)) {
                        System.out.println("Signature : " + eElement.getAttribute("signature"));
                        System.out.println("Status : " + eElement.getAttribute("status"));
                        if (status.contains("FAIL")) {
                            eElement.setAttribute("status", "PASS");
                        }
                        System.out.println("Signature : " + eElement.getAttribute("signature"));
                        System.out.println("Status : " + eElement.getAttribute("status"));
                    }
                }
            }
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, new StreamResult(new FileOutputStream(xml_file)));

        System.out.println("File updated!");
    }

    public static void modify_xml() throws Exception
    {
        String currentBuild = System.getProperty("CURRENT_BUILD");
        String test_names = System.getProperty("TEST_NAMES");
        String path = "/var/lib/jenkins/jobs//builds//testng/testng-results.xml";
        String currentPath = path.replace("", currentBuild);

        parse_xml(currentPath, test_names.split(","));

    }

    public static void main(String args[]) throws Exception
    {
        modify_xml();
    }

}


My Profile

My photo
can be reached at 09916017317