Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, December 29, 2016

Java Telnet example : testing remote service state



In most of the cases in daily job, you must have get into some situation where you needed to telnet to a machine. Although telnet is not a secure way to access remote machine, but still it can be useful if all we want to know if the particular service port on particular machine is running or not(for example you want to check say on local ip address 192.168.110 on port 3389 the RDP service is running or not and there may be other cases)

Below, we will be showing up sample code in java which you can use the automate the process. This can also be used anywhere like if you are writing a service to report health of the multiple services, just a case.

import org.apache.commons.net.telnet.TelnetClient;

import java.io.IOException;
import java.net.ConnectException;

public class JavaTelnetExample {

    private static final String RDP_SERVER = "10.66.6.62.1";
    private static final int RDP_SERVER_PORT = 3389;
    private static final String HTTP_SERVER = "10.66.62.2";
    private static final int HTTP_SERVER_PORT = 80;
    // Similar to above you can test state for number of other services on number of other machines
    public static void main(String[] args) {
        System.out.println("Rdp service status on server ip : " + RDP_SERVER + " , port : " + RDP_SERVER_PORT + " = " + isServiceRunning(RDP_SERVER, RDP_SERVER_PORT));
        System.out.println("Ssh service status on server ip : " + HTTP_SERVER + " , port : " + HTTP_SERVER_PORT + " = " + isServiceRunning(HTTP_SERVER, HTTP_SERVER_PORT));

    }

    // If able to connect successfully, return true for service state else return false.        
    private static boolean isServiceRunning(String ip, int port) {
        try {
            TelnetClient telnetClient = new TelnetClient();
            telnetClient.connect(ip, port);
            return true;
        } catch (ConnectException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
}

Note:
To run this code, you can download the dependencies 'Apache Commons Net' from the https://mvnrepository.com/artifact/commons-net/commons-net depending upon build tool you are using maven/gradle or jar file

Feel free to leave comment if you get any issue or any suggestion.

Sunday, March 20, 2016

Connecting to MySql from java with Maven

In this example we will be creating a simple maven java project to connect to the local mysql instance, without actually installing any jdbc connector and setting it to classpath (maven will take care of this :))

1. Add MySQL connector maven dependency in the pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.automatethebox</groupId>
    <artifactId>mysql-connect-maven</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>
</project>

2. Sample java source file: Connecting to local mysql instance and listing tables;

package com.automatethebox.mysql_connect_maven;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySqlConnectionWithMaven {

    public static void main(String[] args) {

        // Databases url (here 'information_schema' is database name)
        String databaseUrl = "jdbc:mysql://localhost/information_schema";
        String jdbcConnectorClass = "com.mysql.jdbc.Driver";
        String mysqlUser = "root";
        String myUserPass = "Admin@123";
        String query = "Select distinct(table_name) from INFORMATION_SCHEMA.TABLES";

        try {
            Class.forName(jdbcConnectorClass);
            Connection connection = DriverManager.getConnection(databaseUrl, mysqlUser, myUserPass);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                System.out.println("Table : " + tableName);
            }
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Friday, March 4, 2016

Disable Java JVM Default DNS Caching


You can disable the Java Virtual machine default DNS caching following any of the below methods
( By Default java 1.6 caches all the DNS queries ):



  • Method 1(Changes while staring up JVM)
    • Add -Dsun.net.inetaddr.ttl=0 while starting up the JVM.

  • Method 2(Changes in java config file)
    • Add/Edit the property networkaddress.cache.ttl=0 in %JRE%/lib/security/java.security file. Here JRE refers to Java Runtime Environment folder.

  • Method 3(Changes in your code)
    • Set the property in you java code as java.security.Security.setProperty("networkaddress.cache.ttl", "0" );

Saturday, December 12, 2015

Some helpful commands to build multi-module maven project tests

Build and execute tests from all the sub modules


  • mvn clean install

Build and execute tests from a specific sub module


  • mvn clean install -pl <module-name> -am

Build and execute a specific test from a specific sub module


  • mvn -DfailIfNoTests=false -Dtest=<test-class-name> clean install -pl <module-name> -am
  • mvn -DfailIfNoTests=false -Dtest=<test-class-name#test-method-name> clean install -pl <module-name> -am

Saturday, January 3, 2015

Running Selenium Webdriver tests on Internet Explorer browser

So finally added support to execute tests on Internet Explorer browser also in my github project https://github.com/lalit-k/selenium-java-tests.

3 Simple steps to add Internet Explorer support in Selenium Webdriver project:
  1. Download the IEDriverServer.exe , you can download the latest version from http://selenium-release.storage.googleapis.com/index.html for your target operating system.[download url may change, you can google latest if it changes]
  2. Extract the IEDriverServer.exe from the downloaded zip, and place in your project resources folder.
    IEDriverServer.exe
  3. Now, go to the Driver script where you are initializing the IEDriverServer and add the below code line to initialize the IEDriverServer.

System.setProperty("webdriver.ie.driver", <full system path of the IEDriverServer.exe. Example: c:\tests\resources\IEDriverServer.exe>);
WebDriver driver = new InternetExplorerDriver();

Tip : you can use the "System.getProperty("user.dir");" to get the current working directory and then append the path to IEDriverServer.exe
System.getProperty("user.dir")
You can also view the complete code changes for your reference at https://github.com/lalit-k/selenium-java-tests/commit/d1dc4cd3f878d64a4119fc0d6297df026a07cf5a

Running Selenium Webdriver tests on Google Chrome browser

Few months back i had added the support to execute tests on Google Chrome browser in my github project https://github.com/lalit-k/selenium-java-tests , so i thought to write it down how you can do the same if needed in your project.

3 Simple steps to add Google Chrome support in Selenium Webdriver project:
  1. Download the ChromeDriver.exe , you can download the latest version from http://chromedriver.storage.googleapis.com/index.html for your target operating system.[download url may change, you can google latest if it changes]
  2. Extract the chromedriver.exe from the downloaded zip, and place in your project resources folder.
    Add Chromedriver.exe
  3. Now, go to the Driver file where you are initializing the ChromeDriver and add the below code line to initialize the ChromeDriver.

System.setProperty("webdriver.chrome.driver", <full system path of the chromedriver.exe. Example: c:\tests\resources\chromedriver.exe>);
WebDriver driver = new ChromeDriver();

Tip : you can use the "System.getProperty("user.dir");" to get the current working directory and then append the path to chromedriver.exe


System.getProperty("user.dir")


You can also view the complete code changes for your reference at https://github.com/lalit-k/selenium-java-tests/commit/01cda755f72918a417b7b0cded1b2db4c387eb70

Wednesday, July 23, 2014

Address is invalid on local machine, or port is not valid on remote machine


This issue is caused generally when your Java attempts to use an IPV6 address, where either OS does not support it or its not set up properly. You may get this issue while running your java program from CMD, Java IDE or when downloading jar dependency using maven etc.

So, to resolve this you just need to tell your java code to use IPV4 instead of IPV6 :)

"To fix when running from Command prompt. Just add the properly as: "
java -Djava.net.preferIPv4Stack=true <Your Java Class to Run>

" TO fix when running from Java IDE. Suppose Intellij IDEA: "
Set the property under Run -> Edit Configuration

Monday, June 30, 2014

How to Disable Selenium HtmlUnitDriver logging

Recently, while working on a project using Selenium HtmlUnitDriver, i found that it generates too much log messages by default to output console which really fills the screen with non wanted messages.


So, like me some of you may also get this and wanted to resolve the same. What i did is added the below code statements to suppress the logging messages.


LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF); 

and it Worked :) :)

Saturday, May 3, 2014

Handle Sharepoint HTTP basic window authentication - using selenium webdriver java


import org.openqa.selenium.Alert;
import java.awt.*; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent;
// Switch to alert window. Alert authenticationWindow = driver.switchTo().alert();
// Type the username/email. authenticationWindow.sendKeys("<username/email address>");
// Shift cursor focus to password input text field. Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_TAB);
// Type the password in password field. [ Selenium does not know at this point that the cursor focus is shifted, so calling Alert class instance sendKeys() will cause password to be typed in username field. So, we are copying the password first to windows clipboard and then pasting it directly into the password field using  Robot class instance ] StringSelection stringSelection = new StringSelection("<user password>"); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,null); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL);
// Accept the authentication window. robot.keyPress(KeyEvent.VK_ENTER);

Sunday, January 5, 2014

Tuesday, January 22, 2013

How to create Maven in-project repository


Pre-requisites :You should have Maven installed on your system.

In my example i am using "sshxcute-1.0" jar file. You can download it from link https://code.google.com/p/sshxcute/"

Follow the below steps :

1. Create a "lib" folder in your java project.(Actually the name does'nt matter you can use "library" instead or whatever you like)

2. Copy the "sshxcute-1.0" jar file in "lib" folder.

3. Open command prompt and navigate to "lib" folder, then execute following command.(In my case 'sshxcute-1.0.jar' file is at "c:\project\src\com\lib" location,so you need to change file locations in below  command accordingly)

mvn deploy:deploy-file -Durl=file:///c:\project\com\src\lib -Dfile=sshxcute-1.0.jar -DgroupId=com.automatethebox -DartifactId=automatethebox -Dpackaging=jar -Dversion=1.0

 Note that you get BUILD SUCCESS on console output after running the command.



4. Now go to your project "lib" directory, and notice that an package "com.automatethebox.apis" is created.This is your in-project maven repositoy.

5. Now Open the project "pom.xml" file

6. Add following dependency in pom.xml file :

<dependencies>
        <dependency>
            <groupId>com.automatethebox</groupId>
            <artifactId>apis</artifactId>
            <version>1.0</version>
        </dependency>
</dependencies>

7. Add following repository in pom.xml file :

<repositories>
        <repository>
            <id>project.local</id>
            <name>project</name>
            <url>file:${project.basedir}/src/com/lib</url>  
        </repository>
</repositories>

NOTE : You need to update this path in url according to your project.

8 .Then refresh the Maven dependencies for the project using your IDE Maven > Reimport option.

All done, now you can use the classes from the Jar file and maintain your Maven project with your in-project Maven repository.

Friday, October 26, 2012

How to locate element in Html 'svg' tag in Selenium 2(Webdriver)


Sample svg code enbeded into Html code
 <html>  
 <head>  
 <title>automatethebox.blogspot.com</title>  
 </head>  
 <body>  
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="939" height="360">  
 <defs>  
 <g zIndex="10">  
 <tspan x="5.5">You</tspan>  
 </g>  
 <g zIndex="20">  
 <tspan x="5.5">Me</tspan>  
 </g>  
 <g zIndex="30">  
 <tspan x="5.5">None</tspan>  
 </g>  
 </svg>  
 </body>  
 </html>  
Selenium 2 (Webdriver) code to locate and intract with an svg element embeded into HTML 
Suppose in above given svg code three buttons are embeded into the svg.
Now we will be finding the button and be clicking on them using 'css locators'.Here we go....

Method 1
 // First of all find the 'svg' tag in the page and save it into as WebElement instance.  
 WebElement svgElement = driver.findElement(By.cssSelector("svg"));  
   
 // Get the Buttons with which we want to interact in a list  
 List<WebElement> gElements = svgElement.findElements(By.cssSelector("g"));  
   
 // Click on 'Me' Button  
 WebElement button = gElements.get(0).findElement(By.cssSelector("tspan");  
 button.click();  
   
 // Click on 'You' Button  
 WebElement button = gElements.get(1).findElement(By.cssSelector("tspan");  
 button.click();  
   
 // Click on 'None' Button  
 WebElement button = gElements.get(2).findElement(By.cssSelector("tspan");  
 button.click();  
Method 2
 // Locate buttons and save in the WebElement instances.  
 WebElement meButton = driver.findElement(By.cssSelector("//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']//*[local-name()='tspan' and text()='Me']"));  
 WebElement youButton = driver.findElement(By.cssSelector("//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']//*[local-name()='tspan' and text()='You']"));  
 WebElement noneButton = driver.findElement(By.cssSelector("//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']//*[local-name()='tspan' and text()='None']"));  
   
 // Click on the buttons.  
 meButton.click();  
 youButton.click();  
 noneButton.click();  

Wednesday, October 24, 2012

How to switch between browser windows in Selenium 2 (WebDriver Java)

 // Store you current window handle in a String variable.  
 String parentWindow = driver.getWindowHandle();  
   
 // Click on the the page element which causes a new window to be opened,suppose a link.  
 driver.findElement(BY.linkText("myLink")).click();  
   
 // Get the window handle of the new browser window opened.  
 String childWindow = (String) driver.getWindowHandles().toArray()[1];  
   
 // Switch to newly opened window.  
 driver.switchTo().window(childWindow);  
   
 // Switch back to main window.  
 driver.switchTo().window(parentWindow);  


© automatethebox. All Rights Reserved

AWS Certified Solutions Architect Associate - AWS Introduction - Questions

All the Best !!! Show Result !! Try Again !! ×