How to get synchronized version of ArrayList object?

By default ArrayList object is non synchronized but we can get synchronized version of ArrayList by using collection class’s synchronizedList() method.

Non-synchronized 

ArrayList nonSyncronizedList = new ArrayList();

Synchronized

List syncronizeList = new Collections.synchronizedList(l1);

Similarly we can get synchronized version of set, map objects by using the following methods of collection class.

Public static Set synchronizedSet(Set s);

Public static Map synchronizedMap(Map m);

415 total views, 3 views today

Stack Class

  1. It is the child interface of vector.
  2. It is specially designed class for last in first out (LIFO).

Methods in stack

  1. Object push(Object o)

For inserting an object to the stack.

  • Object pop()

To remove and return top of the object.

  • Int peak();

To return the top of the stack without removal of object.

  • Int search(Object o)

If the specified object is available it returns its offset from the top of the stack.

If the specified object is not available it returns -1.

Examples

package List;

import java.util.Stack;

public class StackDemo {
	public static void main(String[] args) {
		Stack s = new Stack();
		s.push("A");
		s.push("B");
		s.push("C");
		System.out.println(s); // [A, B, C]
		System.out.println(s.search("A")); // 3
		System.out.println(s.search("Z")); // -1
	}

}

306 total views, 1 views today

Vector Class

  1. The underlying data structure for the vector is resizable array or grow able array.
  2. Duplicates objects are allowed.
  3. Insertion order is preserved.
  4. Null insertion is possible.
  5. Heterogeneous objects are allowed.
  6. Vector class implemented Serializable, Cloneable and RandomAccess.
  7. Most of the methods present in vector are synchronized. Hence vector object is thread safe.
  8. Best choice if frequent operation is retrieved.

Methods of vector class

For adding objects:-

add(Object o) [from Collection-List l]
add() [from List]
addElement(Object o) [from Vector]

For removing objects:-

remove(Object o) [from Collection]
removeElement(Object o) [from Vector]
remove(int index) [from List]
removeElementAt(int index) [from Vector]
clear() [from Collection]
removeAllElements() [from Vector]
=

For accessing elements:-

Object get(int index) [from Collection]
Object elementAt(int index) [from Vector]
Object firstElement() [from Vector]
Object lastElement() [from Vector]

Other Methods:-

int Size();
int Capacity();
Enumeration elements ();

Constructors of Vector class

Vector v = new Vector();

Creates an empty vector object with default initial capacity 10, once vector reaches its maximum capacity a new object will be created with new capacity.

             New Capacity = 2*Current Capacity

Vector v = new Vector(int initial capacity);

Creates an empty vector object with specified initial capacity.

Vector v = new Vector(int initial capacity, int incremental capacity)
Vector v = new Vector(Collection c);

Creates an equivalent vector object for the given collection.

Example

package List;

import java.util.Vector;

public class VectorDemo {
	public static void main(String[] args) {
		Vector v = new Vector();
		System.out.println(v.capacity()); // 10
		for (int i = 1; i <= 10; i++) {
			v.addElement(i);
		}
		System.out.println(v.capacity()); // 10
		v.addElement("A");
		System.out.println(v.capacity()); // 20
		System.out.println(v); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]

	}

}

264 total views, 1 views today

LinkedList

  1. The underlying data structure is double linked list.
  2. Insertion order is preserved.
  3. Duplicates are allowed.
  4. Heterogeneous objects are allowed.
  5. Null insertion is possible.
  6. LinkedList implements Serializable and Cloneable interfaces but not RandomAccess interface.
  7. LinkedList is best choice if our frequent operation is insertion and deletion in the middle.
  8. LinkedList is worst choice if our frequent operation is retrieval operation.
  9. Usually we can use LinkedList to implement stacks & queue to provide support for this requirement LinkedList class defines following specific methods.
  10. In retrieval, 1st element takes 1sec to find, 2nd element takes 2sec to find. Hence nth element takes n sec. So time complexity is O(n)

A double linkedList whose node contains three fields, 1st field either points to the start or address of the previous node, 2nd field contain the data or 3rd field either contain the next node address or points to the end (null).

  LinkedList node

Previous node address or
address point
Data Next node address
or null

LinkedList list points to the 1st element and it has the address of the second node where second node will contain the address of previous node, data and address of next node.

Methods of LinkedList

void addFirst();

void addLast();

Object getFirst();

Object getLast();

Object removeFirst();

Object removeLast();

Constructors of LinkedList

LinkedList list = new LinkedList();

Creates an empty LinkedList object.

LinkedList list= new LinkedList(Collection c);

Creates an equivalent linked list object for given collection.

Examples

package List;

import java.util.LinkedList;

public class LinkedListDemo {

	public static void main(String[] args) {
		LinkedList l1 = new LinkedList();
		l1.add("durga");
		l1.add(30);
		l1.add(null);
		l1.add("durga");
		System.out.println(l1); // [durga, 30, null, durga]
		l1.set(0, "software");
		System.out.println(l1); // [software, 30, null, durga]
		l1.add(0, "venky");
		l1.addFirst("ccc");
		System.out.println(l1); // [ccc, venky, software, 30, null, durga]
	}

}

279 total views, 1 views today

ArrayList

  1. The underlying data structure is resizable array and grow able array.
  2. Duplicates are allowed.
  3. Insertion order is preserved.
  4. Heterogeneous objects are allowed [except TreeSet and TreeMap]
  5. Null insertion is possible.

ArrayList Constructors

  • ArrayList list = new ArrayList();

Creates an empty array list object with default initial capacity. Once array list reaches its maximum capacity a new array list will be created with new capacity.

New capacity = (Current Capacity*3/2)+1 which is almost 75%

            With the above mentioned constructor Arraylist with default size i.e. 10 will be created and once it reaches its maximum capacity then it grows dynamically with new capacity i.e. 15.

  • ArrayList list = new ArrayList(int initial capacity);

Creates an empty array list object with the given initial capacity. Once array list reaches its maximum capacity a new array list will be created with new capacity.

  • ArrayList list = new ArrayList(Collection c)

Creates an array list object for the given collection.

Example

package List;

import java.util.ArrayList;

public class ArrayListDemo {
	public static void main(String[] args) {
		ArrayList l = new ArrayList();
		l.add("A");
		l.add("10");
		l.add("A");
		l.add("null");
		System.out.println(l); // [A, 10, A, null]
		l.remove(2);
		System.out.println(l); // [A, 10, null]
		l.add(2, "M");
		l.add("N");
		System.out.println(l); // [A, 10, M, null, N]

	}

}

6. Usually we can use collection to hold and transfer objects over the network and to support this requirement every collection already implements Serializable and Cloneable.

7. ArrayList and vector classes implements RandomAccess interface so that we can access any random element with the same speed.

package List;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.RandomAccess;

public class ArrayListSerialClone {

	public static void main(String[] args) {
		ArrayList l1 = new ArrayList();
		LinkedList l2 = new LinkedList();
		System.out.println(l1 instanceof Serializable); // true
		System.out.println(l1 instanceof Cloneable); // true

		System.out.println(l2 instanceof Serializable); // true
		System.out.println(l2 instanceof Cloneable); // true

		System.out.println(l1 instanceof RandomAccess); // true
		System.out.println(l2 instanceof RandomAccess); // false

	}
}

8. Hence if our frequent operation is retrieval operation then ArrayList is the best choice.

9. ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle(Because several shift operations will be required).

282 total views, 1 views today

List interface

  1. It is the child interface of collection.
  2. Duplicates are allowed
  3. If we want to represent a group of individual objects as a single entity where insertion order is preserved then we should go for list.
  4. We can differentiate duplicates by using index.
  5. We can preserve insertion order by using index, hence index play very important role in list interface.

List of 10 elements where index starts with 0 to 9. Index goes from 0 to 9. 0 & 9th position contains the same element.

Methods of List:-

void add(int index, Object o)

boolean addAll(int index, Collection c)

object get(int index)

object remove(int index)

object set(int index, Object new)

int indexOf(Object o)

int lastIndexOf(Object o)

ListIterator listIterator();

371 total views, 1 views today

Learn Docker Beginner


If you are in Software industry then you must use this phrase to prove yourself.





But I m sure after reading this tutorial you won’t be able to say this again.





1. What is Docker

Docker is a software platform designed to make it easier to create, deploy, and run applications by using containers. It allows developers to package up an application with all the parts it needs in a container, and then ship it out as one package

2. Virtual Machines vs. Docker

Virtual machines have a full OS with its own memory management installed with the associated overhead of virtual device drivers. Every guest OS runs as an individual entity from the host system.

On the other hand Docker containers are executed with the Docker engine rather than the hypervisor.

 







3. Introduction to Dockerfiles, images and containers

A Dockerfile is a text file that Docker reads in from top to bottom. It contains a bunch of instructions which informs Docker HOW the Docker image should get built.

A Docker image gets built by running a Docker command (which uses that Dockerfile)

A Docker container is a running instance of a Docker image

If you are too much into object oriented design then you can assume Docker image as a class, where as a Docker container is an instance of that class.


4. The Docker Hub

Docker Hub is a cloud-based repository in which Docker users and partners create, test, store and distribute container images which you can get from here.

https://hub.docker.com/


Create and Run docker image

prerequisite : Must have docker installed in system

https://javaquicky.com/2019/01/27/install-docker-on-ubuntu/


In this scenario, you’ll learn how to create a Docker Image for running a static HTML website using Nginx.
The scenario will explain how to build a Docker Image running Nginx with your HTML site.
The aim is to help you understand how to create and run Docker Images created by yourself.

create folder Docker and add file hello.html file into that.

Hello.html
<h1>Hello World</h1>


add one more file name Dockerfile make sure file name should be like this only without ant extension.

Open terminal and reach at folder Docker
vikash@vikash-pc:~/D-Drive/RKS_DOCS$ cd /home/vikash/D-Drive/RKS_DOCS/Docker/
vikash@vikash-pc:~/D-Drive/RKS_DOCS/Docker$ ls -lrt
total 8
-rw-rw-r-- 1 vikash vikash 20 Jan 27 16:03 Hello.html
-rw-rw-r-- 1 vikash vikash 49 Jan 27 16:04 Dockerfile


Step 1 – Create Dockerfile

Copy the below content in your Dockerfile for building your image.

Copy to EditorFROM nginx:alpine

COPY . /usr/share/nginx/html



The first line defines our base image.

The second line copies the content of the current directory into a particular location inside the container.

Step 2 – Build Docker Image
The Dockerfile is used by the Docker CLI build command. The build command executes each instruction within the Dockerfile. The result is a built Docker Image that can be launched and run your configured app. The build command takes in some different parameters.
The format is

docker build -t <build-directory>


The -t parameter allows you to specify a friendly name for the image and a tag, commonly used as a version number. This allows you to track built images and be confident about which version is being started.

sudo docker build -t webserver-image:v1 .

 

Result:
 
vikash@vikash-pc:~/D-Drive/RKS_DOCS/Docker$ sudo docker build -t webserver-image:v1 .
[sudo] password for vikash: 
Sending build context to Docker daemon  3.072kB
Step 1/2 : FROM nginx:alpine
alpine: Pulling from library/nginx
cd784148e348: Pull complete 
6e3058b2db8a: Pull complete 
7ca4d29669c1: Pull complete 
a14cf6997716: Pull complete 
Digest: sha256:385fbcf0f04621981df6c6f1abd896101eb61a439746ee2921b26abc78f45571
Status: Downloaded newer image for nginx:alpine
 ---> 315798907716
Step 2/2 : COPY . /usr/share/nginx/html
 ---> 6c54defc9f09
Successfully built 6c54defc9f09
Successfully tagged webserver-image:v1


As you can see in above output that above command executes all given steps in Dockerfile one by one.

You can view a list of all the images on the host using

sudo docker images



Output:
 
vikash@vikash-pc:~/D-Drive/RKS_DOCS/Docker$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
webserver-image     v1                  6c54defc9f09        2 minutes ago       17.8MB
hello-world         latest              fce289e99eb9        3 weeks ago         1.84kB
nginx               alpine              315798907716        4 weeks ago         17.8MB

The built image will have the name webserver-image with a tag of v1.

Step 3 – Run

Launch our newly built image providing the friendly name and tag. As it’s a web server, bind port 80 to our host using the -p parameter.

docker run -d -p 80:80 webserver-image:v1


Once started, you’ll be able to access the results of port 80 via

http://localhost/Hello.html


You now have a static HTML website being served by Nginx.



271 total views, no views today

Install docker on Ubuntu

Step :1  

Open terminal using command Ctrl+T.

Step 2:

Update your existing list of packages.

sudo apt update


Step 3:

Install prerequisite packages which let apt use packages over HTTPS:

sudo apt install apt-transport-https ca-certificates curl software-properties-common


Step 4:

Add GPG key for the official Docker repository to your system:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -


Step 5:
Add the Docker repository to APT sources:


sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bioni


Step 6:


Update the package database 

sudo apt update


Step 7:


Make sure you are about to install from the Docker repo instead of the default Ubuntu repo:

apt-cache policy docker-ce


You’ll see output like this, although the version number for Docker may be different:


Notice that docker-ce is not installed

Step 8:


Finally, install Docker:

sudo apt install docker-ce



Step 9:


Docker should now be installed, the daemon started, and the process enabled to start on boot. Check that it’s running:

sudo systemctl status docker






Installing Docker now gives you not just the Docker service (daemon) but also the docker command line utility,


Step 10:


To view system-wide information about Docker, use:

docker info



This will give you permission error so try with sudo you can check more on how to avoid using sudo everytime


sudo docker info

To check whether you can access and download images from Docker Hub, type:


Step 11:


sudo docker run hello-world





To see the images that have been downloaded to your computer, type:

sudo docker images






The output should look similar to the following:


The hello-world container you ran in the previous step is an example of a container that runs and exits after emitting a test message. Containers can be much more useful than that, and they can be interactive.

After using Docker for a while, you’ll have many active (running) and inactive containers on your computer. To view the active ones, use:

sudo docker ps




check latest one

sudo docker ps -l



  

To view all containers — active and inactive, run docker ps with the -a switch:

sudo docker ps -a



Thats all in terms of installing Docker and some basic commands.

286 total views, 1 views today

Template for API gateway creation using CI-CD

Below is the template which can be used for api gateway creation in AWS
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  Application containing RestAPI for First

Globals:
  Function:
    Timeout: 30

Parameters:
  #s3 bucket name
  BucketName:
    Type: String
    Description: Bucket to be used
    Default: lambda-deployment-d1

  EnvironmentName:
    Type: 'AWS::SSM::Parameter::Value<String>'
    Default: /<parameterPath>/EnvironmentName                        
    # /myDemo/d1/EnvironmentName

  StageName:
    Type: 'AWS::SSM::Parameter::Value<String>'
    Default: /<parameterPath>/StageName                             
    # /myDemo/d1/EnvironmentName

  BucketPrefix:
    Type: String
    Description: bucket prefix
    Default: first-project-api                                   
    # /myDemo/d1/EnvironmentName

  CertificateARN:
    Type: 'AWS::SSM::Parameter::Value<String>'
    Default: /<parameterPath>/CertificateARN    
    # /myDemo/d1/CertificateARN

  DomainName:
    Type: 'AWS::SSM::Parameter::Value<String>'
    Default: /<parameterPath>/DomainName        
    # /myDemo/d1/DomainName



Resources:

  LambdaRoleForVPCResources:
    Type: AWS::IAM::Role                                            
    # https://serverless.com/framework/docs/providers/aws/guide/resources/
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: "Allow"
          Principal:
            Service:
            - "lambda.amazonaws.com"
          Action:
          - "sts:AssumeRole"
      Policies:
      #policy name
      - PolicyName: "LambdaVpcPolicy"
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
          - Effect: "Allow"
            Action:
            - "logs:CreateLogGroup"
            - "logs:CreateLogStream"
            - "logs:PutLogEvents"
            - "ec2:CreateNetworkInterface"
            - "ec2:DescribeNetworkInterfaces"
            - "ec2:DeleteNetworkInterface"
            - "dynamodb:*"
            - "apigateway:*"
            Resource: "*"
  #creates api gateway using swagger.yml
    
    
  FirstRestAPI:
    Type: AWS::Serverless::Api                 
    # https://docs.aws.amazon.com/serverless-alication-model/latest/developerguide/serverless-sam-template.html
    Properties:
      Name: !Join ['', [' first-rest-api-', !Ref EnvironmentName]]
      StageName: !Ref StageName
      # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-transform.html
      DefinitionBody:
        'Fn::Transform':        
         # Fn::Transform specifies a macro to perform custom processing on part of a stack template. 
          Name: 'AWS::Include'
          # Replace <bucket> with your bucket name
          Parameters:
            Location: !Join ['', [ 's3://',!Ref BucketName, '/',!Ref BucketPrefix, '/swagger.yaml'  ] ]

  FirstRestAPIGetByItem:
    Type: AWS::Serverless::Function 
    # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-transform.html
    FunctionName: !Join ['', [ 'FirstRestAPIGetByItem-', !Ref EnvironmentName ] ]
    Properties:
      #python code base containg lambdas which process request
      CodeUri: First-rest-api/build/
      #lambda name and its method
      Handler: ItemByName.lambda_handler
      Runtime: python3.7
      #role of lambda
      Role: !GetAtt LambdaRoleForVPCResources.Arn
      #these are environment variable which are required for lambda
      Environment:
        Variables:
          First_TABLE:  !Join ['', [ 'Item-table-', !Ref EnvironmentName ] ]
         
      Events:
        #listner of lambda fucntion ...this can be api kinesis or any aws service
        SubscribeToEvents:
        #type of service to subscribe
          Type: Api
          Properties:
            #name of service this is declared above
            RestApiId: !Ref FirstRestAPI
            #path to access api this is also maed to swagger.yml
            Path: /item
            #method type
            Method: post



    #done for static name creation --create name of api
  ApiDomainName:
    Type: 'AWS::ApiGateway::DomainName'
    Properties:
      CertificateArn: !Ref CertificateARN
      DomainName: !Join ['', ['first-api-', !Ref EnvironmentName, '.', !Ref DomainName]]
   
   #done for static name creation -- create maing for api
  APIMaing:    
    Type: 'AWS::ApiGateway::BasePathMapping'
    Properties:
      BasePath: v1
      DomainName: !Ref ApiDomainName
      RestApiId: !Ref FirstRestAPI
      Stage: !Ref StageName


#generates output url for the generated services      
Outputs:

  ItemByNameApiUrl:
    Description: URL of API endpoint
    Value: !Join
    - ''
    - - https://
      - !Ref FirstRestAPI
      - '.execute-api.'
      - !Ref 'AWS::Region'
      - '.amazonaws.com/'
      - !Ref StageName
      - '/item'



   #shows details of all created api's
  FirstRestAPIGetByItem:
    Description: " Rest API Function ARN"
    Value: !GetAtt FirstRestAPIGetByItem.Arn



313 total views, 1 views today

Caused by: java.lang.ClassNotFoundException: javax.jms.JMSContext

I was also facing the same issue when I moved from spring-3.0 to spring-5.0 while using Tomcat-7 to deploy my application. I added below maven dependency in pom.xml file and it got resolved.
<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>javax.jms-api</artifactId>
    <version>2.0.1</version>
</dependency>
The root cause I found is, UserCredentialsConnectionFactoryAdapter class provided by spring-jms-5.0.2.RELEASE.jar was using JMSContext class internally. This class was not available in jms-1.1.jar which I was using with spring-jms-3.2.4.jar.
So I replaced jms-1.1.jar with javax.jms-api-2.0.1.jar
I would suggest you to add/upgrade your jms jar as mentioned above according to you spring version.
Hope this works!

929 total views, 2 views today