Tuesday, July 23, 2024

Flutter , Angular and React

 

Flutter

1.       Google created.

2.       Open source Flutter software development framework

3.       create mobile applications for iOS and Android from a single Dart codebase.

4.       Flutter utilizes Dart, object-oriented programming language optimized specifically for developing mobile apps and web apps

a.       Dart code is compiled ahead of time into native machine code using the Flutter compiler, enabling apps to achieve exceptionally high performance.

5.       A standout feature of Flutter is its incredibly fast hot reload functionality, which allows developers to experiment rapidly and visualize changes in UI almost instantly without losing the application state.

6.       create mobile app interfaces reflecting Google's modern design principles using Material Design and Cupertino widgets.

7.       Flutter has a widget binding, namely InheritedWidget. It binds two or more widgets together (one provider and some consumers) so that whenever one updates, all of its dependencies are forced to update too.

8.       Popular apps built using Flutter include Hamilton Broadway Musical, Google Ads, eBay Motors, Groupon, Reflectly meditation app, etc.

 

Pros

 

  • ·       Single Dart codebase to build iOS and Android apps
  • ·       Stateful hot reload enables instant visual updates without recompilation
  • ·       Excellent performance powered by Dart's compiled machine code
  • ·       Extensive catalog of customizable Material and Cupertino widgets
  • ·       Increased software development speed and iteration facilitated by features such as hot reloading
  • ·       Expressive and easy-to-learn Dart programming language

Cons

  • ·       As a relatively new SDK, it has a smaller ecosystem of libraries and tools than older alternatives.
  • ·       Restricted access to some exclusive platform-specific APIs and features
  • ·       Primarily focused only on mobile app development, it is less suitable for web
  • ·       Very few developers know the Dart programming language, leading to a talent shortage
  • ·       Architectural changes and breaking updates are likely as the framework matures 

Angular

1.       by Google

2.       web application development framework

3.       Angular apps are written in TypeScript, an enhanced version of JavaScript that brings optional typing and other improvements aimed at large-scale apps. 

4.       The framework uses an MVC architecture style to separate an app's concerns into distinct Models, Views, and Controller components.

5.       two-way data binding, which automatically syncs data between model and view

6.       dependency injection to manage relationships between various app modules.

7.       Popular Angular sites include PayPal, NBC, UPS, Lego, and Forbes.

 

Pros

  • ·       The full-featured framework integrates a wide range of web functions
  • ·       MVC architecture enables the separation of concerns
  • ·       Powerful data binding(two-way) synchronizes model and view components
  • ·       Extensive toolbox including testing suites, lint test
  • ·       High focus on reusability and maintainability
  • ·       Simplifies form building and form validation
  • ·       The large community provides many reusable libraries
  • Cons
  • ·       Steep learning curve due to the vast API surface area
  • ·       More complex compared to lighter-weight libraries like React
  • ·       Bulkier apps due to a large framework codebase
  • ·       Longer bootstrap and rendering times result from complexity
  • ·       Demands strong TypeScript knowledge
  • ·       Upgrades between versions may require significant rework

React

1.       by Facebook 

2.       open-source JavaScript front-end library 

3.       use to build interactive user interfaces and web application front-ends

4.       React aims to simplify the development of complex, changing data flows in web UIs

5.       React builds on basic HTML/CSS/JS to provide a declarative component model. 

a.       UIs are broken into encapsulated, reusable pieces called components. 

6.       Components use a templating language called JSX that resembles HTML to render content, can have a local state, and update dynamically in response to data changes.

7.       Events triggered from one component bubble up to notify parent components automatically through a unidirectional data flow paradigm. ( first the model state is updated, and then it renders the change in the UI element. )

8.       Virtual DOM tracking of changes combined with selectively re-rendering only components that change enables very high performance compared to raw JavaScript ops.

a.       This helps power data-intensive apps like Facebook and Instagram that show constantly updating content flows.

9.       Popular Apps

Facebook, Airbnb, Uber, Netflix, Instagram, WhatsApp, Dropbox etc.

 

 

Pros

  • ·       Promotes reusability via encapsulated components
  • ·       Components offer separation of concerns
  • ·       Virtual DOM provides excellent performance gains
  • ·       Unidirectional data flow simplifies data handling logic
  • ·       The large open-source ecosystem of reusable React component libraries
  • ·       Easy integration into existing codebases
  • ·       The growing developer community provides abundant support resources

Cons

  • ·       Only handles the view layer, not a complete framework
  • ·       Many auxiliary libraries are needed for complex apps (routing, state management)
  • ·       Code complexity from JSX and nested component trees
  • ·       Steep learning curve mastering inner workings like state and lifecycle
  • ·       Rapid evolution means breaking API changes, which is not uncommon
  • ·       Less out-of-box project scaffolding sets up


Tech Stack

Flutter uses the Dart programming language and provides its robust widget set for building mobile interfaces. This allows it to compile code into native machine code for excellent performance.

Angular utilizes TypeScript, a typed superset of JavaScript and HTML and CSS, for building responsive web applications. It compiles down to plain JavaScript code to run in browsers.

React Native is based on the React JavaScript library and uses the same paradigm of components. It compiles code to native UI components while communicating with native code through a JavaScript bridge.

 

Learning Curve

Flutter offers a moderately easy learning curve for developers with prior experience in object-oriented code and mobile development. Its declarative widget-based approach is intuitive.

Given the complexity of its technology stack, Angular has a rather steep learning curve, including TypeScript, components, directives, services, dependency injection, and hierarchical injectors.

React Native is moderately easy to get started with for JavaScript developers who understand React concepts like components, states, and props. However, bridging to native code can have a learning curve

 

Flutter vs Angular vs React: The Ultimate Showdown [2024] (simplilearn.com)

https://www.javatpoint.com/angular-vs-react

https://stackoverflow.com/questions/52590759/does-flutter-have-data-binding

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;
}

}