Wednesday, January 10, 2024

How to install Linux on Windows with WSL - Windows Subsystem for Linux

 WSL on Windows

--------------

Windows Subsystem for Linux currently has several limitations. First, it does not support all Linux applications; it is intended to provide a tool to handle bash and major Linux command-line utilities. WSL does not support Linux graphical user interface (GUI) environments such as Gnome or K Desktop Environment.

How to install Linux on Windows with WSL

https://learn.microsoft.com/en-us/windows/wsl/install


Run Below command in Power Shell ( better to run with Administrator mode )

1. wsl --install

 Note

The above command only works if WSL is not installed at all. If you run wsl --install and see the WSL help text, please try running wsl --list --online to see a list of available distros and run wsl --install -d <DistroName> to install a distro. To uninstall WSL, see Uninstall legacy version of WSL or unregister or uninstall a Linux distribution.

2. Check which version of WSL you are running

wsl -l -v


3. Check version

wsl --version

4. wsl --status

may give sample output like

-------------------------------------------------------------------------------------------------------

Default Distribution: Ubuntu

Default Version: 2

Windows Subsystem for Linux was last updated on 7/7/2023

WSL automatic updates are on.

Kernel version: 5.10.16

------------------------------------------------------------------------------------------------------------

5. help

wsl --help

6. To run as specific user

wsl --user {username}

wsl --user myname

7. Update 


8.To shutdown

wsl --shutdown



https://learn.microsoft.com/en-us/windows/wsl/basic-commands


Sample Word to PDF convert with docx4j

Below is sample application to convert Word file to Pdf using dox4j

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.poc.convert</groupId>
<artifactId>convert</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>convert</name>
<description>Poc Project to convert word to pdf</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- dox4j -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.3.9</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>8.3.9</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-MOXy</artifactId>
<version>8.3.9</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.3.9</version>
</dependency>

<!--- ****** -->
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>

<!-- java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException -->
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>

<!-- java.lang.NoClassDefFoundError: javax/activation/DataSource -->
<!-- Caused by: java.lang.ClassNotFoundException: javax.activation.DataSource-->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>

<!-- java.lang.NoClassDefFoundError: javax/mail/internet/MimeMultipart-->
<!-- Caused by: java.lang.ClassNotFoundException: javax.mail.internet.MimeMultipart-->

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>

<!-- Documents4jLocalServices-->
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-documents4j-local -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-documents4j-local</artifactId>
<version>11.4.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.5</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
</dependency>



<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


Above POM all dependencies 

Below Convert Class contains the Logic

--------------------------------------------------------------------------------------------------------


package com.poc.convert.convert;


import com.documents4j.api.DocumentType;

import org.docx4j.Docx4J;

import org.docx4j.documents4j.local.Documents4jLocalServices;

import org.docx4j.openpackaging.exceptions.Docx4JException;

import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


import java.io.*;


public class Convert {

    private static final Logger LOGGER = LoggerFactory.getLogger(Convert.class);


    public static Documents4jLocalServices exporter = new Documents4jLocalServices();


    private static volatile Convert instance;


    private Convert() {

    }


    public static Convert getInstance() {

        if (instance == null) {

            synchronized (Convert.class) {

                if (instance == null) {

                    instance = new Convert();

                }

            }

        }

        return instance;

    }


    /**

     * Convert word .docx format file to pdf file.

     *

     * @param inputWordFile Input word .docx file.

     * @param outputPdfFile Converted .pdf file.

     * @throws IOException     Exception when reading input word ,docx file or writing to .pdf output file

     * @throws Docx4JException Excpetion occcuring during converting word file to Pdf file.

     */

    public void convertWordDocxtoPdf(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {

        LOGGER.info("Start Converting Word {} file to {}", inputWordFile, outputPdfFile);

        InputStream templateInputStream = new FileInputStream(inputWordFile);

        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();


        FileOutputStream os = new FileOutputStream(outputPdfFile);

        Docx4J.toPDF(wordMLPackage, os);

        os.flush();

        os.close();

        LOGGER.info("Successfully converted {} to {}", inputWordFile, outputPdfFile);

    }


    public void convertWordDocxtoPdfWithLocalServer(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {

        LOGGER.info("Start Converting with local server Word {} file to {}", inputWordFile, outputPdfFile);

        try (FileOutputStream fos = new FileOutputStream(outputPdfFile)) {

            if (inputWordFile.toLowerCase().endsWith(".docx")) {

                exporter.export(new File(inputWordFile), fos, DocumentType.MS_WORD);

            }

            LOGGER.info("Start Flushing ***********");

            fos.flush();

            fos.close();

            LOGGER.info("End Flushing ***********");

//            System.exit(0);

        }

        LOGGER.info("Successfully converted with local server {} to {}", inputWordFile, outputPdfFile);

    }


    public void convertWordDocxtoPdfWithLibre(String inputWordFile, String outputPdfFile) throws IOException {

        LOGGER.info("Start Converting Word with Libre {} file to {}", inputWordFile, outputPdfFile);


        String command = "libreoffice --headless --convert-to pdf " + inputWordFile + " --outdir " + outputPdfFile;

        Runtime.getRuntime().exec(command);


        LOGGER.info("Successfully converted with Libre {} to {}", inputWordFile, outputPdfFile);

    }

}

----------------------------------------------------------------------------------------------------------------


package com.poc.convert.convert;

import com.documents4j.api.DocumentType;
import org.docx4j.Docx4J;
import org.docx4j.documents4j.local.Documents4jLocalServices;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class Convert {
private static final Logger LOGGER = LoggerFactory.getLogger(Convert.class);

public static Documents4jLocalServices exporter = new Documents4jLocalServices();

private static volatile Convert instance;

private Convert() {
}

public static Convert getInstance() {
if (instance == null) {
synchronized (Convert.class) {
if (instance == null) {
instance = new Convert();
}
}
}
return instance;
}

/**
* Convert word .docx format file to pdf file.
*
* @param inputWordFile Input word .docx file.
* @param outputPdfFile Converted .pdf file.
* @throws IOException Exception when reading input word ,docx file or writing to .pdf output file
* @throws Docx4JException Excpetion occcuring during converting word file to Pdf file.
*/
public void convertWordDocxtoPdf(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {
LOGGER.info("Start Converting Word {} file to {}", inputWordFile, outputPdfFile);
InputStream templateInputStream = new FileInputStream(inputWordFile);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

FileOutputStream os = new FileOutputStream(outputPdfFile);
Docx4J.toPDF(wordMLPackage, os);
os.flush();
os.close();
LOGGER.info("Successfully converted {} to {}", inputWordFile, outputPdfFile);
}

public void convertWordDocxtoPdfWithLocalServer(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {
LOGGER.info("Start Converting with local server Word {} file to {}", inputWordFile, outputPdfFile);
try (FileOutputStream fos = new FileOutputStream(outputPdfFile)) {
if (inputWordFile.toLowerCase().endsWith(".docx")) {
exporter.export(new File(inputWordFile), fos, DocumentType.MS_WORD);
}
LOGGER.info("Start Flushing ***********");
fos.flush();
fos.close();
LOGGER.info("End Flushing ***********");
// System.exit(0);
}
LOGGER.info("Successfully converted with local server {} to {}", inputWordFile, outputPdfFile);
}

public void convertWordDocxtoPdfWithLibre(String inputWordFile, String outputPdfFile) throws IOException {
LOGGER.info("Start Converting Word with Libre {} file to {}", inputWordFile, outputPdfFile);

String command = "libreoffice --headless --convert-to pdf " + inputWordFile + " --outdir " + outputPdfFile;
Runtime.getRuntime().exec(command);

LOGGER.info("Successfully converted with Libre {} to {}", inputWordFile, outputPdfFile);
}
}


3. This is the default Springboot main classs
This class simply call the logic of the Convert class where takes InputFilePath and OutputFilePath as arguments

package com.poc.convert.convert;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;

@SpringBootApplication
public class ConvertApplication {

private static final Logger LOGGER = LoggerFactory.getLogger(ConvertApplication.class);

public static void main(String[] args) {
SpringApplication.run(ConvertApplication.class, args);

String inputWordFile = "";
String outputPdfFile = "";

if (args[0].length() > 0) {
inputWordFile = args[0];
} else {
LOGGER.info("Please define Input file");
}

if (args[1].length() > 0) {
outputPdfFile = args[1];
} else {
LOGGER.info("Please define Output file");
}


try {
Convert.getInstance().convertWordDocxtoPdf(inputWordFile, outputPdfFile);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Docx4JException e) {
throw new RuntimeException(e);
}

}

}


With this you can execute Jar file with below command.
{space} --> empty space character, separate parts of the commands

1. command to execute jar
java {space} -jar {space} {name of the jar file} {space} {input file path} {output file path}

java -jar convert-0.0.1-SNAPSHOT.jar D:/sample.docx D:/sample.pdf






Wednesday, January 3, 2024

Sample Web Browser configuration for selenium automation

package com.example.test.runner;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;

public class ChromeBrowserExecution {
public WebDriver getDriver() throws IOException {

System.setProperty("webdriver.chrome.driver", "C:\\Intel\\chrome\\chrome-win64\\chrome.exe");
//System.setProperty("webdriver.chrome.whitelistedIps", "*");

ChromeOptions ops = new ChromeOptions();
ops.addArguments("--remote-allow-origins=*");
//ops.addArguments("--headless");

// ----- Creating an object of ChromeDriver
WebDriver driver = new ChromeDriver(ops);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();

return driver;
}

}

package com.example.test.runner;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.IOException;

public class EdgeBrowserExecution {
public WebDriver getDriver() throws IOException {
System.setProperty("webdriver.edge.driver","C:\\Intel\\webDriver\\Edge\\msedgedriver.exe");

// ----- Creating an object of EdgeDriver
WebDriver driver = new EdgeDriver
(new EdgeOptions().addArguments("--remote-allow-origins=*"));
driver.manage().deleteAllCookies();
driver.manage().window().maximize();

return driver;
}

}

package com.example.test.runner;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.io.IOException;

public class FirefoxBrowserExecution {
public WebDriver getDriver() throws IOException {
// Setting system properties of ChromeDriver
System.setProperty("webdriver.gecko.driver", "C:\\Intel\\Firefox Geckodriver 0.31.0\\geckodriver.exe");
// System.setProperty("webdriver.chrome.whitelistedIps", "*");
// C:\Intel\chromedriver_win32

// ChromeOptions ops = new ChromeOptions();
// ops.addArguments("--remote-allow-origins=*");
// ops.addArguments("--headless");

// ----- Creating an object of ChromeDriver
WebDriver driver3 = new FirefoxDriver();
driver3.manage().deleteAllCookies();
driver3.manage().window().maximize();
return driver3;
}
}

Samplelog back xml

<configuration>

<property name="LOGS" value="./logs" />

<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C): %msg%n%throwable
</Pattern>
</layout>
</appender>

<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/test-automation-poc-logger.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d %p %C [%t] %m%n</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily and when the file reaches 10 MegaBytes -->
<fileNamePattern>${LOGS}/archived/test-runner-logger-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>

<!-- LOG everything at INFO level -->
<root level="info">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</root>

<logger name="com.example.test.runner" level="trace" additivity="false">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</logger>

<logger name="com.example.test.framework" level="trace" additivity="false">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</logger>


</configuration>

Sample Custom Exception class

package com.example.test.framework.exception;

/**
* Handle exception when element is not available.
*/
public class ElementNotFoundException extends RuntimeException {
/**
* Instantiates a new {@link ElementNotFoundException}.
*
* @param message the exception message,
*/
public ElementNotFoundException(String message) {
super(message);
}
}

Sample Enum

package com.example.test.framework.enums;

/**
* Message matching type
*/
public enum MessageMatchType {
/** The exact message will be checked. */
EXACT(0),

/** The partial of the original message text is matched. */
PARTIAL(1);

/** The key. */
private int key;

private MessageMatchType(int key) {
this.key = key;

}

public int getKey() {
return key;
}

}

Thursday, November 23, 2023

Java 9 : JShell

 1. How to run Jshell

    get a command prompt windows key + R --> type cmd

2. Check java version, should be higher than 9

    java -version

3. type "jshell"

4. Now you can write syntax and check validity , edit and play on with this

5. /help --> help command

6. /list   --> will list the command typed/executed

7. edit use edit command with command number, number you can select using /list . Once you use edit, it will prompt with shell to edit.

    /edit 2


Below you I have attached series of commands i tried with all mistakes

----------------------------------------------------------------------------------------------------------------------

Microsoft Windows [Version 10.0.22621.2715]

(c) Microsoft Corporation. All rights reserved.


C:\Users\USR>java -version

openjdk version "21" 2023-09-19

OpenJDK Runtime Environment Zulu21.28+85-CA (build 21+35)

OpenJDK 64-Bit Server VM Zulu21.28+85-CA (build 21+35, mixed mode, sharing)


C:\Users\USR>jshell

|  Welcome to JShell -- Version 21

|  For an introduction type: /help intro


jshell> System.out.println("Hello");

Hello


jshell> /help

|  Type a Java language expression, statement, or declaration.

|  Or type one of the following commands:

|  /list [<name or id>|-all|-start]

|       list the source you have typed

|  /edit <name or id>

|       edit a source entry

|  /drop <name or id>

|       delete a source entry

|  /save [-all|-history|-start] <file>

|       Save snippet source to a file

|  /open <file>

|       open a file as source input

|  /vars [<name or id>|-all|-start]

|       list the declared variables and their values

|  /methods [<name or id>|-all|-start]

|       list the declared methods and their signatures

|  /types [<name or id>|-all|-start]

|       list the type declarations

|  /imports

|       list the imported items

|  /exit [<integer-expression-snippet>]

|       exit the jshell tool

|  /env [-class-path <path>] [-module-path <path>] [-add-modules <modules>] ...

|       view or change the evaluation context

|  /reset [-class-path <path>] [-module-path <path>] [-add-modules <modules>]...

|       reset the jshell tool

|  /reload [-restore] [-quiet] [-class-path <path>] [-module-path <path>]...

|       reset and replay relevant history -- current or previous (-restore)

|  /history [-all]

|       history of what you have typed

|  /help [<command>|<subject>]

|       get information about using the jshell tool

|  /set editor|start|feedback|mode|prompt|truncation|format ...

|       set configuration information

|  /? [<command>|<subject>]

|       get information about using the jshell tool

|  /!

|       rerun last snippet -- see /help rerun

|  /<id>

|       rerun snippets by ID or ID range -- see /help rerun

|  /-<n>

|       rerun n-th previous snippet -- see /help rerun

|

|  For more information type '/help' followed by the name of a

|  command or a subject.

|  For example '/help /list' or '/help intro'.

|

|  Subjects:

|

|  intro

|       an introduction to the jshell tool

|  keys

|       a description of readline-like input editing

|  id

|       a description of snippet IDs and how use them

|  shortcuts

|       a description of keystrokes for snippet and command completion,

|       information access, and automatic code generation

|  context

|       a description of the evaluation context options for /env /reload and /reset

|  rerun

|       a description of ways to re-evaluate previously entered snippets


jshell>

/list


   1 : System.out.println("Hello");


jshell> void printMessage(){

   ...>     System.out.print;n("Hello")

   ...> }

|  Error:

|  not a statement

|      System.out.print;n("Hello")

|      ^--------------^

|  Error:

|  ';' expected

|      System.out.print;n("Hello")

|                                 ^


jshell> printMessage()

|  Error:

|  cannot find symbol

|    symbol:   method printMessage()

|  printMessage()

|  ^----------^


jshell> /lsit

|  Invalid command: /lsit

|  Type /help for help.


jshell> /list


   1 : System.out.println("Hello");


jshell>

        void printMessage(){

   ...>     System.out.print;n("Hello");

   ...> }

|  Error:

|  not a statement

|      System.out.print;n("Hello");

|      ^--------------^

|  Error:

|  cannot find symbol

|    symbol:   method n(java.lang.String)

|      System.out.print;n("Hello");

|                       ^


jshell> void printMessage(){

   ...>     System.out.println("Hello");

   ...> }

|  created method printMessage()


jshell> printMessage

|  Error:

|  cannot find symbol

|    symbol:   variable printMessage

|  printMessage

|  ^----------^


jshell> printMessage()

Hello


jshell> /list


   1 : System.out.println("Hello");

   2 : void printMessage(){

           System.out.println("Hello");

       }

   3 : printMessage()


jshell> edit 2

|  Error:

|  ';' expected

|  edit 2

|      ^

|  Error:

|  cannot find symbol

|    symbol:   variable edit

|  edit 2

|  ^--^


jshell> /edit 2

|  modified method printMessage()


jshell> printMessage()

Hello Edited


jshell>