Home | Tutorials | Smart-Cloud | Smart-EIS | License | FAQ | Contact

The Util API contains common utility classes and methods that most of the time requires single call to achieve its goal.

General

To use smart-cloud-util components, create Maven project with the pom such as the following example:

<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>
	<groupId>com.jalalkiswani</groupId>
	<version>4.0.4</version>
	<artifactId>smart-cloud-util-examples</artifactId>
	<dependencies>
		<dependency>
			<groupId>com.jalalkiswani</groupId>
			<artifactId>smart-cloud-util</artifactId>
			<version>4.0.8</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Logging

This section includes the logging description in the framework.

Always consider adding logging to classes that could require debugging or monitoring.

Basic Usage

You can use logging by

public class YourClass{
	JKLogger logger=JKLoggerFactory.getLogger(getClass());
	...

	public void method(String param1){
		logger.info("Calling method1() with param {}",param1);
		....
		...
		logger.debug("End of method1()");
	}

Note that the "{}" braces is used as placeholders for variables, and they are served by order

Recommendations

It is recommended to use logging as follows:

  • Public method: logger.info(); only once on every method

  • Non-public methods: logger.debug()

  • Most of the time you will not need to use logger.error() since it will be used internally by the framework in case of exceptions or failure.

  • It could be a good idea to have logger.debug at the end of each public methods for later performance tuning.

Logging Config File

A default logging configuration as available out of the box in the framework, and includes the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Check full configurations documentation at: http://logback.qos.ch/manual/configuration.html -->
<configuration debug="false" scan="true" scanPeriod="60 seconds" packagingData="true">
	<!-- <shutdownHook/> -->
	<statusListener class="ch.qos.logback.core.status.NopStatusListener" />
	<contextName>Smart-Cloud</contextName>
	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<Pattern>
				%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
			</Pattern>
		</layout>
	</appender>
	<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>logs/jk.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
			<!-- rollover daily -->
			<fileNamePattern>logs/jk-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
			<!-- each file should be at most 100MB, keep 30 days worth of history, but at most 10GB -->
			<maxFileSize>100MB</maxFileSize>
			<maxHistory>30</maxHistory>
			<totalSizeCap>10GB</totalSizeCap>
		</rollingPolicy>
		<encoder>
			<pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern>
		</encoder>
	</appender>
	<!-- Levels are: TRACE, DEBUG, INFO, WARN, info, ALL or OFF -->
	<logger name="com.jk" level="info" />
	<logger name="org.springframework" level="info" />
	<logger name="org.springframework.security.web" level="info" />
	<logger name="com.jk.util.factory.spring" level="info" />
	<logger name="org.hibernate" level="info" />
	<logger name="log.org.jboss.logging" level="info" />
	<logger name="javax.enterprise" level="info" />
	<logger name="javax.faces" level="info" />
	<logger name="org.primefaces" level="info" />
	<logger name="com.sun.faces" level="info" />
	<logger name="org.apache.catalina" level="info" />
	<logger name="org.apache" level="info" />
	<logger name="com.mchange" level="info" />
	<logger name="org.omnifaces" level="info" />
	<root level="warn">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
	</root>
</configuration>

For having custom logging configuration, create src/main/resources/logback.xml file which shall contain your custom configurations.

For unit testing, the logback file name should be named logback-test.xml.

Exception Handling

Exception handling in Smart-Cloud framework is implemented based on my article Exception Handling in Real-Life Java Applications published on DZone.com.

Exception Handing Bullet Points:

  1. Always have only one catch statement

  2. Never catch Runtime exception

  3. In the catch statement just call JK.handle(e); the framework will handle the rest.

  4. If you are handling an exception inside method that should return value, it is safe to return null, check the following example.

Example 1:

package com.app;

import com.jk.util.JK;

public class ExceptionExample1 {
	public static void main(String[] args) {
		//Throw nullpointer exception and handle with default handler, which log the error then through runtime exception
		try {
			String name = null;
			name.length();
		} catch (Exception e) {
			JK.handle(e);
		}
	}
}

Custom Exceptions Handling

  1. Create Custom Handler

package com.app;

import javax.swing.JOptionPane;

import com.jk.util.exceptions.handler.ExceptionHandler;
import com.jk.util.exceptions.handler.JKExceptionHandler;

@ExceptionHandler
public class ArrayIndexExceptionHandler implements JKExceptionHandler<ArrayIndexOutOfBoundsException> {

	@Override
	public void handle(ArrayIndexOutOfBoundsException throwable, boolean throwRuntimeException) {
		JOptionPane.showMessageDialog(null, "My ArrayIndexException Handler");
	}

}
  1. Register Handler:

package com.app;

import com.jk.util.JK;
import com.jk.util.exceptions.handler.JKExceptionHandlerFactory;

public class ExceptionExample2 {
	public static void main(String[] args) {
		JKExceptionHandlerFactory.getInstance().registerHandlers("com.app");
		//Throw nullpointer exception and handle with custom handler, which show the message in JOptionPane
		try {
			int arr[]=new int[0];
			int x=arr[1];
		} catch (Exception e) {
			JK.handle(e);
		}
	}
}

For more details, check the DZone article at: https://dzone.com/articles/exception-handling-in-real-life-applications

Caching

Caching using Java, a Simple Tutorial

Last Updated: March 12, 2021

Steps:

  1. Create Maven project with the following pom.xml:

<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>
	<groupId>com.jalalkiswani</groupId>
	<version>4.0.4</version>
	<artifactId>smart-cloud-util-examples</artifactId>
	<dependencies>
		<dependency>
			<groupId>com.jalalkiswani</groupId>
			<artifactId>smart-cloud-util</artifactId>
			<version>4.0.8</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

If you are using Eclipse, be sure to refresh your project (select your project→ right click→ Maven→ Update Project)

  1. Create Main class with the following contents:

package com.app.cache;

import com.jk.util.JK;
import com.jk.util.cache.JKCacheFactory;
import com.jk.util.cache.JKCacheManager;

public class JKCacheExample {
	public static void main(String[] args) {
		//Cache value
		JKCacheManager cm = JKCacheFactory.getCacheManager();
		cm.cache("username", "Jalal");

		//Retrieve value
		String value = cm.get("username", String.class);
		JK.print(value);

		//Remove value
		cm.remove("username", String.class);

		String value2 = cm.get("username", String.class);
		JK.print(value2);//null

	}
}

Thats it, now run your App class, and you should see something line this:

cache

Full example source-code can be found at https://github.com/smartapi-com/smart-cloud-util

Code Refactoring

  • JK.fixMe(); to remember back to code block that need to be fixed later.

  • JK.implementMe(); to throw an exception when called reminding you to fix ASAP.

Validation

  • JKValidationUtil

    1. isBoolean

    2. isDouble

    3. isEmpty

    4. isFloat

    5. isInt

    6. isInteger.

    7. isUpperCase

  • JK.validateNull("Variable Name", variable);

Conversion

  • JKConversionUtil

    1. toInt

    2. toDouble

    3. toDate

    4. toLong

    5. toBoolean

Remote Reflection

Remote Reflection is a Java API which make it easier to call remote methods on remote JVM in very simple way without the need for any special configurations or common contract between client and server.

Test Service

package com.app.server;

public class TestService {
	public String hello(String name) {
		return "Hello " + name + " from server";
	}
}

Server

In the server application(the application which you want to expose its method remotely) , add the following after at the end of you main method:

package com.app.server;

import com.jk.util.reflection.server.ReflectionServer;

public class ServiceServer {

	public static void main(String[] args) {
		int port=7125;
		ReflectionServer server = new ReflectionServer(port);
		server.start();
	}
}

Thats it , now you can expose any method inside this application VM to your application client.

Client

In the client application(the application which should consume the remote method):

package com.app.client;

import com.jk.util.reflection.client.ReflectionClient;
import com.jk.util.reflection.common.MethodCallInfo;

public class ServiceClient {
	public static void main(String[] args) {
		ReflectionClient client=new ReflectionClient("localhost", 7125);
		MethodCallInfo info=new  MethodCallInfo("com.app.server.TestService", "hello", "Jalal");
		client.callMethod(info);

		String result = (String) info.getResult();
		System.out.println(result);
	}
}

Git Integration

JKGitWrapper is a full wrapper that enables full communication with a Git repository.

Full example can be found below.

	String url = "Remote Repository URL";
	String userName = "UserName";
	String password = "Password";
	String localPath = "local-source-path";

	JKGitWrapper gw = new JKGitWrapper();

	gw.url(url).user(userName).password(password).localPath(localPath);

	Git git = gw.cloneRepo();

	JKIOUtil.createDirectory(gw.getLocalPath(), "dir1");
	JKIOUtil.createDirectory(gw.getLocalPath(), "dir2");
	JKIOUtil.createDirectory(gw.getLocalPath(), "dir2/dir2-1");
	JKIOUtil.createDirectory(gw.getLocalPath(), "dir3");

	JKIOUtil.writeDataToFile("Hello from uncle Jalal0", new File(gw.getLocalPath(), "dir1/test.txt"));
	JKIOUtil.writeDataToFile("Hello from uncle Jalal1", new File(gw.getLocalPath(), "dir2/test.txt"));
	JKIOUtil.writeDataToFile("Hello from uncle Jalal2", new File(gw.getLocalPath(), "dir2/dir2-1/test.txt"));
	JKIOUtil.writeDataToFile("Hello from uncle Jalal3", new File(gw.getLocalPath(), "dir3/test.txt"));

	gw.add(git);
	gw.commit(git);
	gw.push(git);

Home | Tutorials | Smart-Cloud | Smart-EIS | License | FAQ | Contact