Posts

Showing posts from 2018

serenity cucumber selenium automation

BDD fundamentals Behaviour-Driven Development (BDD) is a collaborative approach to software development that bridges the communication gap between business and IT. BDD helps teams communicate requirements with more precision, discover defects early and produce software that remains maintainable over time. Writing acceptance criteria with Cucumber-JVM In Cucumber, you express acceptance criteria in a natural, human-readable form. For example, you want to write acceptance criteria for sending a mail you could write like this: Given I want to send a mail When I login to to mail box. clicked compose button, entered the details and clicked send Then I should see mail sent to the receiver. Sometimes tables can be used to summarize several different examples of the same scenario. Scenario Outline: sending a mail Given I have login to the mail box When I can enter the details '<Email>' and '<Subject>' Then I should see mail sent succes...

cucumber selenium automation for ag-Grid example

How to select row in xpath?

What is addShutdownHook method in java?

addShutdownHook method registers a new virtual-machine shutdown hook. A shutdown hook is a initialized but unstarted thread.  When JVM starts its shutdown it will start all registered shutdown hooks in some unspecified order and let them run concurrently.  When JVM (Java virtual machine)  shuts down > When the last non-daemon thread finishes, or when the System.exit is called. Once JVM’s shutdown has begun new shutdown hook cannot be registered neither  previously-registered hook can be de-registered. Any attempt made to do any of these operations causes an IllegalStateException. Example: public class AddShutDownHookTest extends Thread{    public static void main(String[] args) throws InterruptedException {              System. out .println( "main thread started" );                 ...

What is preemptive scheduling and time slicing in java

In preemptive scheduling, the highest priority thread executes until it enters into the waiting or dead state. In time slicing, a thread executes for a certain predefined time and then enters runnable pool. Than thread can enter running state when selected by thread scheduler.

When to use ArrayList and when to use LinkedList in application?

ArrayList has constant time search operation O(1) .Hence, ArrayList is preferred when there are more get() or search operation . Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.

Lombok "val" example

" val " can use as the type of a local variable declaration instead of actually writing the type. Java With out Lombok public class ValExample {   public void example() {     ArrayList<String> example = new ArrayList<String>();     example.add("Hello, World!");     String foo = example.get(0);   } } Java With Lombok import java.util.ArrayList; import java.util.HashMap; import lombok.val; public class ValExample {   public void example() {     val example = new ArrayList<String>();     example.add("Hello, World!");     val foo = example.get(0);   } }

Lombok @Builder example

The @Builder annotation produces complex builder APIs for your classes. Java With Out Lombok public class BuilderExample {   private String name;   private int age;     BuilderExample(String name, int age) {     this.name = name;     this.age = age;     this.occupations = occupations;   }   //setter and getter } With Lombok import lombok.Builder; import lombok.Singular; @Builder public class BuilderExample {   private String name;   private int age; } Lombok with java 8 example BuilderExample.builder().name("Test").age(20).build();

Project Lombok Example

Lombok features The  Lombok javadoc  is available, but we advise these pages. val Finally! Hassle-free final local variables. var Mutably! Hassle-free local variables. @NonNull or: How I learned to stop worrying and love the NullPointerException. @Cleanup Automatic resource management: Call your  close()  methods safely with no hassle. @Getter/@Setter

Project lombok Installation in IDE

IntelliJ IDEA The  Jetbrains IntelliJ IDEA  editor is compatible with lombok. Add the  Lombok IntelliJ plugin  to add lombok support for IntelliJ: Go to  File > Settings > Plugins Click on  Browse repositories... Search for  Lombok Plugin Click on  Install plugin Restart IntelliJ IDEA Eclipse Download from https://projectlombok.org/download

Project Lombok dependencies

Lombok Gradle dependencies lombok { version = '1.18.4' sha256 = "" } Maven Dependencies <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency> </dependencies>

Java Sound API Example

The Sound API is a low-level API for creating, modifying, and controlling the input and output of sound media, including both audio and MIDI (Musical Instrument Digital Interface) data. The JavaSound API provides explicit control over the capabilities normally required for sound input and output, in a framework that promotes extensibility and flexibility. The public JavaSound API consists of two main packages: javax.sound.sampled (interfaces and classes for sampled audio) javax.sound.midi (interfaces and classes for MIDI). javax.sound.sampled.spi javax.sound.midi.spi More info

Java 12 features

JDK 12 This release will be the Reference Implementation of version 12 of the Java SE Platform, as specified by  JSR 386  in the Java Community Process. Status The  development repositories  are open for bug fixes, small enhancements, and JEPs as proposed and tracked via the  JEP Process . Schedule 2018/12/13 Rampdown Phase One  (fork from main line) 2019/01/17 Rampdown Phase Two 2019/02/07 Release-Candidate Phase 2019/03/19 General Availability Features JEPs targeted to JDK 12, so far 325:  Switch Expressions (Preview) 326:  Raw String Literals (Preview) 340:  One AArch64 Port, Not Two 341:  Default CDS Archives

Java 11 features

JDK 11 is the open-source reference implementation of version 11 of the Java SE 11 Platform as specified by by  JSR 384  in the Java Community Process. JDK 11 reached  General Availability  on 25 September 2018. Production-ready binaries under the GPL are  available from Oracle ; binaries from other vendors  will follow shortly . The features and schedule of this release were proposed and tracked via the  JEP Process , as amended by the  JEP 2.0 proposal . The release was produced using the  JDK Release Process (JEP 3) . Features 181:  Nest-Based Access Control 309:  Dynamic Class-File Constants 315:  Improve Aarch64 Intrinsics 318:  Epsilon: A No-Op Garbage Collector 320:  Remove the Java EE and CORBA Modules 321:  HTTP Client (Standard) 323:  Local-Variable Syntax for Lambda Parameters 324:  Key Agreement with Curve25519 and Curve448 327:  Unicode 10 32...

PUBG mobile not responding after match end.

Java String strip() method Example

String strip() method String strip() method added in jdk 11. String strip()  Returns a string whose value is this string, with all leading and trailing white space removed. If this String object represents an empty string, or if all code points in this string are white space, then an empty string is returned. Otherwise, returns a substring of this string beginning with the first code point that is not a white space up to and including the last code point that is not a white space. This method may be used to strip white space from the beginning and end of a string. strip method remove the extra space from both side. Java Program Example: class StripMethodExample{ public static void main(String args[]){ //with var variable var test = "     hello!   "; System.out.println(test.strip()); //with String class String test1 = "      hello!   "; System.out.println(test1.strip()); } } Output: hello! hello! ...

Java 11 : repeat method example

repeat method accept a integer parameter and repeat variable that many time. var test = " hello "; System.out.println(test.repear(3)); Output: hello   hello   hello

Java 10 : Garbage Collector

The GC interface would be defined by the existing class  CollectedHeap  which every garbage collector needs to implement. The  CollectedHeap  class would drive most aspects of interaction between the garbage collector and the rest of HotSpot (there a few utility classes needed prior to a  CollectedHeap  being instantiated). More specifically, a garbage collector implementation will have to provide: The heap, a subclass of  CollectedHeap The barrier set, a subclass of  BarrierSet , which implements the various barriers for the runtime An implementation of  CollectorPolicy An implementation of  GCInterpreterSupport , which implements the various barriers for a GC for the interpreter (using assembler instructions) An implementation of  GCC1Support , which implements the various barriers for a GC for the C1 compiler An implementation of  GCC2Support , which implements the various barriers for a GC for the C2 compiler Init...

Java 10 : 'var' variable example

'var' keyword - "var" variable introduced in Java 10 to declared any type of datatype. Example: var message= "hello"; var size = 10; var array = new String[]{"1","2","3"}; for(var i=0;i<10;i++){ } var in collection: var map = getMap(); public Map<String,String> getMap(){ Map<String,String> m=new HashMap<>(); m.put("1","1"); return m; }

Java 9 : JShell example

Image
In your command prompt, type jshell and press enter. You will see a message and then a jshell> prompt: Use  Ctrl + A  to reach the beginning of the line and  Ctrl + E  to reach the end of the line. 1) /help intro or /help help you in interacting with JShell 2) /imports java.lang.Object This imports the Object class 3) Let's declare an Employee class. class Employee{ private String empId; public String getEmpId() { return empId; } public void setEmpId ( String empId ) { this.empId = empId; } } 4) /open  loading the code from within a file. /open Test.java It will load the Test class definition and create an Test object.

Java 9 : Unified logging for JVM

Image
Java 9 implemented JEP 158: Unified JVM Logging, which requested to introduce a common logging system for all the components of the JVM. The main components of JVM include the following: Class loader Runtime data area        Stack area        Method area        Heap area        PC registers        Native method stack Execution engine           Interpreter           The JIT compiler           Garbage collection           Native method interface JNI           Native method library

Java 9 : HTTP POST request example

1. Create an instance of HttpClient using its HttpClient.Builder builder: HttpClient client = HttpClient.newBuilder().build(); 2. Create the required data to be passed into the request body: Map<String, String> requestBody = Map.of("key1", "value1", "key2", "value2"); 3. Create a HttpRequest object with the request method as POST and by providing the request body data as String. We make use of Jackson's ObjectMapper to convert the request body, Map<String, String>, into a plain JSON String and then make use of HttpRequest.BodyProcessor to process the String request body: ObjectMapper mapper = new ObjectMapper(); HttpRequest request = HttpRequest .newBuilder(new URI("http://httpbin.org/post")).POST( HttpRequest.BodyProcessor.fromString( mapper.writeValueAsString(requestBody))) .version(HttpClient.Version.HTTP_1_1).build(); 4. The request is sent and the response is obtained by using the send(HttpRequ...

Java 9 : HTTP GET request example

Using the JDK 9 HTTP Client API to make a GET request to the URL Package jdk.incubator.http.HttpClient jdk.incubator.http.HttpRequest java.net.URI HttpClient client = HttpClient.newBuilder().build(); HttpRequest request = HttpRequest.newBuilder(new URI("http://java.com")).GET().version(HttpClient.Version.HTTP_1_1).build(); HttpResponse<String> response = client.send(request,HttpResponse.BodyHandler.asString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); Print the status code and the response body.

Producing and consuming JSON or XML in Java REST Services with Jersey

Maven dependencies <dependencies>   <dependency>  <groupId>com.sun.jersey</groupId>  <artifactId>jersey-bundle</artifactId>  <version>1.19.3</version>  </dependency>  <dependency>     <groupId>com.sun.jersey</groupId>     <artifactId>jersey-json</artifactId>     <version>1.17.1</version> </dependency>  <dependency>  <groupId>org.codehaus.jackson</groupId>  <artifactId>jackson-mapper-asl</artifactId>  <version>1.9.10</version>  </dependency>  <dependency>  <groupId>org.codehaus.jackson</groupId>  <artifactId>jackson-core-asl</artifactId>  <version>1.9.10</version>  </dependency>  <dependency>  <groupId>org.codehaus.jackson</groupId>...

Java - Stream Operations and Pipelines

java.util.stream  This package allows you to have a declarative presentation of the procedures that can be subsequently applied to the data, also in parallel; these procedures are presented as streams, which are objects of the Stream interface. For better transition from the traditional collections to streams, two default methods (stream() and parallelStream()) were added to the java.util.Collection interface along with the addition of new factory methods of stream generation to the Stream interface. This approach takes advantage of the power of composition, discussed in one of the previous chapters. Together with other design principles--encapsulation, interface, and polymorphism--it facilitates a highly extensible and flexible design, while lambda expressions allow you to implement it in a concise and succinct manner. Today, when the machine learning requirements of massive data processing and the fine-tuning of operations have become ubiquitous, these new features...

Java 9 : functional programming

Functional programming--the ability to treat a certain piece of functionality as an object and to pass it as a parameter or the return value of a method--is a feature present in many programming languages. It avoids the changing of an object state and mutable data. The result of a function depends only on the input data, no matter how many times it is called. This style makes the outcome more predictable, which is the most attractive aspect of functional programming. Its introduction to Java also allows you to improve parallel programming capabilities in Java 8 by shifting the responsibility of parallelism from the client code to the library. Before this, in order to process elements of Java collections, the client code had to acquire an iterator from the collection and organize the processing of the collection.

java 9 : Modular Programming

Modular programming enables one to organize code into independent, cohesive modules, which can be combined together to achieve the desired functionality. This allows in creating code that is: More cohesive because the modules are built with a specific purpose, so the code that resides there tends to cater to that specific purpose. Encapsulated because modules can interact with only those APIs that have been made available by the other modules. Reliable because the discoverability is based on the modules and not on the individual types. This means that if a module is not present, then the dependent module cannot be executed until it is discoverable by the dependent module. This helps in preventing runtime errors. Loosely coupled. If you use service interfaces, then the module interface and the service interface implementation can be loosely coupled. So, the thought process in designing and organizing the code will now involve identifying the modules, code, and configur...

Java 9 : HTML5 in Javadocs - HTML5 tags in the Javadoc comments

Image
Generate javadocs to HTML content using java command HTML5 provides better browser compatibility. It is also more mobile-friendly than its predecessor, HTML4. But to take advantage of HTML5, one has to specify the html5 parameter during Javadoc generation. Otherwise, only HTM4-style comments will continue to be supported. Here is an example of the HTML5 tags used for Javadoc comments: /** <h2>Returns the weight of the car.</h2> <article> <h3>If life would be often that easy</h3> <p> Do you include unit of measurement into the method name or not? </p> <p> The new signature demonstrates extensible design of an interface. </p> </article> <aside> <p> A few other examples could be found <a href="http://www.nicksamoylov.com/cat/programming/">here</a>. </p> </aside> * @param weightUnit - an element of the enum Car.WeightUnit * @return the weight of the car in the ...

Java 9 : jmod

JMOD is a new format for packaging your modules. This format allows including native code, configuration files, and other data that do not fit into JAR files. The JDK modules have been packaged as JMOD files. The jmod command-line tool allows create, list, describe, and hash JMOD files: create: This is used to create a new jmod file list: This is used to list the contents of a jmod file describe: This is used to describe module details hash: This is used to record hashes of tied modules

Java 9 : jlink

This tool is used to select modules and create a smaller runtime image with the selected modules. $> jlink --module-path mods/:$JAVA_HOME/jmods/ --add-modules com.packt --output img Looking at the contents of the img folder, we should find that it has the bin, conf, include, and lib directories.

Java 9 : jdeps

This tool analyses your code base specified by the path to the .class file, directory, or  JAR, lists the package-wise dependency of your application, and also lists the JDK module in which the package exists. This helps in identifying the JDK modules that the application depends on and is the first step in migrating to modular applications. We can run the tool on our HelloWorldXml example written earlier and see what jdeps provides: $> jdeps mods/com.packt/ com.packt -> java.base com.packt -> java.xml.bind com.packt -> java.io                                  java.base com.packt -> java.lang                              java.base com.packt -> javax.xml.bind                     java.xml.bind com.packt -> javax.xml.bind.annotation  ...

Java 9 : jdeprscan

This tool is used for scanning the usage of deprecated APIs in a given JAR file, classpath, or source directory. Suppose we have a simple class that makes use of the deprecated method, addItem , of the   java.awt.List  class, as follows: import java.awt.List; public class Test{ public static void main(String[] args){ List list = new List(); list.addItem("Hello"); } } Compile the preceding class and then use jdeprscan , as follows: C:Program FilesJavajdk-9bin>jdeprscan.exe -cp . Test You will notice that this tool prints out class Test uses method java/awt/List addItem (Ljava/lang/String;) deprecated, which is exactly what we expected.

Java 9 : more concurrency updates

In this update, a new class, java.util.cuncurrent.Flow , has been introduced, which has java.util.concurrent nested interfaces supporting the implementation of a publish-subscribe framework. The publish-subscribe framework enables developers to build components that can asynchronously consume a live stream of data by setting up publishers that produce the data and subscribers that consume the data via subscription, which manages them. The four new interfaces are as follows: java.util.concurrent.Flow.Publisher java.util.concurrent.Flow.Subscriber java.util.concurrent.Flow.Subscription (which acts as both and Subscriber). java.util.concurrent.Flow.Processor

Java 9 : multi-release JAR files

As of now, JAR files can contain classes that can only run on the Java version they were compiled for. To leverage the new features of the Java platform on newer versions, the library developers have to release a newer version of their library. Soon, there will be multiple versions of the library being maintained by the developers, which can be a nightmare. To overcome this limitation, the new feature of multirelease JAR files allows developers to build JAR files with different versions of class files for different Java versions. The following example makes it more clear. Here is an illustration of the current JAR files: jar root - A.class - B.class - C.class Here is how multirelease JAR files look: jar root - A.class - B.class - C.class   - META-INF      - versions         - 9              - A.class         - 10              - B...

Java 9 : jshell -- the Java shell (Read- Eval-Print Loop)

Image
You must have seen languages, such as Ruby, Scala, Groovy, Clojure, and others shipping with a tool, which is often called REPL (Read-Eval-Print-Loop). This REPL tool is extremely useful in trying out the language features. For example, in Scala, we can write a simple Hello World program as scala> println("Hello World"); Some of the advantages of the JShell REPL are as follows: Help language learners to quickly try out the language features Help experienced developers to quickly prototype and experiment before adopting it in their main code base Java developers can now boast of an REPL Let's quickly spawn our command prompts/terminals and run the JShell command, as shown in the following image: