JSF Custom Converter Example

JSF 2 Custom Converter Example - Pretech Blog: JSF 2 Custom Converter Example

JSF 2 PhaseListener example

JSF PhaseListener

As we know JSF life cycle and if we want to trace each phase we can use the PhaseEvent api , here is one simple JSF 2 example which is using phase listener (via method binding) in the managed bean and printing messages on each phase.

Create a Managed Bean 

In this managed bean we need to add a method with the argument as PhaseEvent, use this this event object we can get the phase details

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;

@ManagedBean
public class PhaseListenerBean {
    public String getMessage() {
        return "Hello World!";
    }

    public void phaseTest(PhaseEvent evt) throws Exception {
        try {
            if (PhaseId.APPLY_REQUEST_VALUES.equals(evt.getPhaseId())) {
                System.out.println("Phase is " + PhaseId.APPLY_REQUEST_VALUES);
            }
            if (PhaseId.INVOKE_APPLICATION.equals(evt.getPhaseId())) {
                System.out.println("Phase is " + PhaseId.INVOKE_APPLICATION);
            }
            if (PhaseId.RENDER_RESPONSE.equals(evt.getPhaseId())) {
                System.out.println("Phase is " + PhaseId.RENDER_RESPONSE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String actionSubmit() {
        System.out.println("Action submit triggered");
        return "phase.xhtml";

    }
}
 

Create a JSF page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
<h:head>
    <title>Facelet Title</title>
    <f:view beforePhase="#{phaseListenerBean.phaseTest}" />
</h:head>
<h:body>
    <h:form>
            Hello from Facelets
            #{phaseListenerBean.message}
            <h:commandButton value="Submit" id="submit"
            action="#{phaseListenerBean.actionSubmit}" />
    </h:form>
</h:body>
</html>
 

Run Application and click on the submit button (phase.xhtml) and we can see the console it is printing the phases

 

Phase is RENDER_RESPONSE 6

 

Phase is APPLY_REQUEST_VALUES 2

 

Phase is INVOKE_APPLICATION 5

 

Action submit triggered

 

Phase is RENDER_RESPONSE 6


 


Done..download application ..use mvn jetty:run to run the application

Java Mongodb Hello world example

Java Mongodb Connection example - Pretech Blog

Java program to normalize different forms of IPV4

Different representation of IPV4 in Java - Pretech Blog

Different representation of IPV4 in Java

🌐 IPv4 Address — Different Representations & Normalization Using Java

When working with networks, operating systems, or low-level protocols, an IPv4 address may not always appear in the familiar dotted-decimal form like:

192.0.2.235

An IPv4 address is fundamentally a 32-bit integer, and therefore it can be represented in multiple notations:

Representation FormatExampleDescription
Dotted Decimal192.0.2.235Standard human-friendly format
Dotted Hexadecimal0xC0.0x00.0x02.0xEBEach octet represented in base-16
Dotted Octal0300.0000.0002.0353Each octet represented in base-8
Hexadecimal (no dots)0xC00002EBFull 32-bit value as a single hex number
Decimal (no dots)3221226219Full 32-bit value represented as decimal
Octal (no dots)030000001353Full 32-bit value represented as octal

👉 All of the above represent the same IPv4 address:

192.0.2.235


🧠 Why does this matter?

Some operating systems, browsers, and networking libraries accept alternative representations of IP addresses.
This can be exploited:

  • To evade security filters (firewalls, validation rules).

  • To bypass URL allow/block lists (e.g., app allows only whitelisted domain IP).

Example:

http://0xC00002EB → interpreted internally as 192.0.2.235

✅ Java Program — Normalize any IPv4 Representation

The following Java program accepts an IPv4 address in any supported notation (hex, octal, dotted, decimal), normalizes it, and prints it back in standard dotted decimal format.

package com.pretech; import java.net.URL; import java.util.StringTokenizer; import java.util.regex.Pattern; public class Ipv4Example { private static final Pattern IPV4REGEX = Pattern.compile( "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b" ); public static void main(String[] args) { try { System.out.println(createHostAddress("http://192.0.2.235")); System.out.println(createHostAddress("http://0xC0.0x00.0x02.0xEB")); System.out.println(createHostAddress("http://0300.0000.0002.0353")); System.out.println(createHostAddress("http://0xC00002EB")); System.out.println(createHostAddress("http://030000001353")); } catch (Exception e) { e.printStackTrace(); } } private static String createHostAddress(final String url) throws Exception { URL urldetails = new URL(url); String addr = urldetails.getHost(); boolean validHost = true; StringBuffer hostStringBuffer = new StringBuffer(); try { StringTokenizer hostTokenizer = new StringTokenizer(addr, "."); int tokenCount = hostTokenizer.countTokens(); // Case 1: nondotted hex or decimal number format if (isNumber(addr) && tokenCount == 1) { long decimalIpAddress = Long.decode(addr); hostStringBuffer.append(longToIpAddress(decimalIpAddress)); if (!IPV4REGEX.matcher(hostStringBuffer.toString()).matches()) { validHost = false; } // Case 2: dotted hex or dotted octal representation } else if (isNumber(addr) && tokenCount > 1) { int i = 0; while (hostTokenizer.hasMoreTokens()) { String token = hostTokenizer.nextToken(); hostStringBuffer.append(Integer.toString(Integer.decode(token))); if (i < 3) { hostStringBuffer.append("."); } i++; } if (!IPV4REGEX.matcher(hostStringBuffer.toString()).matches()) { validHost = false; } } else { // Other host formats hostStringBuffer.append(addr); } if (!validHost) { throw new Exception("Invalid Host name"); } } catch (Exception e) { throw new Exception("Invalid Host name: " + e.getMessage(), e); } return hostStringBuffer.toString(); } // Convert long format to dotted decimal IP public static String longToIpAddress(long ipAddress) { StringBuilder ipStringBuffer = new StringBuilder(); for (int i = 0; i < 4; i++) { ipStringBuffer.insert(0, Long.toString(ipAddress & 0xff)); if (i < 3) { ipStringBuffer.insert(0, '.'); } ipAddress >>= 8; } return ipStringBuffer.toString(); } private static boolean isNumber(final String addr) { try { StringTokenizer addrTokenizer = new StringTokenizer(addr, "."); while (addrTokenizer.hasMoreTokens()) { String token = addrTokenizer.nextToken(); Long.decode(token); // detects hex (0x..), octal (0..), decimal } return true; } catch (Exception e) { return false; } } }

🖨 Output

192.0.2.235 192.0.2.235 192.0.2.235 192.0.2.235 192.0.2.235

IPV6 Java Regular expression example

Pattern

private static final Pattern IPV6REGEX = Pattern.compile(""
+ "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}"
+ "|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]"
+ "|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,"
+ "4})(?<![^:]:|\\.)\\z", Pattern.CASE_INSENSITIVE);

Example

package com.pretech;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

public class Ipv6Example {
private static final Pattern IPV6REGEX = Pattern.compile(
"" + "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}"
+ "|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]"
+ "|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,"
+ "4})(?<![^:]:|\\.)\\z",
Pattern.CASE_INSENSITIVE);

public static void main(String[] args) {

URL url;
int i1, i2;

try {
url = new URL("http://[FF01:0:0:0:0:0:0:0101]");
String originalHostName = url.getHost();

System.out.println(originalHostName);
if (originalHostName.startsWith("[") && originalHostName.endsWith("]")) {

i1 = originalHostName.indexOf("[");

originalHostName = originalHostName.substring(i1 + 1);

i2 = originalHostName.lastIndexOf("]");

originalHostName = originalHostName.substring(0, i2);

if (IPV6REGEX.matcher(originalHostName).matches()) {

System.out.println(url + " is a ipv6 address");
String hostName = InetAddress.getByName(originalHostName).getHostAddress().toLowerCase();
if (hostName.contains(":")) {
hostName = "[" + hostName + "]";
}

}
}

} catch (MalformedURLException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Output

[FF01:0:0:0:0:0:0:0101]
http://[FF01:0:0:0:0:0:0:0101] is a ipv6 address

Thread safe Arraylist Example (CopyOnWriteArrayList Example)

What is CopyOnWriteArrayList ?

 A thread-safe variant of java.util.ArrayList in which all mutative operations (add,set,and so on) are implemented by making a fresh copy of the underlying array.

Example

package com.collections;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample {
    public static void main(String[] args) {
        ArrayList al = new ArrayList();
        al.add("sunday");
        al.add("monday");
        al.add("tuesday");
        Iterator<String> alIterator = al.iterator();
        while (alIterator.hasNext()) {
            String value = alIterator.next();
                al.add("wednesday");
        }
        System.out.println(al);
        CopyOnWriteArrayList coal = new CopyOnWriteArrayList();
        coal.add("sunday");
        coal.add("monday");
        coal.add("tuesday");
        Iterator<String> coalIterator = coal.iterator();
        while (coalIterator.hasNext()) {
            String value = coalIterator.next();
                coal.add("wednesday");
        }
        System.out.println(coal);
    }
}

Output

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at com.collections.CopyOnWriteArrayListExample.main(CopyOnWriteArrayListExample.java:17)

In this example while adding element in to ArrayList throwing above exception, to overcome this we can make use of CopyOnWriteArrayList.

Please comment below line and run the program

    al.add("wednesday");

Output after commenting

[sunday, monday, tuesday]
[sunday, monday, tuesday, wednesday, wednesday, wednesday]

How to continue Java loop if exception occurred

Example

package com.vinod;

import java.util.*;

public class ExceptionTest {

    public static void main(String[] args) {
        List al = new ArrayList();
        al.add("1");
        al.add("5");
        al.add("pretech");
        al.add("6");

        // iterating arraylist and expecting NumberFormat exception

        for (int i = 0; i <= al.size() - 1; i++) {
            try {
                int a = Integer.parseInt((String) al.get(i));
                System.out.println("value :" + a);
            } catch (Exception e) {
                try {
                    throw e;
                } catch (Exception e1) {
                    System.out.println(e);

                }
            }
        }

    }

}

Output

value :1
value :5
java.lang.NumberFormatException: For input string: "pretech"
value :6

Java Escape sequences Examples

Java Escape sequences Examples

Java Escape sequences

Escape Sequence Description
\t tab
\n new line
\r carriage return
\' single quote
\" double quote
\\ backslash

Example

Here is one printing example which is using escape sequences.

package com.http;

public class JavaEscapes {

    public JavaEscapes() {
    }
    public static void main(String[] args) {
            System.out.println("Start\tProcess\tStop");
            System.out.println("Start\nProcess\nStop");
            System.out.println("Start\rProcess\rStop");
            System.out.println("Start\'Process\'Stop");
            System.out.println("Start\"Process\"Stop");
            System.out.println("Start\\Process\\Stop");
    }

}

Output

Start Process Stop
Start
Process
Stop
Start
Process
Stop
Start'Process'Stop
Start"Process"Stop
Start\Process\Stop

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts