Print next Greatest Element for entry in an Array.

Problem

Given an array, which can have positive and negative numbers, write a code to print the next greatest element for each element. For the last number, next greater element will always be Integer.MIN.

For element, for which no greater number is present, print Integer.MIN.

Example – input array – [7,1,5,3,6,4]

Expected output – [MIN,6,6,6,MIN,MIN] .{MIN is considered as Integer.MIN}

Method to implement :


public String[] solution(int[] input);

Solution


public String[] solution(int[] input){

if(input == null || input.length <=1 ) return null;
int n = input.length;
String[] result = new String[n];
Stack<Integer> s = new Stack<>();
result[n-1] = "MIN";
s.push(input[n-1]);

for(int i = n-2;i>=0;i--){

while (!s.empty() && s.peek() < input[i]){
s.pop();
}
if(s.isEmpty()){
result[i] = "MIN";
s.push(input[i]);

}else{
result[i] = s.peek().toString();

}

}
return result;
}

Implementation

  • Find the day on which stock should be bought and sell, to have maximum profit, Stock can be bought and sold only once.

 

 

Advertisements

AOP in Java Using Annotation

What is AOP? 

AOP stands for the Aspect-Oriented Programming. It is an approach to programming that allows global properties of a program to determine how it is compiled into an executable program. AOP can be used with object-oriented programming ( OOP ).It addresses the problem of cross-cutting concern.

All above is the technical definition, but now we will try to understand it in the more simpler term. Let suppose, as a developer you want to log request and response in the database whenever third-party API is called. One simple method is to add the logging code in the method itself. But should we add the code to log in method, as my method is not created for logging? Even if you are OK with adding the code to the method, now think if you have more than one method where you have to perform this logging. Now what?  Will we write the logging code in each and every method?

No, what we will do, we will find some magic way, by which our logs should be automatically written to the database. And that magic is AOP.

To read more about the AOP, read here.

How to use Annotation with AOP?

Since by now we should know that AOP needs pointcut to perform the magic.Now suppose you just want to log whenever any method is called. If you put a simple annotation on any method, and your work is done.

Here is an example of the same of how to use annotation for logging.

 

 

 

Some Use cases of Annotations

In our previous post, we understand what annotation is, and how to create our custom annotations. Now we will try to understand how and when we can use annotation.

This is more sort of the suggestion rather than any rule of using experience.All this will be from my experience, it can change from person to person.

The common examples where I love to use annotations are:

Separating and Categorization
Every one of us loves to code and to protect our code we write test cases. We all are familiar with unit test cases and integration test cases. To reduce the build in time we always want to run these test cases in parallel.But to run them in parallel we first have to categorize these in two different buckets. we need some mechanism to identify what test cases are unit test cases and what are integration test cases.
For this, we will try very simple use case. We will try to use annotation to identify our type of test cases.We will create a simple spring application with Gradle, which have few unit test cases and integration test cases.
You can access the code base directly from GIT Repo.
  • First, create a simple spring-boot application with Gradle.
  • Create two interfaces “UnitTest” and “IntegrationTest

 

package com.application
public interface UnitTest{}

 

package com.application
public interface IntegrationTests{}

  • Create Gradle task to run different type of test cases

Gradle tasks

test {
    useJUnit {
        includeCategories 'com.application.UnitTest'
    }
}

task integrationTest(type: Test) {
    useJUnit {
        includeCategories 'com.application.IntegrationTest'
    }
}

 

All you need to do is put the annotation on your test case now.


@Category(IntegrationTest.class)
public class IntegrationTestCaseExample {
}

 


@Category(value = UnitTest.class)
public class UnitTestCaseExample {
}

Now all you need to do is run the gradle test if running unit test cases and gradle integrationTest if have to run integration test.

 

Sample code for the same can be seen at this link

For further usage of Annotation,  will try to write few more blogs

Java Annotations

AOP in Java Using Annotation

Java is one of my favorite languages. It is simple. But some of its features are still not used very commonly. One of them is Annotations. Annotation is very simple and one of the powerful concept of java. If you have worked the on framework like spring , you may have seen there are Annotation to do most of the setting.

Though we have used annotation in many ways , still I have not seen my developer going for the creation of their custom annotation. This blog helps us to understand when and where we can utilize the power of annotation.

What is Annotation?

import javax.annotation.PostConstruct;
import javax.validation.constraints.Max;

@Deprecated
public class Foo {

@Max(10)
int foo = 0;

@PostConstruct
private void setFoo() {
foo = 4;
}
@Deprecated
int returnFooCount() {
return foo;
}
}

Annotation is a tag which can have metadata that can be attached to class, interface, methods or fields to indicate some additional information which can be used by Java compiler and JVM.

Example:- @Deprecated,@Override,@PostConstruct are some of the in build java annotation which we have been using.Here you have seen we have added the annotation at class , at attribute and even at method.

Why Annotations?

Prior to Annotations, XML was often used to have the metadata. The Large set of Architectures and developers often believe that XML maintenance is difficult and it is not very easy to read. Something was needed which should be more close to code.Annotations are easy to understand and more readable.

Uses Of Annotations

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings or to give some information to the compiler.[eg- @Serialization]
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.[eg -lombok project – @Data,@Builder]
  • Runtime processing — Some annotations are available to be examined at runtime.[ It can be used as point cut in Aspect Oriented Programming]
  • Comments — Often people use annotation to provide comments, why I prefer annotations over the comment as it provides the structural way of commenting.[@Deprecated, any other custom annotation]

How Annotation Works?

Before using any concept we should understand how it works internally, only then we can explore the better way of using it and can use it properly.As we all know annotation does not contain any business knowledge.Then how it actually works?

When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed, and also modify the annotated code itself. The Java compiler conditionally stores annotation metadata in the class files, if the annotation has a RetentionPolicy of CLASS or RUNTIME(We will cover more about retention policy in further section). Later, the JVM or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.

In addition to processing an annotation using an annotation processor, a Java programmer can write their own code that uses reflections to process the annotation

This package contains the interface called AnnotatedElement that is implemented by the Java reflection classes including Class, Constructor, Field, Method, and Package. The implementations of this interface are used to represent an annotated element of the program currently running in the Java Virtual Machine. This interface allows annotations to be read reflectively.

The AnnotatedElement interface provides access to annotations having RUNTIME retention. This access is provided by the getAnnotation, getAnnotations, and isAnnotationPresentmethods. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object.

How to Build Custom Annotation?

Below is the simplest Annotation one can create.


public @interface CustomAnnotation {
}

 

Annotations itself can have some annotations, which tell us something about our new annotation.

  • Retention – It tells java how long any annotation will be retained during the different phase of code. Retention annotation have property RetentionPolicy which have 3 possible values:-
    • Source: Annotations are to be discarded by the compiler.
    • Class: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.[DEFAULT]
    • Runtime: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time so they may be read reflectively.

@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
}

Note-A Retention meta-annotation has effect only if the meta-annotated type is used directly for annotation. It has no effect if the meta-annotated type is used as a member type in another annotation type.

  • Target: As we know we can put annotation at many different levels, at class, at attribute and many other. But as a developer, you might want to bound the use of your annotation at some level only, as your annotation can make sense some particular level.To declare the level this annotation is used.It has an attribute array of element type which can have all the possible level. There are different type elements in java.Most of them are self-explanatory.
    • Element Type
      • TYPE
      • FIELD
      • METHOD
      • PARAMETER
      • CONSTRUCTOR
      • LOCAL_VARIABLE
      • ANNOTATION_TYPE
      • PACKAGE
      • TYPE_PARAMETER [new in java 1.8]
        • eg  <T extends @A Object & @B Comparable, U extends @C Cloneable>
      • TYPE_USE [new in java 1.8] eg –
        • Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;
  • Inherited:- If this annotation is present it will be inherited to the subclass, By default it is not present. It will only be effective when the annotation is given at class level.
  • Documented:-  Marks the annotation for inclusion in the documentation. Indicates that annotations with a type are to be documented by javadoc and similar tools by default.
  • Repeatable: Prior to Java 8 user were not allowed to give same anntation multiple times at same place.But If any annotation have repeatable annotation that can be put multiple time at same place.

Example

 

@Retention( RetentionPolicy.RUNTIME )
public @interface Cars {
       Manufacturer[] value() default{};
 }

@Repeatable(value = Cars.class )
public @interface Manufacturer {
String value();
};

@Manufacturer( "Mercedes Benz")
@Manufacturer( "Toyota")
@Manufacturer( "BMW")
@Manufacturer( "Range Rover")
public interface Car { 

}

Now we can give Manufacturer annotation multiple times to interface Car. Manufacturer annotation contains the Repeatable annotation which contains some other annotation as its value.

 

 

Now we know all the attribute of annotation, we can create annotations.


@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(value = {ElementType.TYPE})
public @interface CustomAnnotation {
String name();
String identifier() default "";
}

 

In our custom annotation, we have two properties name and identifier. A value doesn’t have any default property, so whenever we use this  CustomAnnotation it is mandated to give value attribute some value, otherwise, it gives error.On the other hand, identifier contain some default value, so we don’t have to compulsory give its value.

 

So, till now we have some basic idea how annotation work, and how to create an annotation.In the further blog, we will see the different situations where we can create our own custom annotations, and how to tell JVM to process these annotations.

Some Useful In-Build Annotations in Java

 

  • @GuardedBy
  • @Immutable
  • @NotThreadSafe
  • @ThreadSafe
  • @SuppressWarnings

Some Uses on Annotations

 


Useful Links

Spring Boot + Docker + Bit Bucket + Automate Deployment

An idea behind this blog to walk through the auto build of docker image in docker hub for Spring boot application.

Note: – This method is not production level, so use it for staging or development phase only.

(Why it is not suitable for production ?)

[As we have to push the jar to the git repository, to reduce few steps.]

Technology Stack Used

  • Spring Boot [1.4.1 Release]
  • Java 8
  • Maven 2
  • Bit Bucket
  • Docker Hub

Prerequisite

  • Docker Hub Account
  • Bit Bucket Account
  • Minimum knowledge of Spring boot and Java
  • Link Bit Bucket to Docker Hub. CLICK HERE for the reference.

Steps

  1. Create Spring boot Application Capable of creating docker image
    • Create simple spring boot application with web module.[CLICK HERE to create using spring start.io or get it from BIT-BUCKET repo (master branch)].
    • Add Simple test controller to the Spring Project or check out to the branch controller-test.
    • Add Docker support to your current spring boot application or check out to branch docker-support. [To learn how to add docker support to spring boot application you check this blog.]
  2.  Create New Repository and link for auto creation of image
    1. Go to docker hub and click on create -> create automatic build
    2. Click on create Auto-build bit-bucket
    3. Select the desired bitbucket repository
    4. Fill required information and click on create.
    5. Go to build setting and provide the branch name from which image should be created and save changes.
    6. Click on build details, it will be empty right now
    7. Make Some changes in that particular branch and push it to the Origin.
    8. Now again check the build details tab, there will be new entry populated with status queued.
    9. Wait for some time its status will change to building than to success.
    10. Now your docker image is ready to use.
  3. Test created docker image
      1. Now pull the docker image
      2. Run the docker image with command [docker run –name docker.test -d -p 8088:8080 jainamit333/docker.demo:docker-support]
      3. Navigate to http://localhost:8088/docker/test.It will show the desired result.

Now each time user push to anything to branch, new docker image will be created.

Dockerize Spring Boot Application

This blog will help the audience to enable them to create docker image from a Spring boot Application.We have created a Spring Boot with maven.

We have already created the code repository. This repository contain 3 branches

1.Master: – Vanilla Spring Boot with Web Module

2.Controller-Test: – Master with test Rest repository.

3.Docker-Support :- Added docker support to Controller-Test branch

Prerequisite

  • Spring Boot Knowledge
  • How to create simple DockerFile

Here we will see what changes are required to add docker support to Spring Boot Application. It is the changes required to create Docker-Support branch from Controller-Test branch.

Changes Required in Pom

We need to add below mention plugin in the pom.

<plugin>
   <groupId>com.spotify</groupId>
   <artifactId>docker-maven-plugin</artifactId>
   <version>0.2.3</version>
   <configuration>
      <imageName>horizon/${project.artifactId}</imageName>
      <dockerDirectory>/</dockerDirectory>
      <resources>
         <resource>
            <targetPath>/</targetPath>
            <directory>/</directory>
            <include>${project.build.finalName}.jar</include>
         </resource>
      </resources>
   </configuration>
</plugin>

Add DockerFile in the project path

FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD target/docker-0.0.1.jar app.jar
RUN sh -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
EXPOSE 8080

There are two ways to create a docker image from the current source now.

1.Create docker image using maven plugin [can also be used using Jenkin worklow]

Run the command from project directory:- mvn clean package docker:build

2.Create docker image using docker build command

Run mvn install:- mvn clean install

Create docker image by executing the following command from project directory:

docker build  -t  docker.demo:latest  .

ThoughtWorks-interview experience

Got a call from a consultant,

I am sharing my interview experience for the same with you.

  1. Telephonic [30 mins]
    1. Current Project, and how PMS work internally.
    2. The difference between quick sort and merge sort.
    3. Which sorting did java use internally?
    4. When to user Interface, and Abstract classes.
    5. How to make class Immutable, and if immutable class contain a list, how to handle it.
  2. Coding[With Laptop coding]
    1. Write a program to full fill following problem: two(times(three())) or nested cases also.All the operator should be there.[logic was important].Click Here to get the complete code of this problem
  3. Coding[With Laptop coding]
    1. Write a code to compute the cost of the checkout cart, have many items with quantity, the group of items can have the special price. Every item has there individual price.[Focus on domain design]
  4. F2F Interview
    1. Current project design, architecture, your role.
    2. Difference btw soap and rest service.
    3. Domain design for a ROOM.
    4. Multi-thread simple question,
    5. DB designing simple.
  5. F2F Interview
    1. this was more of a discussion rather than the interview, more related to culture and personality.They will try to understand who you are, what are your goals.Are you  right person or not for ThoughtWorks
  6. F2F Interview
    1. It was related to the 3 pillars that ThoughtWorks build on, and try will try to understand your point of view on various social issues
  7. Aptitude Test
    1. There are around 50 questions, you  have to complete as much as question in 12 min
  8. Logical Test
    1. There are 13 question which have to completed in 1 hour.
A major focus will be given to Domain Design, how the class is created and how the will interact.
OOPS, concepts are important.Name of the classes matter.
If really want to crack Thoughtworks, please check few books.