Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Tuesday, January 22, 2019

Java 8: How to check date is valid future date.

Check if a date is a valid future date. 

As a developer we come across many scenarios where we want to validate the user selected date is the correct future date.  

Java 8 provides many useful classes and methods under Date Time API. Below code snippet checks if the date is a valid future date. 



        /**
  * DateTime function which checks for the valid future date.
  * 
  * @author ajain5
  * @param futureDate
  *            : in dd-mm-yyyy or dd/mm/yyyy format
  * @return true if futureDate isAfter currentDate
  */
 public boolean isValidFutureDate(String futureDate) {
  String date[] = futureDate.split("[\\/-]");
  int day = Integer.parseInt(date[0]);
  int month = Integer.parseInt(date[1]);
  int year = Integer.parseInt(date[2]);

  LocalDate today = LocalDate.now();
  return today.isBefore(LocalDate.of(year, month, day));

 }


You can test the above code using below driver program. 


System.out.println(new Ti().isValidFutureDate(args[0]));

Response after running the above program :


Current date : 22-01-2019

The above program was tested on 22-Jan-2019 .

Wednesday, January 31, 2018

Version one useful Restful web service to get the test case detail using test case id.



version one api to get the Test case details using Test Case ID 

http://Your_Version_ONE_URI/rest-1.v1/Data/Test?where=Number="AT-57708"


Where, Your_Version_ONE_URI looks like below :

--> https://www3.v1host.com/DieHardTechy

NOTE: 
  • To call the above api from postman you need to use basic authentication with your version one username and password.
  • If AT-57708 id exists in Version one , Above API gives the XML response containing details about that Test case. 


Sample response : 



<?xml version="1.0" encoding="UTF-8"?>
<Assets total="1" pageSize="2147483647" pageStart="0">
    <Asset href="/DieHardTechy/rest-1.v1/Data/Test/1215543" id="Test:1215543">
        <Attribute name="AssetType">Test</Attribute>
        <Relation name="GeneratedFrom" />
        <Relation name="SecurityScope">
            <Asset href="/DieHardTechy/rest-1.v1/Data/Scope/8686" idref="Scope:8686" />
        </Relation>
        <Relation name="Super" />
        <Relation name="Team" />
        <Relation name="Parent">
            <Asset href="/DieHardTechy/rest-1.v1/Data/Story/408352" idref="Story:408352" />
        </Relation>
        <Relation name="Status" />
        <Relation name="Category">
            <Asset href="/DieHardTechy/rest-1.v1/Data/TestCategory/116" idref="TestCategory:116" />
        </Relation>
        <Relation name="Timebox" />
        <Relation name="Scope">
            <Asset href="/DieHardTechy/rest-1.v1/Data/Scope/8686" idref="Scope:8686" />
        </Relation>
        <Attribute name="Number">AT-57708</Attribute>
        <Attribute name="VersionTested" />
        <Attribute name="ActualResults" />
        <Attribute name="ExpectedResults">This is expected result</Attribute>
        <Attribute name="Steps">Subscribe to die hardtechy blog</Attribute>
        <Attribute name="Order">1077139536</Attribute>
        <Attribute name="Description">Call GET API without passing any Parameter</Attribute>
        <Attribute name="Name">Subscribe</Attribute>
        <Attribute name="AssetState">64</Attribute>
        <Attribute name="SecurityScope.Name">DieHardTechy API</Attribute>
        <Attribute name="Parent.Name">Regression Test Cases</Attribute>
        <Attribute name="Parent.Number">B-09384</Attribute>
        <Attribute name="Status.Name" />
        <Attribute name="Category.Name">Functional</Attribute>
        <Attribute name="Timebox.Name" />
        <Attribute name="Scope.Name">DieHardTechy API</Attribute>
        <Attribute name="TaggedWith">
            <Value>SANITY</Value>
        </Attribute>
        <Attribute name="Ideas" />
        <Relation name="Owners">
            <Asset href="/DieHardTechy/rest-1.v1/Data/Member/153428" idref="Member:153428" />
        </Relation>
        <Attribute name="Owners.Name">
            <Value>xyz abc</Value>
        </Attribute>
        <Attribute name="Owners.Nickname">
            <Value>xyz</Value>
        </Attribute>
    </Asset>
</Assets>



Wednesday, January 3, 2018

What is the best way to check element not present in webpage using selenium webdriver ?


Best Way of checking element not present in webpage using selenium webdriver ?


Often encountered a situation where you have to verify an element is not present in the web page. 

using 


try {

        driver.findElement(locatorKey);

        Assert.assertTrue(false);

    } catch (org.openqa.selenium.NoSuchElementException e) {

        Assert.assertTrue(true);

    }

 


is not a right approach. Because this is layman way of asserting absence of web element.

As per selenium documantaion, best way to check if element is not present is using findElements and then asseting on the size of the list returned. 

findElements does not throw any exception in case if an element is not present. Asserting on 0 length is more appropriate for absence of an element. 

Selenium official comment : 




Jenkins Restful API with Java : Create, abort, build new jobs using API


Jenkins RestFul APIs for Abort, Creating and Building a Job.

How to abort a Jenkins Job using REST API in java.


Below is the Java method to abort a jenkins Job using REST API.

Please note you can use your own api client to post this request.

Please change the IP and PORT according to your Jenkins IP and PORT.


public  String abortJob(String jobName, String buildNumber) {
  String abortURL = "http://192.168.1.1:8080/job/" + jobName + "/"+buildNumber+"/stop";
  Client client = Client.create();

  client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter("taas", "taas"));
  WebResource webResource = client.resource(abortURL);
  ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, null);
  String jsonResponse = response.getEntity(String.class);
  client.destroy();
  return jsonResponse;

 }

How to get the list of all idle nodes from Jenkins using REST API in java.

Please change ip address with your jenkins IP and port

REQUEST TYPE : GET


public ArrayList<String> getIdleVmsList() {

  String response = callAPI("http://192.168.1.1:8080/computer/api/json");
  return parseResponse(response);

 }

 public ArrayList<String> parseResponse(String response) {

  ArrayList<String> idleVm = new ArrayList<String>();

  JSONObject stat = new JSONObject(response);
  JSONArray computer = stat.getJSONArray("computer");

  for (int i = 0; i < computer.length(); i++) {
   JSONObject info = (JSONObject) computer.get(i);
   info.getJSONObject("monitorData");
   String master = (String) info.get("displayName");
   Boolean vmOfflineStatus = (Boolean) info.get("offline");
   Boolean vmIdleStatus = (Boolean) info.get("idle");
   if (!vmOfflineStatus && vmIdleStatus && !master.equalsIgnoreCase("master")) {
    idleVm.add((String) info.get("displayName"));

   }

  }

  return idleVm;

 }

 public static String callAPI(String Url) {
  Client client = Client.create();
  try {
   client.addFilter(new HTTPBasicAuthFilter("username", "pwd"));
   WebResource webResource = client.resource(Url);
   ClientResponse response = webResource.get(ClientResponse.class);
   String jsonResponse = response.getEntity(String.class);

   client.destroy();
   return jsonResponse;
  } catch (Exception e) {
   return "couldnot call jenkins get API";
  }

 }

How to build a job using REST API. 


REST URL : http://192.168.1.1:8080/job/jobName/build?delay=0

METHOD TYPE : POST

where JobName is the name of your jenkins job.


Please contact us for more Restful web services of Jenkins. 

Wednesday, April 19, 2017

How to get all the annotated classes of a package with same attribute value?

One of the most common problem when using annotation is to find the classes based upon the attribute value of an annotation. 


Problem-statement: Find all the classes in com.annot package which have @ExampleAnnot annotation and attribute value of author in @ExampleAnnot is dht.

To achieve this we will need the following jars.

1. javassist-3.12.1.GA.jar  which can be Download  from here.

2. org.reflections.0.9.11.jar which can be Download from here


Add both the jar files in your classpath. 



Example code: 


package annot;

import java.util.Set;

import org.reflections.Reflections;
import org.testng.TestListenerAdapter;

public class Lists extends TestListenerAdapter {
 
 public static void main(String[] args) {
  Reflections reflections = new Reflections("com.annot");
  Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(ExampleAnnot.class);
  
  for(Class<?> c:annotated)
  {
   ExampleAnnot declaredAnnotation = c.getDeclaredAnnotation(ExampleAnnot.class);
   if(declaredAnnotation.author().equals("dht"))
   {
    System.out.println(c.getName());
   }
  }
  
 }

}


The above example first finds all the classes with @ExampleAnnot annotation, then sequentially checks the author attribute from @ExampleAnnot of each class , and if author value is equal to dht, it prints the well qualified name of all those class.
Above example returns all the classes which have author name as dht. 



Happy coding. Let us know if you are stuck somewhere.


 

Authorize an user using LDAP authentication in Java.

LDAP authentication is now-a-days very useful for enterprises application. LDAP also acts as source of SSO [Single sign on]. Ldap stands for Lightweight Directory Access Protocol , in this post we are basically trying to authenticate an user using his windows credentials with Java. 





Prerequisite :

1. Java version 1.7 or higher

2. Springs 

3. You need to know your organizations LDAP url ,port number , username and password of manager account or service account.


Spring provides LDAP template which we can use for easy querying of LDAP server.


Below is the example code of LDAP authentication:




package dht.test.ldap.unittest;

import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;


public class LdapTest {

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

  LdapContextSource contextSource = new LdapContextSource();
  contextSource.setUrl("ldaps://Your-ldap-url-COM:portnum");
  contextSource.setBase("OU=org,DC=corp,DC=die,DC=com");
  contextSource.setUserDn("autoaccount01");
  contextSource.setPassword("We1c0me2ldap");
  contextSource.afterPropertiesSet();

  LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
  ldapTemplate.afterPropertiesSet();

  boolean b = new LdapTest().authenticate(ldapTemplate, "dht3", "Dht@123");
  System.out.println("Authentication " + b);

 }

 public boolean authenticate(LdapTemplate ldapTemplate, String userName, String password) {
  AndFilter filter = new AndFilter();
  filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("sAMAccountName", userName));
  return ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);

 }

}



 Above program returns Authentication successful if user has provided valid login credentials, false otherwise. 



Happy coding. Let us know if you get stuck somewhere.













Tuesday, April 18, 2017

Solution: java.lang.AbstractMethodError: org.testng Error





How to solve 


java.lang.AbstractMethodError: org.testng.remote.RemoteTestNG$DelegatingTestRunnerFactory.newTestRunner(Lorg/testng/ISuite;Lorg/testng/xml/XmlTest;Ljava/util/Collection;)Lorg/testng/TestRunner;
    at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:587)
    at org.testng.SuiteRunner.init(SuiteRunner.java:161)
    at org.testng.SuiteRunner.<init>(SuiteRunner.java:114)
    at org.testng.TestNG.createSuiteRunner(TestNG.java:1290)
    at org.testng.TestNG.createSuiteRunners(TestNG.java:1277)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1131)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:207)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:178)

error ?

This is one of the common issue people face when running testng suites. 

Most common reason is conflicting of testng versions. May be there are 2 versions of testng in your classpath , which are causing this issue.

Check your maven dependency from Build path

[Right click on project-->Build Path -->Configure build path --> Maven dependency and check for testng]

if there are 2 version of testng, delete one. 

This should solve your problem.

If you get stuck somewhere, contact us here : Email

Saturday, September 3, 2016

How to get Test Case Detail from testlink using TestLink Java API?

Getting test case detail from testlink using API is quite needful when displaying results in Reports.

To get test case related detail you will need testlink-java-api.

Prerequisite:


  1. TestLink-Java-API
  2. Java 1.7 or higher
  3. Maven

Since, TestLink-Java-API depends on mulitple other jars, it ia adviceable to create a Maven project and add the below dependencies in POM.XML


<dependencies>
  <!-- Commons APIs -->
  <dependency>
   <groupId>commons-lang</groupId>
   <artifactId>commons-lang</artifactId>
   <version>2.6</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <!-- Logging APIs -->
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.7.21</version>
  </dependency>
  <!-- Configuration APIs -->
  <dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.10</version>
  </dependency>
  <!-- XML-RPC related APIs -->
  <dependency>
   <groupId>org.apache.xmlrpc</groupId>
   <artifactId>xmlrpc-common</artifactId>
   <version>3.1.3</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>xml-apis</groupId>
   <artifactId>xml-apis</artifactId>
   <version>2.0.2</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>commons-httpclient</groupId>
   <artifactId>commons-httpclient</artifactId>
   <version>3.1</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>br.eti.kinoshita</groupId>
   <artifactId>testlink-java-api</artifactId>
   <version>1.9.14-0</version>
  </dependency>
<dependencies>


Use the below code to retrieve Test case description, Steps to execute, Expected results etc. using External test case id.


public void getTestDetailFromTestLink() {
  String testCaseDescription = "", expectedResults = "", steps = "";
  URL url;
  try {
   url = new URL("http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php");

   String devKey = "5062c3fertf9b8886e0edd0ffdf6b14";
   TestLinkAPI api = new TestLinkAPI(url, devKey);
   TestCase tCase = api.getTestCaseByExternalId("P1-46039", 1);

   testCaseDescription = tCase.getSummary();

   List<TestCaseStep> list = tCase.getSteps();
   Iterator<TestCaseStep> itr = list.iterator();
   while (itr.hasNext()) {
    TestCaseStep tcs = itr.next();
    expectedResults = tcs.getExpectedResults();
    steps = tcs.getActions();

   }
  } catch (Exception e) {
   e.printStackTrace();
  }

  System.out.println("Description :"+testCaseDescription);
  System.out.println("Expected Result :"expectedResults);
  System.out.println("Steps to Execute :"+steps);
  
 }


Above code produces the below output.

Description :Verify that on selecting Die Hard Techy from Side menu takes user to blog screen.

Expected Result :User should be navigated to Screen.

Steps to Execute :1.Open DieHardTechy website. 2.Select Die Hard Techy.