Blogs On Programming

Introduction to Data Structures

Introduction to Data Structures

by Vibrant Publishers on May 19, 2022
Data Structures define how the data is organized, efficiently stored in memory, retrieved and manipulated. Data has to be defined and implemented in any program. Data Structures segregate the data definition from its implementation. This introduces a concept called data encapsulation which improves code efficiency. Data Structures are used to store the relationship between the data. A simple example is to implement database and indexing data using the Data Structures.     Data Objects and Data Types: Data Structures allow basic operations such as traversing, inserting, deleting, updating, searching and sorting. These operations are backed up by data objects and data types concepts. You can compare data structure to the data definition, while an object is its implementation.   Data Objects : contain the actual information and can access the methods or information stored in the data structure. They can store, retrieve, or process the information in your program. Unless you garbage collect them at the end of the program, they continue to persist in the memory.   Data Types : define what type of data is stored in the variable. We can categorize them into primitive data types such as boolean, integer, float or character and complex data types such as an integer array.     Real-world applications: All complex solutions rely on Data Structures. We use them in many scenarios as described below:   Memory allocation:This process uses heap and stack concepts for storing and retrieving data from memory.     Business operations: Complexity of data makes it even more complex to represent them in a more meaningful way. Graphs, for example, can help resolve the issue giving more clarity and meaning to the data.   Others:Whether it is building operating systems, or database management, Data Structures are helpful. Most modern technologies such as artificial intelligence, data analytics, or numerical analysis also need Data Structures for proper storage and representation.     Types of Data Structures: We can categorize Data Structures into:   Linear Data Structures:Some data structures are sequentially stored for easy storage and management. Files, queues, lists, arrays and stack are some examples of linear data structures. Files can be stored and accessed sequentially. Arrays, linked lists, queues or stacks are accessed directly using the address pointers.Below are some representation of arrays, stacks, queues, and linked lists.     Arrays:     Queues and Stack:       Linked list:       Non-Linear Data Structures:When information doesn’t follow any specific storage pattern, but they are still related, non-linear data structures are used to manage them. Non-linear data structures are complicated and not easy to manage.   However, many real-time applications are complex and need non-linear data structures like trees and graphs.   Prepare for your DATA STRUCTURE AND ALGORITHMS INTERVIEW with our book Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 DATA STRUCTURE AND ALGORITHMS INTERVIEW Interview Questions and 77 Human Resources Questions crafted by Industry Experts and Interviewers from various interview panels. All our books are available in E-book as well as Paperback Format. Ensure your dream job now!        
Linked List Operations

Linked List Operations

by Vibrant Publishers on May 19, 2022
A linked list supports the following operations:   Traversal Insertion Deletion   All these operations are supported by single, double or circular linked lists. Before going into various operations the data structure supports, it is important to understand how to find the length of a linked list. Once the node pointer and count are initialized to 0, assign the head pointer to current. The list has to be iterated using a counter variable until the current is not NULL. Increment the counter on every traversal, then return the count.   A pseudo-code to find the node length is illustrated below:     getCount()   {     //initialize node     Node temp = head     Count =0     While (temp !=null)     {       //increment count and       Count = Count + 1       //move to next node       temp = temp.next     }     //length of the list     return Count   }   Let’s see the list operations in more detail.     A) Traversal: Initialize the linked list to make sure the pointer address is set to the first node. Loop until the pointer until the end of the list and access the value stored in each node. Make sure to read the address of the next node each time. Assign the next address to the pointer and loop until the end of the list.   A simple pseudo-code is shown below:     head = linkedList   while head !=null   {     var = head ->value       /***  Process in your desired way  ***/     Print var     Head = head ->next   }     B) Insertion: In a singly linked list the header points to the first node and the tail address will be null. When you create a new node, assign the previous node’s next address to the new node’s address and new node’s next address to null.     Doubly and circular linked lists work a similar way. The only difference addition is the node’s previous pointer. Once you add a new node to the list, follow the same steps above to assign the node’s next address. In addition to this, the new node’s previous address will have to be assigned to the old node’s address.     C) Deletion: Given a linked list, deletion of the last node is fairly simple. The next pointer of the second last one needs to be updated to null. As the pointer is lost, that node will be the last node. However, if you are deleting a middle node then, you must traverse through the node and replace the previous node’s next address to the deleted node’s next address.   A simple algorithm can be shown as below:     CurrentNode = head   curPos =1   //start from the 1st node   prevNode = currentNode   currentNode = currentNode -> Next   curPos ++   If currentNode != NULL   {     prevNode->Next = currentNode -> Next     Delete currentNode   } Get one step closer to your dream job!   Prepare for your programming interview with Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 technical interview questions on lists, queues, stacks, and algorithms and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
Data Structures for Sets

Data Structures for Sets

by Vibrant Publishers on May 19, 2022
A set is a group of unique, yet similar items related to each other where order doesn’t matter. For example, a set of balls as shown in the picture is a real-world example for a set.         Below represents a set of balls, but none of them are the same. We can also arrange them in any order. We cannot extend the set to add new items as they are finite.  ball={football,baseball,basketball,cricket ball, tennis ball}     How are sets implemented? Set is an abstract data type that uses List, an Associative array or Bit array for its implementation. We can implement a simple data representation of similar items using Linear list. However, if you are representing Boolean results like True or False, Bit array comes handy as it requires very less storage space. Hash tables and binary trees are used to depict search algorithms and Associative arrays are very useful in those scenarios.         A null set contains no elements. Null sets are used when we are not sure if the elements will be populated as a result of a runtime operation. The values are dynamically populated in a null set.     How are sets implemented? A set supports the following operations:   Subset: smaller set of the larger set. In the below example, A is a Subset of a larger portion B. A subset returns 1 if the first set has some elements which are a subset of B, else returns 0.   Here, A is a subset of B and includes A={4,2,1}   Union: returns a unique set of elements of both Set A and B. For example, pick all the musicians who play a band or who sing a chorus or who sing both and without including the duplicates.   Intersection: When you need a set of elements common to both sets, you can create an intersection. Below is a representation of intersection on sets A and B.         Types of sets: A Mutable Set: Sets can be mutable if you want to create them during runtime. Size of the set can be  dynamically defined and elements can be added or removed during runtime. You can create, or add, delete or check the capacity when working with a mutable set.   An Immutable Set: When you are sure of the set size and the elements, immutable sets are best. These are static, so you cannot alter the set. You can check the size if empty, build or read the element of the immutable set.   A Disjoint Set: This set is a collection of subsets that do not overlap with each other.       A very good way to represent these singleton sets is using a linked list. Elements can be added to the set by pointing to other sets. Undirected graphs are another way to use a disjoint set. Disjoint set supports find, union and subset operations.   A Sparse Set: This is similar to the Bit set with the only difference that the elements are indices of a larger array. As managing a very large array is a big hassle, sparse set lets you easily break them into multiple sets and reference the parent set.Below is an example of a sparse set.     When you use a sparse set, the entire set is split into multiple coarse-grained arrays and each array stores the indices. This makes search faster and simpler. A sparse set supports Union and intersection operations.     Get one step closer to your dream job! Prepare for your programming interview with Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 technical interview questions on lists, queues, stacks, and algorithms and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
Little Known Ways to Link Lists

Little Known Ways to Link Lists

by Vibrant Publishers on May 19, 2022
A linked list is a list of connected nodes. Each node stores the value and address of the next or the previous node. Since the address is stored in the node, linked lists can be dynamically allocated. Linked lists are used in implementing dynamic arrays, stacks, and queues. However, they consume extra memory for storing the address of the next node. These sequential lists are very cumbersome for traversing longer lists.     Array vs Linked List: Compared to an array, a linked list can be easily traversed if the list size is smaller. Unlike arrays linked list items cannot be randomly accessed. Lists store the address of the next node, hence consume more space.  Below picture shows how a linked list can store items anywhere and accessed by the address sequentially. The address can be used to locate the element. This makes insertion, deleting or updating operations in a linked list faster.     Arrays are stored in memory sequentially and accessed using the array index. Hence, arrays take a longer time for insertion, deleting or updating.       Arrays are stored in memory sequentially and accessed using the array index. Hence, arrays take a longer time for insertion, deleting or updating.     Types of Linked Lists: Linked lists are of 3 main types:   A Singly linked list:They contain a list of nodes that have a value and address to the next node. The last node’s address is always null. Below illustration shows that a singly linked list can traverse forward only.     Stacks, queues and dynamic arrays are some implementation areas where singly linked lists are used. They are best suited for smaller forward traversals and when the address to the element is unknown.     A Doubly linked list:A doubly linked list has 3 parts – node value, address to the next node and address to the previous node. The first node’s address to the previous element and the last node’s address to the next node will always be null. A doubly linked list can hence traverse both forward and backward.     We use a doubly linked list to navigate either forward or backward direction, when using an array or other data structures. However, both next and previous address needs to be stored in the node and hence consumes more memory.     A Circular linked list:When the last node’s address points to the first node, the linked list is called a circular linked list. A circular linked list can be singly or doubly linked.   Below is an example of a singly linked circular list.         A doubly linked circular linked list is just like the doubly linked list except that the last node’s next pointer stores the address of the first node and the first node’s previous pointer stores the address of the last node.     The operating system’s task scheduler, circular queues and multi-player games are great real-world examples of a circular linked list.     Get one step closer to your dream job!   Prepare for your programming interview with Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 technical interview questions on lists, queues, stacks, and algorithms and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
Basics of Stack Data Structure

Basics of Stack Data Structure

by Vibrant Publishers on May 19, 2022
Stack is an abstract, Linear Data Structure that follows Last-In-First-Out (LIFO) principle. All data operations are done at the top of the stack which means, the last item inserted is first accessible. Insertions in stack are called “PUSH” and deletions are termed as “POP”. Other abstract data types such as Array, Structure, Pointer, or Linked List are used to implement stack. It is most commonly used in the real-world scenarios such as a stack of books or a stack of coins.     Stack Operations: Initialize stack and de-initialize once done. In order to support these tasks, stack has to implement these basic operations:   Push:lets you store an item on the stack This operation checks if the stack is full and exits. If stack is not full, add the data and increment top to point to the next empty slot.     This pseudo code represents Stack push operation:     push(item)   {     If stack is full     {       exit     }     else     {       top= top +1       stack[top]=item     }   }   Pop:lets you access an item from the stack Pop operation checks if the stack is empty and exits for an empty stack. If the stack is not empty, we access the item at which top is pointing. The top position is decremented by 1.     Below pseudo-code shows a simple representation of pop:   pop(item)   {     If stack is empty     {       exit     }     else     {       item=stack[top]       top= top -1       return item     }   }   Peek:lets you read the top item of the stack without having to remove it   peek()   {     return stack[top]   }   isFull:It returns a Boolean and checks whether the stack is full before push operation. Below pseudo code checks if top is at the max. If it is, that means the stack is full.   bool isfull()   {     if(top == MAXSIZE)     return true;     else return false;   }   isEmpty:It returns a Boolean and checks if the stack is empty before pop operation.  We sometimes use an   array to implement stack and pointers to indicate top which is initialized to -1. So we check if the top is equal   to -1, that means the stack is empty.   bool isempty(){     if(top == -1)     return true;     else     return false;   }   Rotate:Rotates the top-most items in the stack.   Swap:This operation lets you exchange 2 top-most items in a swap. This is most suitable for implementing sort algorithms.     Get one step closer to your dream job!   Prepare for your programming interview with Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 technical interview questions on lists, queues, stacks, and algorithms and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
Know your Queue Data Structures in 60 seconds

Know your Queue Data Structures in 60 seconds

by Vibrant Publishers on May 19, 2022
A queue is a powerful Data Structure that controls the asynchronous flow of data through the buffering technique. Unlike Stack, a queue is used to insert data from one end and retrieve on the other.This abstract data structure follows the First In First Out(FIFO) concept where the data stored first is accessed first.  We can implement queues using Structures, Arrays, Linked-lists or Pointers. Queue uses 2 data pointers – head and tail for Enqueue and Dequeue operations     Applications: A ticketing system is a real-world example for the queue where the person first in the line is served first and the one at the end of the line is served last.   A queue is a special Data Structure efficiently used for buffering. This concept works similar to the print queue where the jobs buffered are printed based on the order of requests received. We can also use queues to prioritize interrupts to address based on their priority.  Another simple example of a queue system is the first-come-first-served calls answered in a call center.     Queue Operations: The life cycle of a queue involves initializing, adding items to the queue (enqueue), retrieving items from the queue (dequeue) and deleting the queue from memory. Learning Queue is incomplete without understanding the steps involved in Enqueue and Dequeue operations.         Enqueue:   Enqueue operation manipulates only the tail pointer and does not hinder the head pointer. We insert data in a queue with the following steps:   Check if the queue is empty  If the queue is not empty, stop the operation  If the queue is empty, increment the tail pointer to point to the next available space  Insert the data in the newly created space  Now that becomes the current tail element of the queue     Algorithm for Enqueue:     Enqueue(data)   {     if queue is empty   {     tail = tail +1     queue[tail] = data   }   else   exit   }     Dequeue:   Dequeue operation does not manipulate the tail pointer. Here, data is removed from the Queue with the following steps: Check if the queue is empty  If the queue is not empty, stop the operation If the queue is not empty, move to the head of the queue Remove the data and increment the head pointer to the next position Now that becomes the current head element of the queue     Algorithm for Dequeue:     Dequeue( ){     if queue is empty     exit     else{       head = head +1       queue[head] = data     }   }     Types of Queues: A simple queue is a linear queue. We insert data until the queue becomes full. Circular queue, commonly referred to as Ring buffer, is a linear queue where the head of the queue is  connected back to the tail. Data is enqueued in the head and dequeued from the tail         Get one step closer to your dream job!   Prepare for your programming interview with Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 technical interview questions on lists, queues, stacks, and algorithms and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
All You Need To Know About Arrays

All You Need To Know About Arrays

by Vibrant Publishers on May 19, 2022
An array is a fixed collection of items of the same data type represented by a single variable. We can access the sequential Data Structure item called ‘element’ using an array index. Arrays can be single dimensional or 2 dimensional with rows and columns.To reach node E we start from node A and move downwards, as deep as we can go. We will reach node C. Now, we backtrack to node B, to go downwards towards another adjacent vertex of B. In this way, we reach node E.       An array is used to implement other Data Structures such as Stacks, Queues and List.     How is an array represented? You can define integer arrays, string arrays or object arrays. Array size has to be defined when it is declared. This ensures memory is allocated based on the array size.   For example: int myarray[5];   We can initialize an array either during declaration or later.   For example: type myarray[size] = {values/elements}   Arrays can be declared in many ways depending on the programming language used. For example, string in C is represented by a character array. Here, we have declared and initialized a character array.   char charArray = {‘ H ’,’ E ’,’ L ’,’ L ’,’ O ’}.   We can declare an array of Strings in the following way:   String names[3] = {“John”,”Kelvin”,”Simmons”} Array index [0]        John Array index [1]        Kelvin Array index [2]        Simmons     Array Operations: An array supports the following basic operations:   Insertion – insert an array element at the index and ensure there is no overflow Deletion – delete an array element at the index Traverse – loops through and prints all the array elements sequentially Search – search by using an array index or by the value Update – update the array element of the index   Let’s see how each operation works.         Array Insertion and Traversal: You can insert one or more elements into an array, in the beginning, end or any index. Let’s see the steps of inserting an array element at index 3.   int arr[5]={10,9,8,6}  insert 7 at arr[3]   Start traversing from the last position and move to the next until you reach the 3rd position. Remember, arr[0] is the 1st element. We need to reach arr[3] which has value 6 in our example. Move arr[3] value to the right and insert 7 in arr[3].     Array deletion and Traversal: Deletion at the beginning and end of the array is straight forward. However, when you have to delete from the middle of the array, rearrange the element to occupy the space emptied.   Let’s take the same example as above and delete the element with value 8 which is arr[2].   Traverse through arr[3] and delete the value of arr[3]. This value now becomes null. Go to the next index arr[4] and move this element to the 3rd position. Stop the move operation if this is the end of the array.   The new array now has these elements: {10,9,6}  Array Search: We can search an array for a specific element using the index or value. When you traverse through an array in a loop iterators reference the element and help to move to the next position.   Below is a pseudo code to indicate the same :     for(iter=0;iter<n;iter++) {   if ( arr[iter]== item)   Return iter; }     Get one step closer to your dream job! Prepare for your programming interview with Data Structures & Algorithms Interview Questions You’ll Most Likely Be Asked. This book has a whopping 200 technical interview questions on lists, queues, stacks, and algorithms and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
Components required for JMS

Components required for JMS

by Vibrant Publishers on May 19, 2022
JMS refers to Java Messaging Service which allows the software developers to loosely couple applications. It has an API (Application Programming Interface) through which we can receive, send, read, and create enterprise system messages. JMS is a message oriented product which is quite expensive and complex. It provides an interface (Java) to write infrastructure code and allow solutions to be built easily and quickly.   Following are the main components of JMS: Administered: ObjectsDestinationConnectionFactory Connection Session Objects: MessageProducer, MessageConsumer, MessageListener, MessageSelector   The component relationship could be explained with the below diagram.   1) Administered Objects:   Following are called as the administered objects as they are created by the JMS provider administrator: Destination ConnectionFactory     Destination:   This object has the configuration information provided by JMS provider. This object is used by the Client to specify the destination for messages to be send and location to receive the messages.   There are 2 types of Interfaces Destination uses. They are: Queue – It belongs to PTP (Point To Point) model Topic – It belongs to pub/sub (Publish / Subscribe) model     Connection Factory:   This object has the connection configuration information (IP address) provided by JMS provider. The connection is obtained through the Java Naming Directory Interface (JNDI) which enables the client to create a connection and get connected to the JMS server.     2) Connection: This component provides the connection (physical) to the JMS server. The physical connection is obtained with the help of ConnectionFactory object which provides the instances of configuration details to connect to the JMS server.     3) Session: This component is responsible to receiving and sending messages, and for handling acknowledgements and managing transactions with the help of JMS objects.   4) Objects:   It refers to the JMS object which are maintained and created by the admin that are used by the JMS clients. The following objects are used to receive and create messages in JMS: MessageConsumer MessageProducer MessageSelector:  This is used to filter the message that does not meet the specified criteria. MessageListener:  This is used to process and receive messages asynchronously     MessageConsumer:   MessageConsumer is for receiving messages synchronously or asynchronously to a particular destination which is created by the session object.   In case of synchronous communication, the consumer calls the any one of the methods receive or receiveNoWait and in case of asynchronous communication, the client registers MessageListener and starts consumer.   Almost all the messages in Java Messaging Service are exchanged asynchronously between clients where the producer never receive acknowledgement from consumer.     MessageProducer: MessageProducer is for sending messages either via PTP or through pub/sub. In PTP (Point-To-Point) model, the destination is known as queue and in pub/sub model, the destination is known as topic.   In producer, we can set the delivery mode either as NON-PERSISTENT or PERSISTENT using the setDeliveryMode method. Non-Persistent has less overhead as the messages are not logged in the server or database.   We can also use the setPriority method to set the message priority. 0 indicates low priority and 9 indicates high priority. We can also use setTimeToLive method to mention the life time of the message in milliseconds.     MessageSelector:   MessageSelector belongs to String object which is used to filter the message that does not fit into the specified criteria.   The message selector can examine the header and compares an expression which is present in the String. The example for expression comprises of arithmetic operators, relational operators, string literals, and logical operators.     MessageListener:   To process messages asynchronously, we have to use instantiate the MessageListener interface. We have to perform the following steps to process and receive messages asynchronously: Create object which implements MessageListener interface and invoke the onMessage method Use setMessageListener method to register with the session object Use Connection object’s start method to start receiving messages.  
REST APIs and Implementations

REST APIs and Implementations

by Vibrant Publishers on Jan 01, 2022
Introduction Building a RESTful service is specific to every programming language. There are different libraries and implementations of REST in each programming language. In this post, we are going to look into the details of how Java language implements REST and how we can build RESTful applications in Java. Java and REST REST got into the Java world through the release of JavaEE 6. It included the JAX-RS API that is responsible for REST API creation using Java. JAX-RS follows the REST framework and the HATEOAS principle. The current version of JAX-RS is version 2.0. JAX-RS uses annotations for ease of development and deployment of web services. These annotations are part of the java package javax.ws.rs. The basic annotations provided by JAX-RS are: @Path @GET, @POST, @PUT, @DELETE, @HEAD @Produces @Consumes @PathParam JAX-RS Implementations There are many implementations of JAX-RS available in Java. They show minor variations in their ways of defining and using REST APIs. But the basic procedures remain the same in all of them. A few of those implementations are: Jersey: This is the reference implementation of JAX-RS from Sun Microsystems. This is one of the most widely used libraries for building RESTful services in Java. Spring REST: This REST library is part of the Spring web framework. If you are using the spring framework for building your application, making it restful is very easy. It follows an MVC architecture. RESTeasy: RESTeasy is developed by JBOSS and is part of their application server. This implementation has server-side caching and GZIP compression features. Apache CXF: This implementation of JAX-RS specification is by Apache. It is an open source library available for free download and modification. Restlet: This is again an open source implementation of JAX-RS 1.1 specification. It is a light-weight library that supports major media types and all REST specifications. Serialization Frameworks When we implement REST APIs depending on the request and response types, one would always need to use some kind of object serializers. The following are some of the popular serialization frameworks: JAXB It stands for “Java Architecture for XML Binding”. This library helps in the conversion of java objects into an XML data format and vice versa. One can find this API in the javax.xml.bind package. There are many implementations of JAXB in the form of annotations that can be used in java code for conversions. JACKSON Jackson is a JSON processor that is used widely in the Java world for converting Java objects into JSON document format and vice versa. This implementation is part of the Jersey library. Building a RESTful Application As you can see, there are many choices in the Java world for building a RESTful application. The libraries and implementations listed here can be used with any Java framework. It is our choice to go for a particular library based on our use case and technologies that we are adopting. General steps for building any RESTful services would be: Identify resources and build URIs Select or build representations. Identify method semantics. Select response codes. The below diagram shows a simple technology stack for a RESTful application.         Summary After the introduction of REST in JavaEE from version 6 onwards, a lot of implementations and libraries came into existence. The JAX-RS has got strict implementation principles and guidelines for building RESTful API services. As a java web services developer it is important to understand which library to use and how to build RESTful services adhering to the REST principles.  
Rest Resources, HTTP Methods and Status Codes

Rest Resources, HTTP Methods and Status Codes

by Vibrant Publishers on Dec 29, 2021
Introduction REST stands for REpresentational State Transfer. We use REST while doing web services programming to communicate between client and server. There are many concepts involved in the REST world that are required to know for building a RESTful service. We will have a look at some of those building blocks of RESTful service here. ResourcesEverything in REST is a resource. It can be a document, an image, a collection of objects, information stored in the database, etc. REST requires a Unique Resource Identifier (URI) associated with each resource for it to be accessible over the internet. URI is the endpoint of a given resource. The state of each resource is also an important factor while accessing it. The client-side can use the resource in the best possible way when it knows the type and state of the resource. So REST responses will have a machine-readable explanation about the resource. That is a resource representation. It can be the details of the resource, its format, size, etc. REST and HTTPWe saw resources can be of any type, but there are some rules in the REST world while interacting with resources. REST requests and responses use the HTTP protocol. There are specific HTTP message formats that REST clients have to follow while sending a request. The response from the server also will be in a certain message format that a REST client can decode.There are eight different message formats that HTTP has defined. The following are the commonly used four methods. GET: Get a representation of a given resource. DELETE: Destroy the specified resource. POST: Create a new resource, based on the given representation. PUT: Update the state of a given resource with the one described in the given representation. The main aspects of choosing these methods are because of its adherence to the REST specification (RFC 2616). The two main properties in RFC 2616 are safety and idempotency. Safety here means the ability of the client to make requests without altering the state of a given resource. Idempotency means the effect of doing an operation will be the same for single or multiple times. Request Response Structure Now we will see how these methods are used in an HTTP request and response in a RESTful way. A REST client library will create a REST API request in the following format: The API response, in turn, will have the following format:Following is a sample GET request:Method: GET URL: http://api.clothshop.com/shirtsWhich will provide the following response: HTTP/1.1 200 Content-Type: application/json { “id”: 10, “name”: “Lee Shirt”, “color”: “yellow”, “price”: “$30” }HTTP Status CodesWhenever we do a REST API request to the server, the server will return a response with an HTTP status code. Each status code will tell a brief about the response from the server. These status codes will be part of the HTTP header which the client will decode and understand. These are wrapped with HTML code and all HTML /HTML5 browsers are capable of understanding these HTTP codes. The following table summarizes the major status codes and their meaning. HTTP Status Codes Summary 200 OK. Request successful. 201 Resource Created. 204 No content found. 400 Bad Request. 401 Unauthorised. 404 Resource not found. 405 Method not allowed 500 Internal Server Error. Summary There are multiple building blocks in the REST framework that makes web services communication happen over the internet. HTTP protocol is one of the main blocks upon which the entire REST communication is built. While designing a REST API it is important to consider the nature of resources that we are planning to expose as APIs. Also it is important to know various HTTP methods and status codes that will help us in the process of accessing these resources at the client side.
JAX-RS Basics

JAX-RS Basics

by Vibrant Publishers on Dec 29, 2021
Introduction The implementation of REST framework in Java is done through JAX-RS API. It serves as the basic building block for RESTful services in Java. Let’s take a look at the basics of JAX-RS. JAX-RS JAX-RS (Java API for RESTful Web Services) is also part of the JSR, with a detailed specification definition. Starting with JAVA EE 6, this technology has been built, similar to RESTful WCF in .NET, that exposes the RESTful service by using some simple annotations in the conventional method.The current version of JAX-RS in use is version 2.0. The below-given diagram shows the features of this version. HTTP Methods and annotationsWe know that the REST APIs work through HTTP protocol. The following are the HTTP methods used in REST via annotations. @GET: Defines HTTP GET request method. @PUT: Defines HTTP PUT request method. @POST: Defines the HTTP POST request method. @DELETE: Defines HTTP DELETE request method. A basic GET requestLet’s see how a basic HTTP GET request is implemented using JAX-RS API using a simple ‘Hello World’ example.   @Path(“/”)       public class SampleWebService {         final String XMLNS_NAMESPACE = “http://localhost:8080/rest/service”;         final String ROOT_NODE = “root”;              @GET          @Path(“/json/hello”)          @Produces(MediaType.APPLICATION_JSON)          public JAXBElement<String> getHelloWorldJSON() {         JAXBElement<String> result = new JAXBElement<String>(new QName(“”, ROOT_NODE), String.class, sayHelloWorld());          return result;        }         ……….        }             private String sayHelloWorld() {        return “Hello, this is a sample JAX-RS API!”;       }     @GET indicates that the service can be accessed directly in the browser address bar (for the GET method in HTTP requests). @Path used here twice, the first on Class, the base address of service, and the second time on a method, representing the URL of a specific service method. @Produces defines the output type of method. Here we are opting for a JSON string format output.   We will also deploy the web.xml file in the root folder of the application.                                                                           Now this REST API can be accessed at the address http://localhost:8080/rest/service/json/hello This will return output in the HTML browser as {“root”: “Hello, this is a sample JAX-RS API!”}In this way, any resource at the server side is made available to the client through simple REST API calls over HTTP. Similarly, create, update and delete operations on a resource can be done at the server-side by calling corresponding REST API commands from the client-side. Content NegotiationWhile using REST APIs, we are sharing resources that are represented by multiple data types. JSON and XML are the two most popular content types that are commonly used. The JAX-RS annotations @Produces, @Consumes are used to specify the content format. As the name suggests, @Produces annotation specifies the type of content produced by a method. The @Consumes annotations specify the type of content that a method is expecting as input. For example, @Produces({“application/xml,application/json”})means the method will produce content in two MIME types, XML and JSON. One thing we should understand here is the differences between data and data format. Data can be anything and the data format is the representation of that data. Data transformations occur before or after transmission.  When there is an equal match with the request and response type, the server will return a 200 OK response or a 400 Bad Request if the data format is not matching with the MIME type that the server expects.  Now, let us say the client does not specify any content format, then in JAX-RS 2.0 there is a factor called ‘QS’ ie. ‘QUALITY FROM SERVER’. It can take value from 0 to 1. So in the above scenarios ‘qs’ factor instructs the server to choose a content type that is the default content format. If we consider, @Produces({“application/json qs=0.8; ,application/xml; qs=0.75”}),  it is clear that the server has to consider the JSON format. Request Matching Request matching is a process where the client API request is mapped to the corresponding method at the server-side. This is achieved using the @Path annotation. The value of the @Path annotation is an expression that indicates the relative URI. Consider the following example:  @Path(“/orders”) public class OrderResource {    @GET    public String getAllOrders() {        …    } } Here if you send an HTTP request of GET /orders to the server, that would dispatch to the getAllOrders() method. The JAX-RS has strict precedence and sorting rules for URI expressions matching. This is based on the ‘most specific match wins’ algorithm. You must also abide by the URL encoding rules that only allow alphabetic characters, numbers and some special characters only. Summary The JAX-RS library has specifications and rules that will help a developer to build web services in the RESTful way. In JAX-RS the importance of annotations and how HTTP methods are mapped using these annotations are important to understand. The request – response matching mechanism and specifying the content type while making a request are also important concepts in JAX-RS implementation. 
JAX-RS Response Handling

JAX-RS Response Handling

by bhagyashree kolge on Dec 22, 2021
Introduction The JAX-RS specification for building RESTful services gives clear directions for handling API responses. Some specific annotations and classes are available for this task. Let’s have a look at how the responses are handled at the server-side of JAX-RS web services. Building a JAX-RS ResponseBy default, JAX-RS supports response messages of common Java types. These responses can be either in plain text, XML or JSON format. JAX-RS provides javax.ws.rs.core.Response class for creating responses. The below code sample will produce a response in the plain-text format. @GET   @Path(“color”)   @Produces(TEXT_PLAIN)   public Response getTextileColor()   {     if (color) {       return Response.ok().build();     }     // return 404 Resource not found error.     return Response.status(Response.Status.NOT_FOUND).build();   } }   Normally a response will contain a resource that the client is requesting from the server. The resource representation in java must be marshaled and converted into the media type specified in the REST API request. A POJO [Plain Old Java Object] is converted into REST response format through the process as given below:Response EntityThe response entity is also referred to as ‘payload’ or ‘message body’. While using JAX-RS, response entities are mapped to and from java types by Entity Providers that implement the JAX-RS interface MessageBodyWriter.Message Body WriterThe JAX-RS Message Body Writer converts java types to a stream. There are three main methods in this class. They are isWritable(), getSize() and writeTo() which can be overridden while implementing our logic. Successful ResponsesSuccessful responses are sent along with corresponding HTTP codes. They range from 200 to 399. The JAX-RS response specifications are similar to that of HTTP specifications for GET, PUT, POST, DELETE methods. If an API request is successful and the response contains a message body, then the status code will be 200, ‘OK’. Otherwise, it will be a 204, ‘No Content’ message in the response status. Error ResponsesError response codes range from 400 to 599. These are used based on failure cases. By examining the error code that is returned to the client, we can understand the type of issue faced at the server-side. @Produces AnnotationThe @Produces annotation mentions the media types that a resource can produce and set back to the client. If no method can produce the resource in the specified media type, the REST library will send a “406 Not Acceptable” error to the client. SummaryIn general, responses are built according to the request type. There are classes in JAX-RS that help in the process of building responses. The responses are handled with specific HTTP codes that are sent along with the responses. These codes help the client application to understand the server-side better.  
JAX-RS Exception Handling

JAX-RS Exception Handling

by Vibrant Publishers on Dec 22, 2021
Introduction An exception is a case where an unexpected outcome occurs during computation. This often disrupts the normal flow of the program. There are different mechanisms available to handle an exception. Here in this article, we are going to see some of the mechanisms that JAX-RS has implemented to handle exceptions in its API services. JAX-RS Exceptions A RESTful API may throw exceptions at many scenarios and its proper handling is important for the functionality of that service. In JAX-RS exceptions are handled in two ways. By throwing a web application exception. By mapping exception using exception mapper.   Throwing a web application exception The WebApplicationException is a special RuntimeException class that JAX-RS has implemented in itself. By throwing a WebApplicationException, JAX-RS can abort a particular service method. This exception class can take an HTTP status code or a Response object as its constructor parameter. Let us consider the following code snippet:  @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (registration == null) {               Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND);               builder.type(“text/html”);               builder.entity(“   Registration Not Found   “);               throw new WebApplicationException(builder.build());           }           return registration;   }       Here if the object ‘registration’ is null, we create a response using the ResponseBuilder class. Here since we could not find any registration number we are setting the HTTP response code as 404 NOT_FOUND. This response class is then passed to WebApplicationException class which then throws this message as an exception to the client. Throwing a Not Found Exception The above code can be made even simpler by just throwing a NotFoundException. Because this class extends the WebApplicationException. So instead of creating a response using the ResponseBuilder, we can throw this exception as shown below:   @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (registration == null) {                     throw new NotFoundException(“Registration NOT found”);           }           return registration;   }       Mapping an exception using ExceptionMapper JAX-RS also provides a mechanism to map generic or custom exceptions into a JAX-RS response. This is done using the ExceptionMapper interface. So the code that throws the exception will implement the ExceptionMapper interface. Let us consider the above code snippet itself. There we were using the exceptions that already existed. Now let’s have a look at how we can use the ExceptionMapper in the same scenario. First, we will build a custom ‘RegistrationNotFoundException’ class.  public class RegistrationNotFoundException extends RuntimeException {       public RegistrationNotFoundException(String message) {          super(message);       }   }     Now we will map this exception to HTTP status message 404 – Resource NOT_FOUND and will build a JAX-RS response. The RegistrationNotFoundMapper class will do this job. Note that it is implementing the ExceptionMapper interface.  @Provider   public class RegistrationNotFoundMapper implements ExceptionMapper {       public Response toResponse(RegistrationNotFoundException exception) {           return Response.status(Response.Status.NOT_FOUND).                   entity(exception.getMessage()).                   type(“text/plain”).                   build();       }   }       Here the @Provider annotation is used for automatic discovery. You don’t need to declare the exception manually. The JAX-RS runtime will automatically discover it during the provider scanning phase. Finally, you throw the RegistrationNotFoundException.   @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (exam == null) {               throw new RegistrationNotFoundException(“Registration is not Found”);           }           return registration;   }    This will invoke RegistrationNotFoundMapper.toResponse and will send the custom response to the client.   The mapping of exceptions in this case is explained in the below given diagram.     Exception Mapping Mechanism Exception mapping providers map a runtime or checked exception to an instance of JAX-RS Response. If multiple exception providers are available, then one with the highest priority will be chosen. What will happen if an exception mapper fails to map an exception and that itself throws an error? In this case, a server error with status code 500 is returned to the client as a response. Summary There are different exception handling mechanisms available in JAX-RS. The simple and easy choice would be to use the built-in WebApplicationException. If there is a need to use custom exceptions, then the ExceptionMapper interface can be implemented in the code.    
JAX-RS Request Handling

JAX-RS Request Handling

by Vibrant Publishers on Oct 28, 2021
Introduction Creation and handling of API requests are very important while implementing RESTful services. Invoking a request, mapping of the request, handling the request call and responding to it, etc. are very essential steps in building RESTful services. In this article, let’s have a look at how the Java REST library, JAX-RS handles requests from the clients. JAX-RS Request Handling There are multiple stages for handling a request in JAX-RS. The diagram below shows some of the main aspects of JAX-RS request handling.     JAX-RS uses annotations at the server-side for handling requests from the client. Different types of annotations match different use cases. We are going to have a look at those annotations that are used while handling a client-side API request. @Path Annotation If you want a Java class to be able to handle REST requests, the class must add at least one @Path (“/”)” annotation. The value of this @Path variable can be simple strings to complex regular expressions. Some of the things that we must know about the @Path annotations are: Priority Check Rules  First, check the number of matching characters in a @Path.  Second, check the number of embedded template expressions.  Finally check the number of non-default template expressions. Path Characters If the expression in the path contains characters that need to be escaped, it will be escaped automatically. Otherwise, the URL encoding will be thought and performed. Here the following characters are allowed.  a-z, A-Z, 0-9, -!. ~'()* The following characters are reserved as escape characters.  ??$??/? @ Sub-resource locators If a method that specifies @Path annotations but does not specify HTTP method annotations returns another resource class object that then distributes and processes requests for sub-resources. Sub-resource classes do not need to be exposed as services, so the class can be without @Path annotation. Consider the following example, here @Path(“{database}-dB”) servers as the sub-resource locator.   public class CustomerData    { ……      @Path(“{database}-dB”)      public CustomerDatabase getDatabase(@PathParam(“database”) String dataBase)       {         // find the instance based on the dataBase parameter         CustomerRecord resource = locateCustomerRecord(dataBase);         return resource;        }        …..     }         The @Consumes annotation This annotation specifies which media type a resource can accept at the server-side from an API request. This is important to specify while creating or updating resources at the server side using REST APIs. If this annotation is applied at the class level, all the methods in the class accept the same media type by default. When there is a method that applies @Consumes at a method level, that will override the class level annotation. The value of @Consumes is a string array with acceptable media types. For example: @Consumes({“text/plain,text/html”}) Request Method Annotations The request method annotations are used to map the HTTP methods to Java programming language methods. These are run-time annotations defined by JAX-RS. They correspond to the similarly named HTTP methods. JAX-RS defines @GET, @POST, @PUT, @DELETE, and @HEAD as common request method annotations. You can also create your own custom request method annotations. Methods decorated with request method annotations must return a void or a javax.ws.rs.core.Response Object. Extracting Request Parameters When we create an API request, we can include different parameters into it so that we can extract information at the server side based on these parameters. The following types of parameters can be extracted from a given request. Query Query parameters are specified by @QueryParam in the method parameter arguments. One must import javax.ws.rs.QueryParam class for this. The following example demonstrates application of                                                                   @QueryParam.   @Path(“smooth”)   @GET   public Response smooth(      @DefaultValue(“2”) @QueryParam(“count”) int count,      @DefaultValue(“true”) @QueryParam(“has-min”) boolean hasMin)           {             ……….           }       Here one thing to note is the use of @DefaultValue annotation. They are used to set a specific value to the request if there is no value is provided by the client while using a specific @QueryParam URI path URI path parameters are extracted from the URI request itself. The parameter name is included in the @Path annotation. In the java method arguments, they are specified using the @PathParam annotations. For example:                                                                               @Path(“/{name}”)   public class UserNamePrinter    {      ……    @GET      public String printUserName(@PathParam(“name”) String userID)      {        ……..         }     }     Form Form parameters use the @FormParam annotation and extract information from a request that is of the MIME media type application/x-www-form-urlencoded and conforms to the HTML form encoding specifications. They are mostly used when information is sent in HTML form using the POST method. Cookie Cookie parameters extract information from the cookie-related HTTP headers. It uses @CookieParam annotation. Header Header parameters extracts information from the HTTP headers. Here we use @HeaderParam annotation. One must include the javax.ws.rs.HeaderParam class for using this annotation. Matrix Header parameters extracts information from the URL path segments. The annotation for the Matrix request parameter is @MatrixParam. The class is located in javax.ws.rs.MatrixParam. Summary JAX-RS uses annotations at the server side for handling API requests and there are specific annotations for handling requests from a client-side API. Forming a correct URI, specifying the media types, extracting information from the URI, etc are some of the important steps while processing an API request at the server-side.