Immutable Objects in Java

Reading Time: 3 minutes

Immutability of an object indicates that once an object is constructed with given values, its state and values cannot be altered. In case of any value change must result in new object creation.

Out of box Java offers some Immutable objects for instance java.lang.String, java.lang.Integer, java.lang.Float, java.math.BigDecimal.

Immutable objects make generally a good use in concurrent programming. The reliability is a key aspect in concurrent programming, so that corrupted data sets and objects may cause unwanted behaviors in applications.

Pros

  • Reliable and Atomic Data: The given data during the initialization of the immutable object is always the same, thus the data set is ensured and atomic. Furthermore, An Immutable object can be a good candidate to be the Key in Map collection,
  • Thread Safety/Concurrency: The content of an immutable object is valid and no method may cause an alteration of the state thus it is thread safe,
  • Garbage Collection: The garbage collectors can easily identify and make decisions on immutable objects.

Cons

  • Mass of objects: Allocating lots of new objects may cause to increase the memory allocation for modifications. This can be somehow manageable while employing a good model of java memory management.

Rules to define an Immutable Object:
Immutability of an object indicates that once an object is constructed with given values, its state and values cannot be altered. In case of any value change must result in new object creation.
Out of box Java offers some Immutable objects for instance java.lang.String, java.lang.Integer, java.lang.Float, java.math.BigDecimal.
Immutable objects make generally a good use in concurrent programming. The reliability is a key aspect in concurrent programming, so that corrupted data sets and objects may cause unwanted behaviors in applications.

Pros:
-Reliable and Atomic Data: The given data during the initialization of the immutable object is always the same, thus the data set is ensured and atomic. Furthermore, An Immutable object can be a good candidate to be the Key in Map collection,
-Thread Safety/Concurrency: The content of an immutable object is valid and no method may cause an alteration of the state thus it is thread safe,
-Garbage Collection: The garbage collectors can easily identify and make decisions on immutable objects,

Cons:
-Allocating lots of new objects may cause to increase the memory allocation for modifications. This can be somehow manageable while employing a good model of java memory management.

Rules to define an Immutable Object

1. Mark the designated immutable class as final; this will disallow the class to be subclasses or its methods to be overridden,
2. Mark all the fields with the final keyword and package access as private, this way fields will not be discoverable for other classes, as well as the values of fields will be forced to be initially set,
3. Mark the no arg constructor as private thus; creation of an empty valued object will be prevented,
4. Provide only one constructor and mark it as public to force callers to initialize all the fields,
5. Elimination of any methods that may change the state known as Setter Methods,
6. Last of all in case of having a mutable class as field member;
a. Mark it as final, so that its value can be assigned once only,
b. Disallow to have methods that will change the object state,
c. Perform to clone of the object not the object reference via getter methods, thus the alteration will be prevented.

Sample Immutable Object

import java.util.Collections;
import java.util.Date;
import java.util.List;

//Rule #1
public final class Student {
    /**
     * Immutable Object Field Declarations
     */
  //Rule #2
    private final String name;
    private final String lastName;
  //Rule #6a
    private final Date birthDate;
    private final List<String> classes;

    /**
     * Immutable Object Constructor Declarations
     */
  //Rule #3
    private Student() {
        this(null, null, null, null);
    }

  //Rule #4
    public Student(String name, String lastName, Date birthDate, List<String> classes) {
        this.name = name;
        this.lastName = lastName;
        this.birthDate = birthDate;
        this.classes = classes;
    }
  
  //Rule #5 and #6b- No setter methods exist

    /**
     * Immutable Object Getter Method Declarations
     */
    public String getName() {
        return name;
    }

    public String getLastName() {
        return lastName;
    }

  // Rule #6c
    public Date getBirthDate() {
        return (Date) birthDate.clone();
    }

    public List getClasses() {
        return Collections.unmodifiableList(classes);
    }
}

 

JSF Input text placeholder

Reading Time: 1 minute

In the Tag description add the pt entry and its corresponding web address

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:pt="http://xmlns.jcp.org/jsf/passthrough">

in the input text declaration

<h:inputText styleClass="form-control" 
pt:placeholder="Enter Search Value" required="true"
requiredMessage="Please enter search value"
value="#{orderController.keyword}" id="keywordSearch"/>

Installing External Jars to Local Maven Repository

Reading Time: 1 minute

Central Maven repository has a large variety of libraries https://mvnrepository.com however there are times that we may be in need of installing such 3rd party jars that are not offered in the central in mavenized projects. This command will allow you to install such jars to your local M2 folder. You need to make sure that if multiple developers are working on the project that experiences this situation, the participants must also carry out the same procedure.

The Command

[bash lang=”bash” smarttabs=”true” tabsize=”4″ wraplines=”true”]mvn install:install-file -Dfile={FILELOCATION}
-DgroupId=GROUPID/KNOWNASPACKAGENAME -DartifactId=ARTIFACTID
-Dversion=VERSION -Dpackaging=PACKAGINGTYLE[/bash]

Example Command

[bash smarttabs=”true” tabsize=”4″ wraplines=”true”]mvn install:install-file -Dfile=C:\myjar1-0.jar
-DgroupId=com.tugrulaslan -DartifactId=MyJar
-Dversion=1.0 -Dpackaging=jar[/bash]

Usage in pom.xml

<dependency>
<groupId>com.tugrulaslan</groupId>
<artifactId>MyJar</artifactId>
<version>1.0</version>
</dependency>

External Links
https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

Resetting ID Sequence in PostgreSQL

Reading Time: 1 minute
-- Latest Inserted ID
SELECT MAX(IDFIELD) FROM TABLENAME;

-- The id that will be assigned to the upcoming data tulip.
-- The result shoult be Latest ID + 1
SELECT nextval('TABLENAME_ID_SEQ');

BEGIN;
LOCK TABLE TABLENAME IN EXCLUSIVE MODE;
SELECT setval('TABLENAME_ID_SEQ', COALESCE((SELECT MAX(IDFIELD)+1 FROM TABLENAME), 1), false);
COMMIT;

 

Proxy Design Pattern and Proxy Objects

Reading Time: 5 minutes

Proxy Design Pattern

This pattern is listed as a Structural pattern in the tree of Design Patterns by GoF. It is more focused on intercepting and delegating client request.

Proxy Objects

Proxy objects are not a separate concept of the Proxy Design pattern, but the outcome of it. I am separately handling this because it eases to understand the case.  In the context Proxy Objects are known as the replica of the class they wrap, they are either created statically or dynamically.

Proxy objects do not modify the original class that they wrap, but apply some logic and call the original method in the proxy’s handler method. Clients first access to the Proxy Objects, it will intercept the requests and delegate the request only when required to the actual object.

The usage of proxy design pattern offers numerous advantages;

  • Access Control and limitation to the real objects. In a situation where the direct access to an enormous file or a remote connection might be expensive, thus Proxies will aid this issue by using lazy loading,
  • Providing  data caching, security, package access functionalities,
  • Proxy objects save the amount of memory used and have a very low memory footprint of the real object. For example in RMI, clients are concerned as Stubs that only make calls to the remote methods. So clients have smaller object footprints.

Feasible scenarios of the proxy pattern

1.Virtual Proxy: This is a situation where the creation of the real object is expensive like big file/network resources,

2.Protection Proxy: In this scenario proxy object acts as a security point where the access rights of the client to the real object are checked.

3.Remote Proxy: A local surrogate object of remote proxy object that resides in a different address space. The method calls on the local surrogate object results in the remote object. This situation is visible in Remote Method Invocation.

Example Class

Purpose

In this example, we will be simulating two concepts;
1.Security: Unauthorized access must be banned to the direct access to the real object,
2.Access to Object: The access to the real object will be monitored, we imagine the txt file is big, thus instantiation will be handled by the proxy for low memory usage.

Code Snippet

enum AccessRight {
    ADMIN, REGULAR, ANONYMOUS;
}

interface MyFile {
    void readFile();
}

class ActualFile implements MyFile {

    private final String fileName;

    public ActualFile(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void readFile() {
        System.out.println("Invoked class: " + this.getClass());
        System.out.println("Reading file: " + fileName + "\n");
    }
}

class ProxyFile implements MyFile {

    private ActualFile actualFile = null;
    private final String fileName;
    private final AccessRight accessRight;

    public ProxyFile(String fileName, AccessRight accessRight) {
        this.fileName = fileName;
        this.accessRight = accessRight;
    }

    @Override
    public void readFile() {
        System.out.println("Invoked class: " + this.getClass());
        //Checking the access rights
        if (accessRight == AccessRight.ADMIN) {
            if (actualFile == null) {
                actualFile = new ActualFile(fileName);
                System.out.println("instantiating the " + actualFile.getClass() + " class");
                actualFile.readFile();
            } else {
                System.out.println("returning the existing " + actualFile.getClass() + " class, no instantiation");
                actualFile.readFile();
            }
        } else {
            System.err.println("You have insufficient access to this class");
            return;
        }
    }
}

public class SampleFileReader {
    public static void main(String[] args) {
        MyFile regularUser = new ProxyFile("userdata.txt", AccessRight.REGULAR);
        MyFile adminUser = new ProxyFile("userdata.txt", AccessRight.ADMIN);

        regularUser.readFile();

        adminUser.readFile();
        adminUser.readFile();
    }
}

Explanation

Console Output:
Invoked class: class ProxyFile
You have insufficient access to this class
Invoked class: class ProxyFile
instantiating the class ActualFile class
Invoked class: class ActualFile
Reading file: userdata.txt

Invoked class: class ProxyFile
returning the existing class ActualFile class, no instantiation
Invoked class: class ActualFile
Reading file: userdata.txt

Ways of Creating Proxy Objects

a)Static Proxy: The programmer is responsible of creating a proxy object for every class,
b)Dynamic Proxy: Java is responsible of creating proxy objects dynamically that is natively achieved via reflection since JDK 1.3 or 3rd party libraries.

Purpose

We will be creating a Dynamic proxy for our audit logger that will wrap file reader class. It is assumed that audit logger is generic and must be called before the file reading is being performed

Code Snippet

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface MyFile {
    void readFile(boolean readOnly);
}

class ActualFile implements MyFile {

    private final String fileName;

    public ActualFile(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void readFile(boolean readOnly) {
        System.out.println("Invoked class: " + this.getClass());
        System.out.println("Reading file: " + fileName + "\n");
    }
}

class AuditLogger implements InvocationHandler {

    private Object targetActualObject;

    public AuditLogger(Object targetActualObject) {
        this.targetActualObject = targetActualObject;
    }

    public Object getTargetActualObject() {
        return targetActualObject;
    }

    public void setTargetActualObject(Object targetActualObject) {
        this.targetActualObject = targetActualObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("in " + this.getClass());
        System.out.println("====Proxied Class Information====");
        System.out.println("1. Proxied class: " + proxy.getClass());
        System.out.println("2. Invoked method on the proxied class: " + method.getName());
        System.out.println("3. Passed arguments on the method of the proxied class: " + args.toString());
        System.out.println("=================================");
        Object object = method.invoke(targetActualObject, args);
        return object;
    }
}

public class SampleFileReaderInvocationHandler {
    public static void main(String[] args) {
        ActualFile myFile = new ActualFile("userdata.txt");
        //myFile.getClass().getInterfaces() can also be replaced with new Class[]{MyFile.class}
        MyFile proxyObject = (MyFile) Proxy.newProxyInstance(SampleFileReaderInvocationHandler.class.getClassLoader(), myFile.getClass().getInterfaces(), new AuditLogger(myFile));
        proxyObject.readFile(true);
    }
}

Explanation

Console Output:
in class AuditLogger
====Proxied Class Information====
1. Proxied class: class $Proxy0
2. Invoked method on the proxied class: readFile
3. Passed arguments on the method of the proxied class: [Ljava.lang.Object;@3e34a1fc
=================================
Invoked class: class ActualFile
Reading file: userdata.txt

1.the newProxyInstance method of the Proxy object will dynamically generate a class which will implement the given interfaces as the second method argument.
2.then the proxied object will call the method invoke, the second parameter Method in the invoke method will refer to the designated method which is “readFile()” on the base class “ActualFile”

Dynamic Proxies at a glance

Dynamic proxies are created during run-time, a bit different than the proxy pattern and it makes use of byte code manipulation, the reflection class and compiling the Java code generated dynamically.
Furthermore, there are levels of the run-time code manipulation;
1.Low Level: This is the era of machine instruction’s level using such tools as ASM,
2.High Level: Briefly this is the Byte code. Having a new class not available as a byte code, but there will be a necessity of byte code generation in run-time and the class loader will load this byte code
working on Java classes only such tools as CGlib, AspectJ, ByteBuddy, Javassist

**Byte code: It is the Java program’s outcome after the successful compilation with the files extension of .class. This is where Java promise’s comes in cross-platform play “Write once, run anywhere”.
The bytecode is processed by JVM instead of the CPU. Still the compiled java classes are not fully compiled rather they remain as intermediate codes that have to be executed and interpreted by JVM.

**ClassLoader: Java ClassLoaders are used to load a compiled classes/bytecodes upon the request in run-time into the JVM and memory.

The purpose of dynamic proxying differs in such situtaions for example transactions, AOP, dynamic object mocking for unit testing etc.
It has been always on the scene and part of our day-to-day software development like Hibernate lazy loading entities, Spring AOP etc.

Elements of JDK Dynamic Proxies;

-java.lang.reflect.Proxy: The class enables to create a dynamic proxy for the passed interface,
-java.lang.reflect.InvocationHandler: The interface that is implemented by the Custom class where the actions are taken every time the application invokes a method on the proxy. Each Proxy class is associated with an InvocationHandler interface.

JSF File Download

Reading Time: 1 minute
<h:commandLink action="#{logController.downloadMessage}">
                                    <h:outputText
                                            styleClass="fa fa-fw fa-download"/>
                                    <f:setPropertyActionListener value="#{log}"
                                                                 target="#{logController.selectedLog}"/>
                                </h:commandLink>
public void downloadMessage() throws IOException {
        logger.info("downloading the log file");
        File file = new File(searchKeyword + "_log.txt");
        FileUtils.writeStringToFile(file, selectedLog.getMessageContent(), Charset.defaultCharset());
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        response.setContentLength((int) file.length());
        FileInputStream input = null;
        try {
            int i = 0;
            input = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            while ((i = input.read(buffer)) != -1) {
                response.getOutputStream().write(buffer);
                response.getOutputStream().flush();
            }
            facesContext.responseComplete();
            facesContext.renderResponse();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

 

d

JSF Primefaces Indicator

Reading Time: 1 minute

This example will show how to show a loader indicator while data is being fetch from the server.

<h:panelGrid columns="1" id="searchPanelGrid">
                        <h:panelGroup>
                            <p:inputText id="employeeId" placeholder="Employee Id" required="true"
                                         requiredMessage="Employee Id is required"
                                         value="#{createAdminController.employeeId}"/>
                            <p:commandButton value="Search in VCN" update="ldapPanel @form"
                                             actionListener="#{createAdminController.searchInVCN}" id="searchButton"/>
                        </h:panelGroup>
                    </h:panelGrid>
                    <p:blockUI block="searchPanelGrid" trigger="searchButton">
                        <h:graphicImage library="images" name="loader.gif"/>
                    </p:blockUI>

 

https://www.primefaces.org/showcase/ui/misc/blockUI.xhtml

http://ajaxload.info/

https://answers.axonivy.com/questions/14/how-to-create-a-loading-indicator-in-a-html-user-dialog/15

JSF Return Hostname and App name

Reading Time: 1 minute
private static HttpServletRequest request = (HttpServletRequest) FacesContext
            .getCurrentInstance().getExternalContext().getRequest();
    static Logger logger = LoggerFactory.getLogger(JSFUtils.class);

    public static String getServerHost() {
        return "http://" + request.getServerName() + ":" + request.getServerPort();
    }

    public static String getServerHostWithAppName(){
        String url = null;
        try {
            url =  new URL(request.getScheme(),
                    request.getServerName(),
                    request.getServerPort(),
                    request.getContextPath()).toString();
        } catch (MalformedURLException e) {
           logger.error(e.toString());
        }
        return url;
    }