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

Monday, July 27, 2020

Selenium testing in JAVA

Following JAVA code can be used to test web application with login page, filtering data and submit form.

You have to install web browser driver. I used chrome driver.

pom.xml

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>
 
JAVA code


System.setProperty("webdriver.chrome.driver","./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();

String baseUrl = "https://testwebsite/login";

driver.get(baseUrl);

//maximizing window

driver.manage().window().maximize();

//get login form details

WebElement username = driver.findElement(By.name("username"));
WebElement password = driver.findElement(By.name("password"));
WebElement login = driver.findElement(By.xpath("//input[@value='Login']"));

// login to site

username.sendKeys("admin");
password.sendKeys("admin@123");
login.click();

// filtering using placeholder

WebElement fullName = driver.findElement(By.xpath("//input[@placeholder='Filter Full Name']"));
WebElement country = driver.findElement(By.xpath("//input[@placeholder='Filter Country']"));
WebElement filter = driver.findElement(By.xpath("//input[@value='Filter']"));

// filter sujith & Sri Lanka

fullName.sendKeys("Sujith");
country.sendKeys("Sri Lanka");
filter.click();

// add new record to list 

WebElement add = driver.findElement(By.xpath("//*[text()='Add New']"));
add.click();

//filter by name

WebElement frmFullName = driver.findElement(By.name("fullName"));
WebElement frmAge = driver.findElement(By.name("age"));
WebElement frmAddress = driver.findElement(By.name("address"));
//filter by placeholder
WebElement frmBirthPicker = 
driver.findElement(By.xpath("//input[@placeholder='yyyy-mm-dd']"));
WebElement frmCountry = driver.findElement(By.name("country"));
//filter by parent input with 'GIT' label
WebElement frmGIT = driver.findElement(By.xpath("//label[contains(., 'GIT')]/parent::*//input"));
WebElement frmHTML = driver.findElement(By.xpath("//label[contains(., 'HTML')]/parent::*//input"));
WebElement frmMale = driver.findElement(By.id("Male"));

frmFullName.sendKeys("Test full name");

frmAge.sendKeys("24");
frmAddress.sendKeys("Test address1");
frmBirthPicker.sendKeys("2010-10-10");
frmCountry.sendKeys("Sri Lanka");
//checking buttons
frmGIT.click();
frmHTML.click();
frmMale.click();

//submitting form  

WebElement submit = driver.findElement(By.xpath("//input[@value='Submit']"));
submit.click();
    
// driver.close();

Friday, October 18, 2019

use VisualVM to monitor JAVA application

Run the JAVA application with the following options.

java8 -jar 
-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port=8662 
-Dcom.sun.management.jmxremote.rmi.port=8662 
-Dcom.sun.management.jmxremote.local.only=false 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false 
-Xms32m 
-Xmx128m 
TestVisualVM.jar

Now, connect the remote JMX session in 8662 port in VisualVM to monitor application.

Thursday, May 23, 2019

Authenticate AD user in JAVA

Use following JAVA applications to authenticate AD user in JAVA. More information can be found on following URL.

https://stackoverflow.com/questions/390150/authenticating-against-active-directory-with-java-on-linux

import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;

class App2 {

    public static void main(String[] args) {

        String domainName;
        String serverName;

            domainName = "mobitel.int";
            serverName = "HO-AD-001";
        

        String username = "sujith";
        String password = "passwd";

        System.out
                .println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);

        // bind by using the specified username/password
        Hashtable props = new Hashtable();
        String principalName = username + "@" + domainName;
        props.put(Context.SECURITY_PRINCIPAL, principalName);
        props.put(Context.SECURITY_CREDENTIALS, password);
        DirContext context;

        try {
            context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
            System.out.println("Authentication succeeded!");

            // locate this user's record
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SUBTREE_SCOPE);
            NamingEnumeration renum = context.search(toDC(domainName),
                    "(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
            if (!renum.hasMore()) {
                System.out.println("Cannot locate user information for " + username);
                System.exit(1);
            }
            SearchResult result = renum.next();

            List groups = new ArrayList();
            Attribute memberOf = result.getAttributes().get("memberOf");
            if (memberOf != null) {// null if this user belongs to no group at all
                for (int i = 0; i < memberOf.size(); i++) {
                    Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
                    Attribute att = atts.get("CN");
                    groups.add(att.get().toString());
                }
            }

            context.close();

            System.out.println();
            System.out.println("User belongs to: ");
            Iterator ig = groups.iterator();
            while (ig.hasNext()) {
                System.out.println("   " + ig.next());
            }

        } catch (AuthenticationException a) {
            System.out.println("Authentication failed: " + a);
            System.exit(1);
        } catch (NamingException e) {
            System.out.println("Failed to bind to LDAP / get account information: " + e);
            System.exit(1);
        }
    }

    private static String toDC(String domainName) {
        StringBuilder buf = new StringBuilder();
        for (String token : domainName.split("\\.")) {
            if (token.length() == 0)
                continue; // defensive check
            if (buf.length() > 0)
                buf.append(",");
            buf.append("DC=").append(token);
        }
        return buf.toString();
    }
}

Monday, October 2, 2017

JAVA application Monitoring using JMX

Your application can be started with following JMX parameter.

-Dcom.sun.management.jmxremote.port=12345

Or

You can set System property as JMX port as follows to enable JMX monitoring.

System.setProperty("com.sun.management.jmxremote.port", 12345);

Then, use VisualVM to monitor your application. You can monitor CPU, Memory, Threads etc using this VisualVM tool.

https://visualvm.github.io/

For more information visit :-

https://dzone.com/articles/java-memory-and-cpu-monitoring-tools-and-technique


Sunday, December 18, 2016

Create soft link in Linux

Suppose you want to create shortcuts in Linux, you can use 'ln -s' command to create soft links.

Ex :- If you need to run JAVA6 and JAVA8 both from terminal, you have to add java6 and java8 commands to /usr/bin for terminal execution.

Steps to keep java6 and java8.

  1. Create two files in /usr/bin/ as java6 and java8
  2. Extract JAVA6 and JAVA8 to Linux file system. Suppose directory locations are /usr/java6/ and /usr/java8/
  3. Create Soft links for java6 and java8 using the following commands as root.

ln -s /usr/java8/jdk1.6.0_10/bin/java /usr/bin/java6

ln -s /usr/java8/jdk1.8.0_12/bin/java /usr/bin/java8

Now check versions using following commands in terminal.

java6 -version
java8 -version

Tuesday, November 29, 2016

Change enum values by passing values

Following code can be used to change the enum return value as required by passing parameters.

import java.text.MessageFormat;

public enum Errors {
     USERNAME_NOT_FOUND("User not found"),
     USERNAME_EXISTS("Username {0} already exists."),
     USERNAME_CONTAINS_INVALID_CHARS("Username {0} contains invalid characters {1}.");

     private final String message;

     Errors(String message) {
          this.message = message;
     }

     @Override
     public String toString() {
          return message;
     }

     public String getMessage(Object... args) {
          return MessageFormat.format(message, args);
     }
      
     public static void main(String args[]) {

System.out.println(Errors.USERNAME_NOT_FOUND);          System.out.println(Errors.USERNAME_EXISTS.getMessage("username"));  System.out.println(Errors.USERNAME_CONTAINS_INVALID_CHARS.getMessage("us%ername", "%"));

     }
}


Wednesday, November 2, 2016

Run different main classes from one project in JAVA

You can use following command to run different classes from one project jar file. Suppose Runner1 and Runner2 are main classes. You want to run both in separately, then you can use the following commands.

java -cp App.jar foo.Runner1
java -cp App.jar foo.Runner2

Tuesday, June 7, 2016

Trust certificates in JAVA

Following trust manager can be used to ignore validation certificate chains.

TrustManager[] trustAllCerts = new TrustManager[] {
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
            }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {

}

Wednesday, May 27, 2015

Set default JAVA path

Sometimes you need to use several JAVA versions in a single machine. But you can't change default running JAVA version. Changing PATH variable doesn't affect for this. You can remove system32 JAVA exe file and reset JAVA path for new version to run newly installed JAVA version.

exe running directory :- C:\Windows\System32
application exe name :- java.exe

Now, try version in command prompt using java -version command. This will show new JAVA version.

Wednesday, May 13, 2015

SFTP client with private key authentication

SFTP ( FTP over SSH ) is a secure way for file transferring. In JAVA application, you can use the following code to build a SFTP client with private key authentication. Here instead of password pass phase is used.

For this code, JSch JAVA library is used. Following jar files also used for code building.

  • jsch-0.1.51.jar
  • commons-vfs2-2.0.jar
  • commons-logging-1.2.jar

         JSch jSch = new JSch();
        final byte[] privatekey = readMyPrivateKeyFromFile(); // Private key must be byte array
        final byte[] passPhrase = "pass phase".getBytes();

        jSch.addIdentity(
            "myusername",    // String userName
            privatekey,          // byte[] privateKey 
            null,            // byte[] publicKey
            passPhrase  // byte[] passPhrase
        );
        Session session = jSch.getSession("myusername", "hostname", 22);
        UserInfo ui = new UserInfoImpl(); // UserInfoImpl implements UserInfo
        session.setUserInfo(ui);
        session.connect();
        Channel channel = session.openChannel("sftp");
        ChannelSftp sftp = (ChannelSftp) channel;
        sftp.connect();

// Now you can execute any SFTP command for the sftp channel.
        final Vector files = sftp.ls(".");
        for (Object obj : files) {
            System.out.println(obj.toString());
        }
        sftp.disconnect();
        session.disconnect();

Monday, January 12, 2015

Check sever status using Socket in JAVA

In some cases, you have to check server status whether server is running or not using telnet command before executing commands on the server application. This code can be used to check whether there is a running something on the given IP and Port.

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.*;

public class Telnet {

    public static void main(String args[]) {
        try {
            String ip =  "192.168.*.*";           
            int port = 23;
            Socket s1 = new Socket(ip, port);
            InputStream is = s1.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            if (dis != null) {
                System.out.println("Connected IP : " + ip + ", Port : " + port);
            } else {
                System.out.println("Connection Invalid.");
            }

            dis.close();
            s1.close();

        } catch (Exception e) {
            System.out.println("Not Connected, check Ip and Port.");

        }

    }
}

Thursday, December 4, 2014

SSH vfs2 Change FTP Directory

Following configuration can be used to change logged user directory. In normally, FTP directory is set to logging user home. Sometimes, you have to access directories outside of the logging SFTP user home.

SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

This code snip can be used, when you are using vfs2 SFTP client.

Now, you can FTP files in any location using following SFTP URI.

"sftp://" + userID + ":" + password + "@" + sftpHost + "/" + remoteDirectory + fileName

Change remote directory as you preferred.

Tuesday, October 28, 2014

SFTP in JAVA

Following JAVA functions can be used to execute SFTP(Secure FTP).

    public boolean putSFTPFile(String sftpHost, String userID, String password, String remoteDirectory, String localDirectory, String fileName) throws FileSystemException {

        boolean put = false;
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {

            String filepath = localDirectory + fileName;
            File file = new File(filepath);
            if (!file.exists()) {
                throw new RuntimeException("Error. Local file not found.");
            }
            manager.init();

            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/" + remoteDirectory + fileName;

            FileObject localFile = manager.resolveFile(file.getAbsolutePath());
            System.out.println(file.getAbsolutePath());

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
            put = true;

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            manager.close();
        }
        return put;
    }

    public boolean getSFTPFile(String sftpHost, String userID, String password, String remoteDirectory, String localDirectory, String fileName) {

        boolean get = false;
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {

            manager.init();

            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/"
                    + remoteDirectory + fileName;

            String filepath = localDirectory + fileName;
            File file = new File(filepath);
            FileObject localFile = manager.resolveFile(file.getAbsolutePath());

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
            get = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            manager.close();
        }
        return get;
    }

    public boolean deleteSFTFile(String sftpHost, String userID, String password, String remoteDirectory, String fileName) {

        boolean delete = false;
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {

            manager.init();

            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/"
                    + remoteDirectory + fileName;

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            if (remoteFile.exists()) {
                if (remoteFile.delete()) {
                    delete = true;
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            manager.close();
        }
        return delete;
    }

    public Collection getSFTPFileList(String sftpHost, String userID, String password, String remoteDirectory) throws FileSystemException {

        Collection fileCollection = new ArrayList();
        StandardFileSystemManager manager = new StandardFileSystemManager();

        FileObject localFileObject = manager.resolveFile("sftp://" + userID + ":" + password + "@" + sftpHost + "/" + remoteDirectory);
        FileObject[] children = localFileObject.getChildren();

        for (int i = 0; i < children.length; i++) {
            fileCollection.add(children[ i].getName().getBaseName());
        }

        return fileCollection;
    }

    public boolean isRemoteFileExist(String sftpHost, String userID, String password, String remoteDirectory, String fileName) {
        StandardFileSystemManager manager = new StandardFileSystemManager();
        boolean isExist = false;

        try {
            manager.init();

            //Setup our SFTP configuration
            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/"
                    + remoteDirectory + fileName;

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            isExist = remoteFile.exists();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            manager.close();
        }
        return isExist;
    }