Wednesday, March 27, 2019

How to use Callable Statement in Java to call Stored Procedure? JDBC Example

The CallableStatement of JDBC API is used to call a stored procedure from Java Program. Calling a stored procedure follows the same pattern as creating PreparedStatment and than executing it. You first need to create a database connection by supplying all the relevant details e.g. database URL, which comprise JDBC protocol and hostname, username, and password. Make sure your JDBC URL is acceptable by JDBC driver you are using to connect to the database. Every database vendor uses different JDBC URL and they have different driver JAR which must be in your classpath before you can run the stored procedure from Java Program.

Oracle Java Certifications, Oracle Java Learning, Oracle Java Tutorial and Material

Once you are done with initial setup, you can obtain CallableStatement from Connection by calling prepareCall(String SQL) method, where SQL must be in the format required by your database vendor e.g. Microsoft SQL Server requires curly braces e.g.
{call Books.BookDetails_Get(?)}.

This stored proc requires an INPUT parameter which must be set by calling setXXX() method on the CallableStatement object before you can execute the query.

Once this is done, just call the executeQuery() method of CallableStatement and it will return the ResultSet contains all the rows returned by this stored proc.

Just loop through ResultSet and extract all the rows. You have successfully run the stored procedure from Java Program using CallableStatement.

Steps to call a stored procedure from Java


1) Create a database connection.

Connection con = null;
try {
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   String url = "jdbc:sqlserver://localhost:42588;";
   con = DriverManager.getConnection(url, "username", "pw");
} catch (Exception e) {
   e.printStackTrace();
}

2) Create a SQL String

You need to create SQL using a String variable to call the stored procedure, for example, CallableStatement e.g. {call Books.BookDetails_Get(?)}. This is database dependent, for Oracle the format is different it starts with BEGIN and ends with ENDS instead of curly braces e.g.

String SQL = "{call Books.BookDetails_Get(?)}" // for Microsoft SQL Server
String Oracle = "BEGIN BOOKDETAILS_GET(?); END;";

3) Create CallableStatement Object

You can create a CallableStatement by calling Connection.prepareCall(SQL) method, pass the SQL created in the previous step.

CallableStatement cs = con.prepareCall(SQL);

4)  Provide Input Parameters

You can set the input parameter by calling various setXXX() method depending upon the data type of query parameters on the CallableStatement object, similar to PreparedStatment e.g.

cs.setString(1, "982928");

5)  Call Stored Procedure

You can execute a stored procedure on the database by calling executeQuery() method of CallableStatement class, as shown below:

ResultSet rs = cs.executeQuery();

This will return a ResultSet object which contains rows returned by your stored procedure.

6) Extract Rows from ResultSet

You can get the data from the ResultSet by Iterating over ResultSet and print the results or create Java objects, as shown below:

while(rs.next()){
  System.out.println(rs.getString(1));
}

This will print the first column of every row. You should also close the ResultSet object once you are done with it.

Oracle Java Certifications, Oracle Java Learning, Oracle Java Tutorial and Material

Java Program to call Stored Procedure in SQL Server using CallableStatement


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

/**
 *
 * A Simple example to use CallableStatement in Java Program.
 */
public class Hello {

  public static void main(String args[]) {
   
    Connection con = null;
    try {
       Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       String url = "jdbc:sqlserver://localhost:42588;";
       con = DriverManager.getConnection(url, "username", "pw");
    } catch (Exception e) {
       e.printStackTrace();
    }

    String SQL = "{call Books.dbo.usp_BookDetails_Get(?)}";

    CallableStatement cs = con.prepareCall(SQL);

    cs.setString(1, "978-0132778046");

    cs.setString(2, "978-0132778047");

    ResultSet rs = cs.executeQuery();
   
    while(rs.next()){
      System.out.println(rs.getString(1));
    }
   
    rs.close();
  }
}

That's all about how to run CallableStatement in Java JDBC. If you are thinking to build your Data Access layer around stored procedures, which is a great design, then you should have a good understanding of CallableStatement.

They are the ones which are used to run the stored procedure from Java programs. By encapsulating your data access logic and SQL on a stored procedure, allow you to change them easily on SQL editor without making any change on Java side, which means you can implement new functionalities without building and deploying a new JAR file on Java side.

Monday, March 25, 2019

How to convert JSON String to Java object - Jackson Example

Oracle Java Tutorial and Material, Oracle Java Certifications, Oracle Java Guides

JSON stands for JavaScript object notation, is a lightweight text or string representation of an object and quickly becoming a popular data exchange format. Though it's pretty early to say that JSON is going to replace XML as popular data interchange format, It is certainly providing an alternative. JSON represent data in two format either an object or an array. JSON object is an unordered collection of key and value, similar to String representation of hash table. On the other hand, JSON Array is an ordered collection of values. The main difference between  JSON Object and  JSON array is there representation. JSON object is started with left brace { and ends with right brace } and key values are separated using a colon (:). On the other hand, JSON Array starts with left bracket [ and ends with right bracket ] and each value is separated by comma. By looking at structure, You can write  your JSON parser to parse JSON object or array to Java object, but you don't need to.

There are lot of open source library in Java which provides tried and tested way of converting JSON String to Java object e.g. Jackson and GSON. In this Java tutorial we will see example of converting a JSON String to Java object using Jackson library

How to convert JSON String to Java object using Jackson


It's very easy to create Java object from JSON String using Jackson library. It's literally require two lines of code to do this, as shown in following Java example. If you look at code, most of code is for creating Java class e.g. User in this case, while code required to convert JSON String to Java object is just two lines in fromJson(String json) method.

This method takes an Jon String which represent a User object in JSON format and convert it into Java User object. In this Java example I have create User as nested static class for convenience, You may create a separate top level class if needed.

import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/*
 * Java program to convert JSON String into Java object using Jackson library.
 * Jackson is very easy to use and require just two lines of code to create a Java object
 * from JSON String format.
 *
 * @author http://javarevisited.blogspot.com
 */
public class JsonToJavaConverter {

        private static Logger logger = Logger.getLogger(JsonToJavaConverter.class);
   
   
        public static void main(String args[]) throws JsonParseException
                                                    , JsonMappingException, IOException{

                JsonToJavaConverter converter = new JsonToJavaConverter();
           
                String json = "{\n" +
                "    \"name\": \"Garima\",\n" +
                "    \"surname\": \"Joshi\",\n" +
                "    \"phone\": 9832734651}";
           
                //converting JSON String to Java object
                converter.fromJson(json);
        }
   
   
        public Object fromJson(String json) throws JsonParseException
                                                   , JsonMappingException, IOException{
                User garima = new ObjectMapper().readValue(json, User.class);
                logger.info("Java Object created from JSON String ");
                logger.info("JSON String : " + json);
                logger.info("Java Object : " + garima);
           
                return garima;
        }
   
   
        public static class User{
                private String name;
                private String surname;
                private long phone;
           
                public String getName() {return name;}
                public void setName(String name) {this.name = name;}

                public String getSurname() {return surname;}
                public void setSurname(String surname) {this.surname = surname;}

                public long getPhone() {return phone;}
                public void setPhone(long phone) {this.phone = phone;}

                @Override
                public String toString() {
                        return "User [name=" + name + ", surname=" + surname + ", phone="
                                        + phone + "]";
                }
           
             
        }
}

Output:
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object created from JSON String
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - JSON String : {
    "name": "Garima",
    "surname": "Joshi",
    "phone": 9832734651}
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object : User [name=Garima, surname=Joshi, phone=9832734651]

Dependency

As I said, You can either use Jackson or Gson to convert JSON String to Java object and in this Java tutorial we have used Jackson library for JSON to Java object conversion. If you are using Maven for dependency management than you can add following dependency in POM.xml :

<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-xc</artifactId>
      <version>1.9.11</version>
</dependency>

Or you can simply add following JAR files into your application’s classpath :

jackson-xc-1.9.11.jar
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

That's all on How to convert JSON String to Java object using Jackson library. Though, this is a trivial example and actual object could be more complex, it demonstrate the process of creating Java object from JSON String. You can also use other JSON library like GSON instead of Jackson to convert JSON String to Java object.

Monday, October 8, 2018

Java - Convert String to Boolean Example

There are two ways to convert a String to boolean in Java, first, by using Boolean.parseBoolean() method and second, by using Boolean.valueOf() method.The parseBoolean() method returns an equivalent boolean value of given String, for example, if you pass "true" it will return the primitive boolean value true. Similarly, if you pass "false" it will return false. The good thing about this method is that it is case insensitive, which means if you pass "true", "TRUE", or "True" you will still get a true boolean value.

 Another good thing about this method is that it doesn't throw an exception if you pass any String value other than true and false. For example, if you pass "YES" it will return false, which is not obvious but that's still better than throwing an exception like NumberFormatException.

The Boolean.valueOf() method work similar, it returns a true boolean value for a non-null String equal to true, ignoring case and returns false for everything else. It also returns a Boolean object instead of a primitive boolean value.

Also, both valueOf() and parseBoolean() methods are null safe, which means they will return false if you pass null i.e. parseBoolean(null) and valueOf(null) will return false instead of throwing NullPointerExcpeiton.

1. Boolean.parseBoolean() Examples


// parseBoolean returns a boolean primitive value
String value = "true";
boolean b = Boolean.parseBoolean(value);
System.out.println(b);

Output
true

2. Boolean.valueOf() Examples


// valueOf returns a Boolean object
String data = "false";
boolean f = Boolean.valueOf(data);
System.out.println(f);
Output
false

Btw, there is another way to convert String to Boolean in Java, by using the constructor of Boolean class e.g. new Boolean(String input) but I won't advise you to use that because everytime you will use this method it will return a new Boolean Object.

Instead, you should always use valueOf() method because Boolean instances are immutable and just two instances are enough to cover all scenarios.

Difference between parseBoolean and valueOf() in Java


Even though both methods can be used to parse a String to a boolean value, there is a slight difference between them. The parseBoolean() method returns a primitive boolean value while the valueOf() returns a Boolean object.

Though in the age of auto-boxing, a Boolean can easily be stored in a boolean variable, this is an important difference which you should remember.

Another benefit of using the valueOf() method is that it caches the boolean value and returns the already created Boolean.TRUE and Boolean.FALSE value instead of creating a new instance every time.

RUE and Boolean.FALSE value instead of creating a new instance every time.

If you don't need a new instance of the Boolean object then you should always use Boolean.valueOf() method to create Boolean objects to get better performance.

This method is also overloaded to create a Boolean object from both Strings as well as primitive boolean value e.g. both valueOf(true) and valueOf("true") will return same Boolean.TRUE object.

In short:

Oracle Java Tutorial and Materials, Oracle Java Learning, Oracle Java Study Materials, Oracle Java Guides

Java Program to Convert String to Boolean


Here is our complete Java program to convert String to Boolean in Java. It's quite similar to the earlier program for converting String to Integer, Long, Double, Float, Short, and Byte in Java. All of them follow same technique to convert String to other data types. 

/**
 * 
 * A simple example to convert String to Boolean in Java
 */
public class Hello {

  public static void main(String args[]) {

    // parseBoolean returns a boolean primitive value
    String value = "true";
    boolean b = Boolean.parseBoolean(value);
    System.out.println(b);

    // valueOf returns a Boolean object
    String data = "false";
    boolean f = Boolean.valueOf(data);
    System.out.println(f);

    value = "NO";
    b = Boolean.parseBoolean(value);
    System.out.println(b);

    // null String will return false
    System.out.println(Boolean.parseBoolean(null));
    System.out.println(Boolean.valueOf(null));

    // any value other than true (Case-insensitive) will
    // return false
    System.out.println(Boolean.parseBoolean("YES"));
    System.out.println(Boolean.valueOf("Y"));
  }
}

Output
true
false
false
false
false
false
false

Important Points


Some important points about parseBoolean and valueOf methods which are worth remembering:

1. Both parseBoolean() and valueOf() are static methods defined in java.lang.Boolean class.

2. The parseBoolean() returns a primitive boolean value while valueOf() returns a Boolean object.

3. Both parseBoolean() and valueOf() are null-safe which means if you pass null String to them they will return false boolean value instead of throwing NullPointerException.

4. Both methods are also case-insensitive, which means "true", "TRUE", and "True" will return same Boolean.TRUE value.

5. Prefer valueOf() over parseBoolean() if you need Boolean object because it returns cached Boolean objects, defined in the Boolean class itself i.e. Boolean.TRUE for true and Boolean.FALSE for false.

6. The valueOf() provides better performance because of caching.

7. Autoboxing boolean primitive to Boolean object also uses the Boolean.valueOf() method.

That's all about how to convert a String to boolean in Java. You should use the Boolean.parseBoolean() method if you need a primitive boolean value and Boolean.valueOf() if you need a Boolean object. The valueOf() method also provide better performance because it always returns the two pre-created instance i.e. Boolean.TRUE and Boolean.FALSE instead of creating a new object everytime you parse a String to boolean.

Monday, October 1, 2018

How to Subtract two Binary Numbers in Java

Binary subtraction is very similar to binary addition which we have learned in the last article. In this tutorial, you will learn how to subtract two binary numbers. Similar to the last article, we'll see two ways, first by converting binary String to a binary number and then doing subtraction. You can use the Java API Integer.toString(number, radix) for that. On second solution you will learn to develop the logic to perform binary subtraction in Java program by using rules you might have learned in your computer classes. Here is a little summary of how binary subtraction works.

Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Certification

Subtraction works in much the same way:

0 − 0 → 0
0 − 1 → 1, borrow 1
1 − 0 → 1
1 − 1 → 0

Subtracting a "1" digit from a "0" digit produces the digit "1", while 1 will have to be subtracted from the next column. This is known as borrowing. The principle is the same as for carrying. When the result of a subtraction is less than 0, the least possible value of a digit, the procedure is to "borrow" the deficit divided by the radix (that is, 10/10) from the left, subtracting it from the next positional value.

There are also a couple of other ways to perform binary subtraction e.g. binary subtraction using 1's complement and binary subtraction using 2's complement. Let's see how those work by first subtracting two binary number using 1's complement:

How to subtract two binary numbers using 1's complement

In one's complement, you negate the binary number where 1 turned to zero and zero turned to 1. Here are the exact steps to subtract two binary number using 1's complement:

1) Calculate1’s complement of the subtrahend.
2) Add 1's complement with the minuend.
3) If the result of addition has a carryover then it is dropped and a 1 is added in the last bit.
4) If there is no carryover, then 1’s complement of the result of the addition is obtained to get the final result and it is negative.

Example: What is the difference between two binary numbers 110101 – 100101?

Solution: 1’s complement of 10011 is 011010.
Hence

Minuted - 110101
1’s complement of subtrahend - 011010
Carryover - 1 001111
1
010000
The required difference is 10000

Here is another example of subtracting 101011 – 111001. First, let's calculate 1’s complement of 111001, which is 000110.
Hence

Minued - 101011
1’s complement - 000110
difference - 110001

Hence the difference between two binary numbers 101011 and 111001 is 1110

Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Certification

Java Program to subtract two binary numbers


import java.util.Scanner;

/*
 * Java Program to add subtract two binary numbers.
 * You can either write your own method or you 
 * can use Java API for doing binary subtraction.
 * 
 * input: 110101 - 100101
 * output = 1111
 */

public class Main {

  public static void main(String[] args) {

    System.out.println("Welcome to Java program to add two binary numbers");
    Scanner scnr = new Scanner(System.in);

    System.out.println("Please enter first binary number");
    String first = scnr.nextLine();

    System.out.println("Please enter second binary number");
    String second = scnr.nextLine();

    String difference = subtract(first, second);
    System.out.println("difference between two binary number is : "
        + difference);

    scnr.close();

  }

  /**
   * Java method to calculate the difference between two binary numbers this method
   * calculate sum by first converting binary String to binary numbers and then
   * subtracting them using binary arithmetic.
   * 
   * @param first
   * @param second
   * @return sum of two given binary numbers
   */
  public static String subtract(String first, String second) {
    int b1 = Integer.parseInt(first, 2);
    int b2 = Integer.parseInt(second, 2);
    int sum = b1 - b2;
    return Integer.toBinaryString(sum);
  }

}

Output
Welcome to Java program to add two binary numbers
Please enter the first binary number
110101
Please enter the second binary number
100101
difference between two binary number is: 10000

Tuesday, September 4, 2018

3 ways to convert String to byte array in Java - Example

I am going to discuss one of the common tasks for programmers, converting a String to a byte array. You need to do that for multiple reasons e.g. for saving content to a file, sending over a network or maybe some other reason. Suppose you have a String "abcd" and you want to convert it into a byte array, how will you do that in a Java program? Remember, String is made of the char array, so it involves character to byte conversion, which is subject to character encoding intricacies. Thankfully, Java provides a convenient getBytes() method to convert String to byte array in Java, but unfortunately, many developers don't use it correctly. Almost 70% of the code I have reviewed uses getBytes() without character encoding, leaving it on the chance that platform's default character encoding will be same as of the source String.

Oracle Java String, Oracle Java Tutorial and Material, Java Certification

The right way to use getBytes() should always be with explicit character encoding, as shown in this article. Java even comes with some standard set of character encoding which is supported out-of-box by StandardCharset class, we will review them as well.

It's also a good practice is to use the pre-defined contestants for specifying character encoding in your code instead of using a free text or String to avoid typos and other silly mistakes.

String to byte array using getBytes()


This is the most common way to convert a String into a byte array, it works most of the time but it's error-prone and can produce an erroneous result if platform's character encoding doesn't match with expected encoding.

Here is an example of converting String to byte[] in Java :

// converts String to bytes using platform's default character encoding,
// in Eclipse it's Cp1252
// in Linux it could be something else
byte[] ascii = "abcdefgh".getBytes();

System.out.println("platform's default character encoding : "
                     + System.getProperty("file.encoding"));
System.out.println("length of byte array in default encoding : "
                     + ascii.length);
System.out.println("contents of byte array in default encoding: "
                     + Arrays.toString(ascii));

Output :
platform's default character encoding : Cp1252
length of byte array in default encoding : 8
contents of byte array in default encoding: [97, 98, 99, 100,
                                               101, 102, 103, 104]

Remark :

1) Platform's default encoding is used for converting a character to bytes if you don't specify any character encoding.

2) You can see platform's default character encoding by using System.getProperty("file.encoding");, this return the default character encoding of the machine your JVM is running.

3) Beware, your code may work in one environment e.g. QA but not work in production because of different default character encoding. That's why you should not rely on default character encoding.

4) length of byte array may not be same as the length of String, it depends upon character encoding. Some character encoding is multi-byte but usually, take 1 byte to encode ASCII characters.

String to byte array using getBytes("encoding)


Here is another way to convert a String to a byte array but this time by specifying the proper encoding to leave any guess or platform default aside.

// convert String to bytes of specified character encoding but
// also throw checked UnsupportedEncodingException, which pollutes the code
try {
byte[] utf16 = "abcdefgh".getBytes("UTF-16");
System.out.println("length of byte array in UTF-16 charater encoding : "
 + utf16.length);
System.out.println("contents of byte array in UTF-16 encoding: "
 + Arrays.toString(utf16));

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

Output :
length of byte array in UTF-16 charater encoding : 18
contents of byte array in UTF-16 encoding: [-2, -1, 0, 97,
0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104]

Remark :

1) It's better than the previous approach but throws a checked exception java.io.UnsupportedEncodingException, if character encoding String has a typo or specifies and character encoding not supported by Java.

2) The returned byte array is on specified character encoding

3) You can see that length of the byte array is not same as a number of characters in String as was the case in the previous example because UTF-16 encoding takes at-least 2 bytes to encode a character.

String to byte array using getBytes(Charset)

This is third but probably the best way to convert to String to byte[] in Java. In this example, I have used java.nio.StandardCharsets to specify character encoding. This class contains some of the widely used character encoding constants e.g. UTF-8, UTF-16 etc.

A good thing about this approach is that it doesn't throw checked java.io.UnsupportedEncodingException, but unfortunately this class is only available from JDK 7 onward so it might not be an option for several Java application running on Java 6 and lower version.

// return bytes in UTF-8 character encoding
// pros - no need to handle UnsupportedEncodingException
// pros - bytes in specified encoding scheme
byte[] utf8 = "abcdefgh".getBytes(StandardCharsets.UTF_8);
System.out.println("length of byte array in UTF-8 : " + utf8.length);
System.out.println("contents of byte array in UTF-8: " + Arrays.toString(utf8));

Output:

length of byte array in UTF-8 : 8
contents of byte array in UTF-8: [97, 98, 99, 100, 101, 102, 103, 104]

Remarks :

1) This is the best way to convert String to a byte array in Java.

2) This doesn't throw java.io.UnsupportedEncodingException exception, which means no boilerplate code for handling this checked exception.

3) Though, you must keep in in mind that StandarhardCasets class is only available from Java 7 onward.

That's all about how to convert a String to byte array in Java. Remember the size of byte array can be more than the length of String because it's not necessary that one byte is used to encode one character, it all depends on character encoding. For example, UTF-8 is a multi-byte character encoding scheme and uses between 1 to 4 bytes per character. In general, characters of the old ASCII range takes 1 bytes but characters from the old ISO-8859 range beyond ASCII takes 2 bytes.

Monday, April 30, 2018

JavaFX WebView Overview

In this blog, we will be looking at how JavaFX can render webpages and the component responsible for it – which is known as WebView

JavaFX is a:

◈ Software platform for creating and delivering desktop applications, as well as rich internet applications (RIAs) that can run across a wide variety of devices.

◈ Set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms.


JavaFX Key Features:


Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

WebView: A web component that uses WebKit HTML technology to make it possible to embed web pages within a JavaFX application. JavaScript running in WebView can call Java APIs, and Java APIs can call JavaScript running in WebView. Support for additional HTML5 features, including Web Sockets, Web Workers, and Web Fonts, and printing capabilities have been added in JavaFX.

JavaFX WebView:

  • JavaFX WebView is a mini browser (also called as an embedded browser) that provides a web viewer and full browsing functionality through its API  in JavaFX applications.
  • This browser is based on WebKit, that is a open source web browser engine that supports HTML5, JavaScript, CSS, DOM rendering and SVG graphics.
  • The WebView class is an extension of the Node class.
  • The embedded browser inherits all fields and methods from the Node class, and therefore, it has all its features.
  • It encapsulates a WebEngine object, incorporates HTML content into an application's scene, and provides properties and methods to apply effects and transformations.
  • The getEngine() method called on a WebView object returns a Web Engine associated with it.
  • The classes that constitute the embedded browser reside in the javafx.scene.web package.
  • WebView  enables developers to implement the following features in their Java applications:
    • Render HTML content from local or remote URLs
    • Support history and provide Back and Forward navigation
    • Reload the content
    • Apply effects to the web component
    • Edit the HTML content
    • Execute JavaScript commands
    • Perform upcalls from JavaScript to JavaFX
    • Handle events
  • WebView component supports the following HTML5 features apart from supporting CSS3 and ecmascript6 (ES6):
    • DOM3
    • Canvas
    • Media Playback
    • Form controls (except for <input type="color"> )
    • Editable content
    • History maintenance
    • Support for the <meter>, <progress>, <details> and <summary> tags
    • SVG
    • Web Sockets
    • Web Workers
    • Support for domain names written in national languages
Below diagram depicts architecture of embedded browser and its relation to other JavaFX classes:

Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

Web Engine:


1. is a non-visual object capable of managing one Web page at a time

2. Provides basic web page functionality through its API.

3. It supports user interaction such as navigating links and submitting HTML forms, although it does not interact with users directly.

4. It loads Web pages, creates their document models, applies styles as necessary, and runs JavaScript on pages.

5. It provides access  to the document model of the current page, and enables two-way communication between a Java application and JavaScript code of the page.

6. It wraps a WebPage object, which provides interaction with the native Webkit core.

Relationship between WebView and WebEngine classes:

Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

Code Snippet for Loading content in JavaFX WebView:


1. Create WebView, WebEngine objects and load via Remote URL.:


Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

2. Load Static HTML Content:


Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

3. Loading HTML content from local file:


Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

4. To track Load Progress with the help of LoadWorker:


◈ Loading always happens on a background thread. Methods that initiate loading return immediately after scheduling a background job.

◈ To track progress and/or cancel a job, we can use the Worker instance available from the getLoadWorker() method.

◈ The following example changes the stage title when loading completes successfully:

Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

5. Access to Document Model


◈ The WebEngine objects create and manage a Document Object Model (DOM) for their Web pages. The model can be accessed and modified using Java DOM Core classes.

◈ The getDocument() method provides access to the root of the model. Additionally DOM Event specification is supported to define event handlers in Java code.

◈ The following example attaches a Java event listener to an element of a Web page. Clicking on the element causes the application to exit:

Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

6. Calling Javascript from JavaFX:


◈ After WebView loads a website, it is possible to execute arbitrary JavaScript code in the context of the current page using the executeScript(java.lang.String) method.

Oracle JavaFX, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

7. Mapping JavaScript values to Java objects:


◈ JavaScript values are represented using the obvious Java classes: null becomes Java null; a boolean becomes a java.lang.Boolean; and a string becomes a java.lang.String.

◈ If the result is a JavaScript object, it is wrapped as an instance of the JSObject class.

◈ The JSObject class is a proxy that provides access to methods and properties of its underlying JavaScript object.

◈ The most commonly used JSObject methods are getMember (to read a named property), setMember (to set or define a property), and call (to call a function-valued property).

◈ A DOM Node is mapped to an object that both extends JSObject and implements the appropriate DOM interfaces. To get a JSObject object for a Node just do a cast:

JSObject jdoc = (JSObject) webEngine.getDocument();

8. Mapping Java objects to JavaScript values:


◈ The arguments of the JSObject methods setMember and call pass Java objects to the JavaScript environment.

◈ This is roughly the inverse of the JavaScript-to-Java mapping described above: Java String, Number, or Boolean objects are converted to the obvious JavaScript values.

◈ A JSObject object is converted to the original wrapped JavaScript object. Otherwise a JavaRuntimeObject is created.

◈ This is a JavaScript object that acts as a proxy for the Java object, in that accessing properties of the JavaRuntimeObject causes the Java field or method with the same name to be accessed.