Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, March 4, 2018

Apache Tika Tutorial

Apache Tika is a powerful library to detect and extract text and metadata from thousands of file formats. This is very useful when you are more interested in the content of the file and building your logic on top of it.

Let's see a simple code in terms of how to use Tika

Tuesday, February 27, 2018

Paging and Sorting using Spring Boot

Picture Credit : Pixabay


Please follow Rest API Server to see the big picture and GitHub repo details.

Paging and Sorting is an important use case for any application. Any web or mobile frontend, a listing will usually need such a capability.

To support Paging and sorting in a Spring boot application, we need to do the following.

The Spring data repository interface

Saturday, February 17, 2018

Swagger 2 Support for Rest API Documentation

Please follow Rest API Server to see the big picture and GitHub repo details.

Swagger 2 helps in building the documentation for Rest API's. Springfox provides a suite of libraries to support this. To support, Rest API documentation in Spring boot, follow the steps below

Add to Gradle dependencies

compile('io.springfox:springfox-swagger2:2.7.0')
compile('io.springfox:springfox-swagger-ui:2.7.0')

The Swagger dependency helps in documenting the Rest API. The second dependency helps in providing a UI to present the set of API's on browser.

Now define the configuration bean

Tuesday, February 13, 2018

Rest based API server

Photo credit: Pixabay.com
Rest based API servers are very common these days. This has also led to the logical separation of front-end and back-end. New front-end techniques like Single page applications nicely fit with these concepts and also is a logical separation of ownership. Backend deals with providing the information in the form of API and front-end deals with presenting them in an appropriate way. This is also true for mobile applications that connect to the backend via Rest-based API's.

Monday, June 6, 2016

Streaming data from Result Set

This example shows a way to stream the database records in a JSON format. This post is done against postgres db and a table is assumed. However you can point to any table structure and db after doing required adjustments.


public class StreamingService {

  public void handleRequest(String sql, OutputStream op) throws IOException 
{
   //Initialize the driver
   try {
 Class.forName("org.postgresql.Driver");
   } catch (Exception e) {

   }

Tuesday, October 27, 2015

Java Simple Serial Connector (jSSC)

Java Simple Serial Connector (jSSC) is a simple library for working with serial ports. This is a good replacement to rxtx library which is not in active development now. Though I am not sure how much jSSC is in active development as I could see in maven a jar from Jan 2014. I would also recommend reading Jim Connor's blog about the state of communications API.

Coming to jSSC library, I will show a simple program to show the list of ports. 

Thursday, July 23, 2015

Cors Filter in Tomcat

CORS stands for Cross Origin Resource Sharing. This is a way to handle Cross domain requests. CORS as a concept is supported by W3C consortium. It is enabled on server side by putting Access-Control-* headers.

The origin header is put by clients side browsers and by enabling CORS we can ask the server to honour the request.

Tomcat supports CORS filter which can be enabled by hooking the filter in web.xml. A minimalist configuration is

Sunday, May 3, 2015

Invoking web services using Restlet

Restslet is a good framework to invoke rest based web services. Let's see through a simple program how to write a client to invoke Rest based webservices.

First  maven dependency

<repositories>
<repository>
<id>maven-restlet</id>
<name>Restlet repository</name>
<url>http://maven.restlet.com</url>
</repository>
</repositories>
<properties>
<restlet-version>2.3.1</restlet-version>
</properties>

Monday, April 27, 2015

Populating Java object in a generic way using reflection

There is a need for reading data from text files/excel files and populate them into objects. Below is a way to handle such population of object in a generic way. This mechanism only works for primitive type. The user defined types need to be handled in the application specific way. The code sample uses reflection to achieve this

//Pass the object that needs to be populated with a map of key 
//value pair. The key is the field name and the value is the value.
//The map can be built by reading the input data. void buildObject(Object obj, Map<String,String> mapOfValues) throws InstantiationException, IllegalAccessException{

Wednesday, April 1, 2015

Support for JDK8 types in Spring using Jackson

Spring has introduced RestController to handle rest based services. These controllers help in providing JSON based webservices using Jackson.  A typical REstcontroller based service looks like

@RestController
public class UserRestController{

@RequestMapping(value= "/user/{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable Long userId){
    User user = userService.getUser(userId);
    return user;
  }
}

Monday, March 16, 2015

Session replication in Tomcat

For HA solution we want to replicate the sessions among a cluster of Tomcat. In this post, we will see a simple way of replicating session. This is not load balancing as load balancing is done by putting a load balancer in front of cluster. I will show taking an example of two Tomcat. Let's call them TomcatA and TomcatB. Also we will have same war deployed on both the Tomcat. I have tried this same machine (Ubuntu 1204)  running two independent instances of Tomcat. I have to change the ports of one of the tomcat so they do not conflict with each other.

First is to tell the web application that it is distributable. For that go to web.xml and put the following tag

Wednesday, December 31, 2014

Apache FOP Tutorial Part 3

<<< Part 2 <<<                                                                                                          

Now let's setup a Java project. If you are using Maven than have the following dependencies in your pom.xml filr

<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>1.1</version>
</dependency>

Tuesday, December 30, 2014

Apache FOP Tutorial Part 2

<<< Part 1 <<<                                                                                                                >>> Part 3 >>>

Let's now write a XSL stylesheet which will convert the data XML into a XSL FO tree. The XSL stylesheet looks as follows. This basically tells about how the data layout will happen.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.1"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"       
        xmlns:fo="http://www.w3.org/1999/XSL/Format"
exclude-result-prefixes="fo">
<xsl:output method="xml" version="1.0" omit-xml-declaration="no"
indent="yes" />

Monday, December 29, 2014

Apache FOP Tutorial Part 1

FOP stands for Formatting Object processor. It's a java library which can read a formatting object (FO) tree and output the results in different formats. The output format supported are:
  • PDF
  • PS
  • PCL
  • AFP
  • XML
  • Print
  • AWT
  • PNG
And to some extent RTF and TXT. PDF is the primary output format supported by Apache FOP. Apache FOP is an alternative to iText for generating different formats.

Getting a File reference from Classpath

Sometime we need to get a file handle to a file sitting in classpath. This could be a configuration file or a properties file. To do that following code can be used to fetch the file handle

public class ReadingFileFromClasspath {

public static void main(String args[]) throws URISyntaxException     {
// Get the URL from the classpath to the file. 
 //Note the leading /
 //Assumes a.txt file at the given location
URL url = ReadingFileFromClasspath.class
.getResource("/com/lalit/javaExamples/files/a.txt");
System.out.println("URL is: " + url);

Thursday, October 23, 2014

Semaphore in Java Threading

In Java, when we have to lock a resource, synchronize keyword is used. In recent versions, we can use ReentrantLocks. However with synchronize of ReentrantLocks approach, it's a binary approach. We either get the lock to resource we do not get it. What to do when we have more than one resources and want to allocate them till they exhaust. For example, let's say there are three ATM machines and we want to server the queue of users wanting to withdraw money. Locking a ATM machine will only allow one user to access it in the synchronize way. The other way is to define three ATM machines and let each be handled separately.

Thursday, October 9, 2014

Handling Symbolic Links in Tomcat in Linux

Tomcat by default does not allows files to be accessed via symbolic links or symlinks. For example 
you have an application context foo. The chance is you will have a foo directory sitting in webapps 
which contains all the things about the application. However you want to have access to a report.pdf 
file generated in other part of system, let's say at /etc/reports/report.pdf. The file is generated with some frequency so you would like to put a symblolic link to the generated file. The symbolic link can be given by

ln -s report.pdf /etc/reports/report.pdf

By default, Tomcat does not allows linking to the symbolic links. To achieve that you neeed to change the context.xml file at <Tomcat Installation Directory>/conf/context.xml

Friday, September 19, 2014

Handling Tomcat Catalina logs with logrotate

Tomcat by default logs on catalina.out file. Tomcat does not have log4j files where we can specify the various parameters to rotate the logs. If left unattended, this can lead to catalina files becoming huge. The big size catalina log files results in
  • Disk space getting chocked
  • Application become slower as when they have to log they have to deal with a large file to work with,
To handle proper rotation of catalina log file, in Linux we can use the logrotate capability. If you

Tuesday, September 16, 2014

Dynamic Proxies in Java

Dynamic proxies in Java is a way to provide an implementation to an interface method at runtime. Proxies are used extensively by frameworks like Hibernate to provide behaviors at runtime.

Creating a Proxy 

First let's define an interface for which we will create a Proxy object. Only interfaces can be proxied. IF you want to proxy a class than you will need to use cglib

public interface InterfaceToProxy {

    public void callMe(String arg1, Integer arg2);
    
}

The behaviour is provided by a concrete implementation of InvocationHandler interface

Tuesday, September 9, 2014

Ehcache Tutorial

Ehcache is caching framework in Java and is one of the most popular one. Ehcache is also used by Hibernate as second level cache mechanism. In this post, we will see how a basic Ehcache can be created and used in your application. 

Caches are essentially a key value map and helps in speeding up the application. For example, if you know that certain data does not changes in database and is frequently accessed, you might just want to load that data upfront in a cache in memory so that the access is faster and will avoid a database lookup. 

One thing you might want to be careful with usage of cache is the design of system should be such