Java Unfolded

– The inner view

Monthly Archives: September 2017

Proxy design pattern – Behaviaral

Below is the code which demonstrates Proxy design pattern.

Basically, in some schools/offices, some HTTP requests are blocked based on the request keywords, below is the sample code to block and log the user requests.


package designpatterns.behaviaral.proxy;
/** * @author Nag * */
public interface InternetServiceProvider {
public String service(String request);
}

package designpatterns.behaviaral.proxy;
/** * @author Nag * */
public class InfaProxy implements InternetServiceProvider{
private InternetServiceProvider isp = null;
public InfaProxy(String name, String ip){
isp = new ACTFiber(name, ip);
}
@Override
public String service(String request) {
logAndValidateRequest(request);
return isp.service(request);
}
private void logAndValidateRequest(String request) {
if(request.contains("cricinfo")){
logToDatabase(request);
throw new RuntimeException("Your request has been blocked : [cricinfo] exists in the request.");
}
}
private void logToDatabase(String request) {
System.out.println("Request has been logged : "+request);
}
}

package designpatterns.behaviaral.proxy;
/** * @author Nag * */
public class ACTFiber implements InternetServiceProvider{
String name = null;
String ip = null;
public ACTFiber(String name, String ip){
this.name = name; this.ip = ip;
}
@Override
public String service(String request) {
String response = ip +" : "+ name +": response";
return response;
}
}

package designpatterns.behaviaral.proxy;
/** * @author Nag * */
public class ProxyDemo {
public static void main(String[] args) {
InternetServiceProvider isp = new InfaProxy("Infa access", "10.1.1.1");
String response = isp.service("www.cricinfo.com");
System.out.println("Response :" + response);
}
}

 

Cipher cloud interview experience

1st round – Team lead

  1. Advantages of using Spring DI.
  2. Explain SSL/HTTPS, how it works?
  3. Implement your own HashMap which can be replaced in Java 9.
  4. Explain Java Garbage collection?
  5. How will you make two JVMs communicate each other, make one program wait for the other (both are running in different JVMs).
  6. How serialization works.
  7. Implement reusable code for below problem – Method can take two arguments one is PATTERN other is NUMBEROFLINES
               L
		
		1
		2 3
		4 5 6
		7 8 9 10
		
		M
			    1
			   2 3
			  4 5 6
			 7 8 9 10
			
		R
				1
			      2 3
			    4 5 6
		         7 8 9 10

– Method can take args as L/M/R/LM/LR/LMR and number of lines example 4

– Code should be modularized and reusable.

2nd round – Architect

  1.  Write code which leads to thread dead lock.
  2.  Implement ArrayBlockingQueue.
  3. How Join works in multi-threading.
  4. What is reentrancy in multi-threading.
  5. Difference between wait() and sleep() methods.
  6. Explain FORK system call.
  7. Did you use messaging brokers in your projects? how they work, code level?(ActiveMQ).
  8. Explain TCP/IP protocol.
  9. How HTTP protocol works, how a packet finds its destination? routing protocols etc.
  10. Asked some Network protocols.

3rd round – Manager

  1. Write code to implement the functionality.
    • There are two databases with tables with the same name.
    • Move data from one database to other, apply following rules.
    • If a column name is age add 20 to the value.
    • If a column name is Salary add 100 to the value.
    • If column name is name then replace char ‘a’ with ‘z’ and ‘z’ with ‘b’
  2. Explain Database Normal forms, NF1, NF2, NF3 and NF4.
  3. Write code to demonstrate Composite design pattern.
  4. Difference between Struts and Spring MVC, how will you implement interceptors in both the frameworks.
  5. Did you solve any Java performance issue? tell me all the tools used to diagnose the problem.
  6. Write code to implement Singleton design pattern.
  7. Implement double ended queue in java.
  8. Implement Circular linked list, with add and remove methods.
  9. Explain how SSL/HTTPS works.
  10. How will you make some set of DB transactions ACID? explain?

4th round – Director

1. Given below code and asked to modularized.

  • The interviewer is a Geek(Indian did Ph.D. from the USA) with 15+ years of experience, knows a lot of coding standards and principles, talking to him made my day.
  • The code was unformatted, no comments, not used relevant names for variables. >> According to the interviewer, code does not need any comments to understand, variable/method names should speak everything.
  • According to the interviewer, the code does not need any comments to understand, variable/method names should speak everything.
public static void main(String [] args){
 int a = Integer.parseInt(args[0]);
 int b = Integer.parseInt(args[1]);
 int s = 0; int [] intArry;
 int val = 0;
 for(Integer i = a ; i <= b; i++){  s = i.toString().length();  intArry = new int[s];  val = i;  int j = s - 1;  while (val > 0) {
 intArry[j] = val % 10;
 val = val / 10;
 j--;
 } 
int p = 0;
 for(int i = 0; i < intArray.length(); i++){
 p += intArray[i];
 } 
if(p == i){
 System.out.println("Number is : "+ i);
 }
 }
 }

2. Find out given two strings are anagrams, write code.

  • When he asked this question I said I know this, he moved to other question.

3. Implement reusable code for below problem

When he asked this question I said this question was already asked in the first round of the interview. he moved to other question.When he asked this question I said this question was already asked in the first round of the interview. he moved to other question. – Method can take two arguments one is PATTERN other is NUMBEROFLINES

               L
		
		1
		2 3
		4 5 6
		7 8 9 10
		
		M
			    1
			   2 3
			  4 5 6
			 7 8 9 10
			
		R
				1
			      2 3
			    4 5 6
		         7 8 9 10
  • The method can take args as L/M/R/LM/LR/LMR and number of lines example 4
  • Code should be modularized and reusable.

4. Below code has a serious problem, find out and write/suggest the fix.

Class Temp{Class Temp{
A a;
void foo(){
a = new A();
a.getB().getC().doSomething();
}
}
  • This opened a discussion of 20+ minutes, there is a very interesting point he took.
  • Hint : Do not talk to Strangers.

5. Write code to demonstrate Decorator design pattern.

  • Implemented a UpperCaseBufferedreader.

6. Write code to demonstrate Abstract factory design pattern.

  • Explained the logic, did not get a chance to write code on the paper as it was 8 PM already.

Meeting room booking system design – Java and mysql

This is a famous question asked in senior level java interviews most often, here we need to demonstrate Java and DB design skills.
I believe this helps and gives some knowledge about the booking system may be ticket or hotel table booking.

Feel free to reach me in case you have any concerns over the post.

Java beans:

Here in the design, we need to understand the basic requirements like what properties can a meeting room have.

  • 1. Name
  • 2. Capacity
  • 3. Is a conference room etc

interface Room, Class MeetingRoom implements Room

Similar way we can have classes for User and a Booking, I have ignored them to make the post simple.

package oo.design;
/** *
@author nag
* */
public interface Room {
    public void setName(String name);
    public void setCapacity(int capacity);
}

package oo.design;
/** * @author nag * */
public class MeetingRoom implements Room {
 String name;
 long id;
 int capacity;
 boolean isBookable;
 boolean isPhoneAvailable;
 boolean isConferenceRoom;

 public long getId() {
  return id;
 }
 public void setId(long id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getCapacity() {
  return capacity;
 }
 public void setCapacity(int capacity) {
  this.capacity = capacity;
  }
 public boolean isBookable() {
  return isBookable;
  }
 public void setBookable(boolean isBookable) {
  this.isBookable = isBookable;
 }
 public boolean isPhoneAvailable() {
  return isPhoneAvailable;
 }
 public void setPhoneAvailable(boolean isPhoneAvailable) {
  this.isPhoneAvailable = isPhoneAvailable;
 }
 public boolean isConferenceRoom() {
  return isConferenceRoom;
 }
 public void setConferenceRoom(boolean isConferenceRoom) {
  this.isConferenceRoom = isConferenceRoom;
 }
}

Java service and DAO:

We have MeetingRoom service which has methods like bookRoom, cancelRoom, fetchAvailableRooms and fetchBookedRooms etc.

package oo.design;
import java.util.List;
/** *
@author nag
* */
interface MeetingRoomBookingService {
 public long bookRoom(long roomId, long startTime, long endTime, long userId);
 public long cancelRoomBooking(long roomId, long bookingId, long userId);
 public List<Room> getAvailableRoomsForWindow(long startTime, long endTime, long userId);
 public List<Room> getBookedRoomsForWindow(long startTime, long endTime, long userId);
}

package oo.design;
import java.util.List;
/** *
 @author nag
* */
public class MeetingRoomBookingServiceImpl implements MeetingRoomBookingService{
 MeetingRoomBookingDao roomBookingDao = new MeetingRoomBookingDaoImpl();
 @Override
 public long bookRoom(long roomId, long startTime, long endTime, long userId) {
  return roomBookingDao.bookRoom(roomId, startTime, endTime, userId);
}
 @Override
 public long cancelRoomBooking(long roomId, long bookingId, long userId) {
  return roomBookingDao.cancelRoomBooking(roomId, bookingId, userId);
 }
 @Override
 public List<Room> getAvailableRoomsForWindow(long startTime, long endTime, long userId) {
  return roomBookingDao.getAvailableRoomsForWindow(startTime, endTime, userId);
 }
 @Override
 public List<Room> getBookedRoomsForWindow(long startTime, long endTime, long userId) {
  return roomBookingDao.getBookedRoomsForWindow(startTime, endTime, userId);
 }
}

Dao:

package oo.design;
import java.util.List;
/** *
 @author Nag
* */
public interface MeetingRoomBookingDao {
public long bookRoom(long roomId, long startTime, long endTime, long userId);
 public long cancelRoomBooking(long roomId, long bookingId, long userId); public List<Room> getAvailableRoomsForWindow(long startTime, long endTime, long userId);
 public List<Room> getBookedRoomsForWindow(long startTime, long endTime, long userId);
}

package oo.design;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/** *
 @author nag
 * */
public class MeetingRoomBookingDaoImpl implements MeetingRoomBookingDao {
 private static final String DATABASE_USER = "nag";
 private static final String DATABASE_PASSWORD = "nagpwd";
 private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
 private static final String DATABASE_CONNECTION = "jdbc:mysql://localhost:3306/wpdemo?autoReconnect=true&useSSL=false";
 @Override
 public long bookRoom(long roomId, long startTime, long endTime, long userId) {
  Connection dbConnection = null;
PreparedStatement preparedStatement = null;
  String insertTableSQL = "INSERT INTO T_MEETING_ROOM_BOOKING"
                           + "(F_ROOM_ID, F_USER_ID, F_START_TIME, F_END_TIME, F_IS_ACTIVE, F_CREATED_TIMESTAMP) "
                           + "VALUES" + "(?,?,?,?,?, UNIX_TIMESTAMP())";
  try {
     dbConnection = getDBConnection();
     preparedStatement = dbConnection.prepareStatement(insertTableSQL);
     preparedStatement.setLong(1, roomId);
     preparedStatement.setLong(2, userId);
     preparedStatement.setLong(3, startTime);
     preparedStatement.setLong(4, endTime);
     preparedStatement.setLong(5, 1);
     preparedStatement.executeUpdate();
   } catch (SQLException e) {
      System.out.println(e.getMessage());
   } finally {
   }
   return 0;
  }
 @Override
 public long cancelRoomBooking(long roomId, long bookingId, long userId) {
   // update the status F_IS_ACTIVE flag to 0 return 0;
 }
 @Override
 public List<Room> getAvailableRoomsForWindow(long startTime, long endTime, long userId) {
    Connection dbConnection = null;
PreparedStatement preparedStatement = null;
    List<Room> availableRooms = new ArrayList<>();
    String selectSQL = "SELECT * FROM T_MEETING_ROOM WHERE F_ID NOT IN (SELECT F_ROOM_ID FROM T_MEETING_ROOM_BOOKING WHERE F_START_TIME BETWEEN ? AND ? or F_END_TIME BETWEEN ? AND ?)";
    try {
      dbConnection = getDBConnection();
      preparedStatement = dbConnection.prepareStatement(selectSQL);
      preparedStatement.setLong(1, startTime);
      preparedStatement.setLong(2, endTime);
      preparedStatement.setLong(3, startTime);
      preparedStatement.setLong(4, endTime);
      ResultSet rs = preparedStatement.executeQuery();
      while (rs.next()) {
         MeetingRoom room = new MeetingRoom();
         room.setId(rs.getLong("F_ID"));
         room.setName(rs.getString("F_NAME"));
         availableRooms.add(room);
      }
    }catch(Exception e){
  } return availableRooms;
 }
 @Override
 public List<Room> getBookedRoomsForWindow(long startTime, long endTime, long userId) {
    Connection dbConnection = null;
PreparedStatement preparedStatement = null;
List<Room> bookedRooms = new ArrayList<>();
    String selectSQL = "SELECT * FROM T_MEETING_ROOM WHERE F_ID IN (SELECT F_ROOM_ID FROM T_MEETING_ROOM_BOOKING WHERE F_START_TIME BETWEEN ? AND ? or F_END_TIME BETWEEN ? AND ?)";
    try {
       dbConnection = getDBConnection();
       preparedStatement = dbConnection.prepareStatement(selectSQL);
       preparedStatement.setLong(1, startTime);
       preparedStatement.setLong(2, endTime);
       preparedStatement.setLong(3, startTime);
       preparedStatement.setLong(4, endTime);
       ResultSet rs = preparedStatement.executeQuery();
       while (rs.next()) {
          MeetingRoom room = new MeetingRoom();
          room.setId(rs.getLong("F_ID"));
          room.setName(rs.getString("F_NAME"));
          bookedRooms.add(room);
        }
    }catch(Exception e){
    }
   return bookedRooms;
 }
 private static Connection getDBConnection() {
    Connection dbConnection = null;
    try {
      Class.forName(DATABASE_DRIVER);
    } catch (ClassNotFoundException e) {
      System.out.println(e.getMessage());
    } try {
      dbConnection = DriverManager.getConnection(DATABASE_CONNECTION, DATABASE_USER, DATABASE_P ASSWORD);
      return dbConnection;
    } catch (SQLException e) {
       System.out.println(e.getMessage());
    }
   return dbConnection;
 }
}

Database scripts:

create database wpdemo;
use wpdemo;
CREATE TABLE T_USER (
    F_ID BIGINT AUTO_INCREMENT PRIMARY KEY,
    F_FNAME VARCHAR(30),
    F_LNAME VARCHAR(30),
    F_EMAIL VARCHAR(30),
    F_PHONE VARCHAR(30),
    F_CREATED_TIMESTAMP LONG
);
insert into T_USER (F_FNAME, F_LNAME, F_EMAIL, F_PHONE, F_CREATED_TIMESTAMP)
 values ('Nag', 'B', 'nag.wordpress@gmail.com', '9898989898', UNIX_TIMESTAMP()); 
commit;

CREATE TABLE T_MEETING_ROOM (
    F_ID BIGINT AUTO_INCREMENT PRIMARY KEY,
    F_NAME VARCHAR(30),
    F_CAPACITY INT,
    F_IS_BOOKABLE INT,
    F_IS_PHONE_AVAILABLE INT,
    F_IS_CONFERENCEROOM INT,
    F_CREATED_TIMESTAMP LONG
);
insert into T_MEETING_ROOM (F_NAME, F_CAPACITY, F_IS_BOOKABLE, F_IS_PHONE_AVAILABLE, F_IS_CONFERENCEROOM, F_CREATED_TIMESTAMP)
 values ('Room no 1', 10, 1, 1, 1, UNIX_TIMESTAMP()); 
insert into T_MEETING_ROOM (F_NAME, F_CAPACITY, F_IS_BOOKABLE, F_IS_PHONE_AVAILABLE, F_IS_CONFERENCEROOM, F_CREATED_TIMESTAMP)
 values ('Room no 2', 5, 1, 0, 0, UNIX_TIMESTAMP()); 

CREATE TABLE T_MEETING_ROOM_BOOKING (
    F_ID BIGINT AUTO_INCREMENT PRIMARY KEY,
    F_ROOM_ID BIGINT,
    F_USER_ID BIGINT,
    F_START_TIME LONG,
    F_END_TIME LONG,
    F_IS_ACTIVE INT,
    F_CREATED_TIMESTAMP LONG,
    FOREIGN KEY (F_ROOM_ID)
        REFERENCES T_MEETING_ROOM (F_ID)
        ON DELETE CASCADE,
    FOREIGN KEY (F_USER_ID)
        REFERENCES T_USER (F_ID)
        ON DELETE CASCADE
);

Main method:

package oo.design;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
/** *
@author Nag
 * */
public class MeetingRoomBookingMain {
 public static MeetingRoomBookingService roomBookingService = new MeetingRoomBookingServiceImpl();
 public static void main(String[] args) {
   String startDateTime = "02/09/2017 09:00:00";
   String endDateTime = "02/09/2017 10:00:00";
   roomBookingService.bookRoom(1, getDateInMilliSeconds(startDateTime), getDateInMilliSeconds(endDateTime) - 1, 1);
   String startDateTime2 = "02/09/2017 10:00:00"; String endDateTime2 = "02/09/2017 11:00:00";
   roomBookingService.bookRoom(1, getDateInMilliSeconds(startDateTime2), getDateInMilliSeconds(endDateTime2) - 1, 1);
   String startDateTime3 = "02/09/2017 11:00:00"; String endDateTime3 = "02/09/2017 12:00:00";
   List<Room> availableRooms = roomBookingService.getAvailableRoomsForWindow(getDateInMilliSeconds(startDateTime3), getDateInMilliSeconds(endDateTime3), 1);
   System.out.println("Available rooms");
   for (Room room : availableRooms) {
     System.out.println(((MeetingRoom)room).getId()+" - "+((MeetingRoom)room).getName());
   }
   List<Room> bookedRooms = roomBookingService.getBookedRoomsForWindow(getDateInMilliSeconds(startDateTime3), getDateInMilliSeconds(endDateTime3), 1);
   System.out.println("Booked rooms");
   for (Room room : bookedRooms) {
     System.out.println(((MeetingRoom)room).getId()+" - "+((MeetingRoom)room).getName());
   }
 }
 public static long getDateInMilliSeconds(String dateStr) {
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("IST"));
   Date date = new Date(); Calendar cal = Calendar.getInstance();
   try {
    date = sdf.parse(dateStr + " 23:59:59");
    cal.setTime(date);
   } catch (ParseException e) {
       cal.setTime(date);
       cal.add(Calendar.DATE, 10);
       return cal.getTimeInMillis() / 1000;
    }
   return cal.getTimeInMillis() / 1000;
 }
}