Posts

Showing posts from March, 2020

What is Web Servies

Web Services: * Web service is a technology is used to communicate different application. (May be developed with different language). * Two major web services are there, 1. SOAP 2. REST

What is Servlet & Use of Servlet & Execution Methods

Java Servlets: * In todays world people are going for web application. Not system based application. * To create web application we should understanding what is Servlet. Use of Servlet: * To Build a web application. * This is used to handle request from the web server, process the request, produce the response and send response back to web server. Servlet Execution Methods: * Client send the request to web server. * Web server receive the request. * Web server pass the request to corresponding server. * Servlet process and request and produce the response. * Servlet send the response back to web server. * Server send the response back to client. * Client browser display it on screen(UI).

Power Mockito

What is PowerMockito? Mockito is not providing us to mock private fields, static methods and constructors. But using PowerMockito we can achieve that as well.

Mockito

What is Mockito? Instead of stub some dummy response using dummy class. Mock class provide all that for us. We can mock any class or interfaces. Mock: It will mock the whole class. We have to stub all the methods. Spy : * Spy is nothing but it will create the real class. But we can stub any specific method alone. Other methods will work normally. * We can verify also . * Mostly will not use. Because it is maintain complex because half is real values half is stub. * Very old system no other option, will use this spy. @RunWith(MockitoJunitRunner.class) This is used to make the class as mockito test class. @Mock It is used to mock particular class. @InjectMock Injected mock classes into this class.

Junit - Classes

What are the Junit classes are available? org.junit.Assert: It is providing some of assertion methods. If this assertions are passed in the test class, then it is assume that test result is pass. Eg. assertEquals, assertFalse, assertNotNull, assertNull, assertTrue etc., org.junit.TestCase It is used to run many test, TestCase class in this packages. org.junit.TestResult When you execute a test, it returns a result (in the form of TestResult object). This TestResult object can be used to analyse the total result object. This test will be failure or successful. org.junit.TestSuite If you want to run the multiple test cases in order, and that order should maintain in one place. That place is called test suite. eg.  @RunWith(Suite.class) @SuiteClasses(Test1.class, Test2.class, ...)

Junit - TestRunner

What is TestRunner.java? * To execute our junit class we need test runner. It will help us to provide our junit class is success or failure. * Using JUnitCore will run our junit test class.

Junit & Basic Annotations

What is Junit: Junit is the testing framework used to test Java application. @Test * It is used to mention the method as test method in the test class. @BeforeClass * Before annotation is used to load any specific data before loading test cases only once. eg. create database connection @Before * Before annotation is used to load any specific data before loading each test cases. eg. create Values @After * After annotation is used to load any specific data after loading the test cases. eg. Deleting the values @AfterClass * Before annotation is used to load any specific data after loading test cases only once. eg. closing database connection @Ignore * If you want to ignore some method in the test class then will use. @Test(timeout=500) * When you dont want to wait for other system for more time then will use this. @Test(expected=IllegalArgumentException.class) * Error Handling. If you want to check particular method is throwing IllegalArgumentException or not.

Set the Environment path for Java:

* Go to my computer. Right click on computer and go to properties. * In Left side, Click Advance System Setting. * Under Advanced tab, click Environment Variables. * Go to system variable, click path add the bin path into this path with ; separator. * Now open command prompt check Java is installed or not  using "javac" command

Java or JDK Installation

Java or JDK Installation: Steps :  * Go to this url: https://www.oracle.com/java/technologies/javase-downloads.html * Click JDK download * Go to your OS specific and download the exe file. * Click on exe file in your system. * By default installation directory will be like this "C:\Program Files\Java\jdk-13.0.XXX"

What is Unit Test & Mockito & PowerMockito

What is Unit testing? As a developer you want to know your codes are working perfectly atleast for positive scenarios. To check that developer has to do unit testing.      As a developer you cannot test all the functionality which other system provides. For example:If you are calling the service of other system which may impact the database level. So in the unit testing code you cannot call the service everytime. It is very expensive. So to avoid that we are just stub some success response from other system response. It means response hardcoded. So that we can test all our codes. What is Mockito? Instead of stub some dummy response using dummy class. Mock class provide all that for us. We can mock any class or interfaces. What is PowerMockito? Mockito is not providing us to mock private fields, methods and constructors. But using PowerMockito we can achieve that as well.

GIT

GIT: GIT is called as Distributed version control system. Created by Linus Torvald Why we need GIT? Case 1 :When you are developing the project alone                  You developed one project and its running successfully. After some days you thought of adding some features into that, then again you added that features in to your old project code. You released multiple version to production like project 1.0, project 1.1, project 1.2, project 1.3 .So you will store all this into one folder. To maintain all this we have a tool called version control.                Earlier we used centralized storage. So everything stored in the server . If server fails , that all we will not have any code.  Now we will keep code in server (Remote repository) and in your local machine(local repository) . So if your server clash also, no problem. you can get it from you or any other system. This...

Java - Idempotence

Idempotence: Produce same result on the server side that is called idempotence. Eg: When we call PUT & DELETE operation on multiple time the result will be same in the server

Java - Request Param vs Path Variable

Request Param: Extract query parameter Used in web application mostly Eg: http://localhost:8080/portal/book?id=123 Path Variable: Extract data right from the URI Used in REST webservices Eg: http://localhost:8080/portal/book/123

Response Code & Meaning

200 - Success 204 - No content 404 - Resource Not Found 400 - Bad Request 401 - Unauthorized 403 - Forbidden 415 - Unsupported Media Type 500 - Server Error 501 - Not Implemented

Spring Boot - application.properties Configuration

Image
Static Resource Caching: Spring.freemarker.cache = true; // Will do only in Production. Automatic-UI-refresh:   Default It is enable Spring.devtools.livereload.enabled = false; Server Restart: Spring.devtools.restart.enabled = false; Using Trigger File: If you want to control, If any specific file changes happens then only it should restart automatically and your changes should apply. Spring.devtools.restart.trigger-file = c:/workspace/trigger.txt;

Spring Boot - Dev Tools

What is the use of Spring boot dev tools ?   Useful to auto reload of UI in browser, whenever there is change in some code.

Spring Boot Starters

What are the spring Boot Starters are there ? <gson.version> <h2.version> <httpClient.version> <httpCore.version> <Jackson.version> <Javax-json.version> <Javax-mail.version> <junit.version> <mysql.version> <slf4j.version> etc., <parent>    <groupId>org.springframework.boot </groupId>    <artifactId> spring-boot-dependencies </artifactId>    <version>  </version> </parent>

Spring - Scope

There are 5 scopes are there in Spring, Singleton - It returns single bean instance per IOC container. Stored in cache. Prototype - It returns a new bean instance each time when requested. Request - It returns single bean instance per HTTP request. Session  - It returns single bean instance per HTTP session. (User Level) Global Session - It returns single bean instance per global HTTP session. (Application Level)

Hibernate - Eager & Lazy

If you are not mentioning anything FetchType.LAZY is a default. Eager: It will load all the relationship tables. Lazy: It will load only particular object instance. It will initialized when its explicitly called by getter methods  (to fetch more tables) Eg: When loading login page, no need of user details tables, just we need user table to check the username & password. As we know to get all the relations is very expensive. 

Hibernate - Query & Catching

Hibernate Query: String sql = "from employee"; Query query = session.createQuery(sql); query.setFirstResult(1); query.setMaxResults(10); List results = query.list(); How to set Catching in Hibernate: query.setCacheable(true);

Spring - BeanFactory & ApplicationContext

BeanFactory vs ApplicationContext: Both are used to get beans from your spring IOC container. Both are Java interfaces. ApplicationContext extends BeanFactory. BeanFactory - IOC Basic ApplicationContext - DI advanced BeanFactory is LazyLoading and ApplicationContext is Aggressive Loading. ApplicationContext support internalization.

Hibernate - Transaction Management

Transaction Management: Transaction management is controlling the transaction at run time time. For Example, Transaction management code has to decide if transaction get success what need to do and transaction is failed how to catch and what need to do  Eg: Session s= null; Transaction t =null; try{ s = sessionFactory.openSession(); t =session.beginTransaction(); // Actual SQL Activities Need to do here. t.commit(); } catch(Exception e){ t.rollback(); } finally{ s.close(); }

Hibernate - SessionFactory & Session

SessionFactory is a factory class for session objects. SessionFactory will available for whole application but session will available for a single transaction. SessionFactory is thread safe but session is not thread safe. SessionFactory will create using,  Configuration.buildSessionFactory() 

Spring - Global Exception Handling

Spring Global Exception Handling ? @ControllerAdvice @ExceptionHandler    

Hibernate - Session Load & get

Session.load(): It is return a proxy value without hitting database. If now row found, throw an ObjectNotFound Exception. It is an object. Session.get(): Always hit the database and return real object. If no row, it return null.

Spring - Why Spring Bean is Singleton

Why Spring Bean is default Singleton ? Stateless Bean rules is the reason for that.    .If you not going to hold the state data in beans then its enough to have only one instance of each bean. And when the service is stateless its thread safe. So spring have only stateless bean. Eg: Connection of Database . 

Spring - Interface

Why interface in Spring: As we know, the core concept of spring is DI. To achieve this we have to go for interface. And Interface gives us better readability. And we can give multiple implementation and we can use to inject in another bean using qualifier seperation. eg. @Autowired @Qualifier ("jdbcdevice") private DeviceDao device;      (or) @Resource(name = "jdbcdevice") private DeviceDao device;

Java - Numeric promotion

Numeric Promotion: To calculate easily convertion of smaller numeric type into large numeric. eg.   byte,char,short to int   int to long long,float to double

Hibernate - Session Factory opensession & getcurrentsession

SessionFacoty.openSession(): It always create a new session object. You need to explicitly flush and close session object. You no need to configure any property to call this method. SessionFactory.getCurrentSession(): It create new session if not exists, else use the same session which is in current hibernate context. You no need to flush and close. Internally Hibernate will take care. You need to configure property,        "hibernate.current_session_context_class" <session-factory>     <property name="hibernate.current_session_context_class" >     </property> </session-factory>

Hibernate - @Transactional

What is the use of @Transactional ? In the middle of transaction if it is calling another business logic, it is the option of joining the transaction. This is much readable & recommended.    Transaction propagation are handled automatically (Propagation = REQUIRED)  - Create new if not exist old.

Spring - MVC Configuration

MVC Configuration Class: @Configuration @EnableWebMVC @ComponentScan( basepackage= "com.test.app") @Bean public viewResolver viewResolver(){ InternalViewResolver view = new InternalViewResolver(); view.setprefix(""); view.setsuffix(".jsp"); }

Spring - Actuator

Actuator: It allows you to see inside the application. For Example, If you want to know which beans are created in spring application context and how the controllers are mapped. Endpoints: /shutdown to kill spring boot application. /env  list of properties /health  health information /beans  list of spring bean etc., Dependency: <artifactId> spring-boot-starter-actuator </artifactId>

Spring - Initilizer

Spring Initilizer :    For a Developer to create a application from scratch it will help. URL : start.spring.io

What & Why Spring Boot

What is Spring Boot ? Spring boot is also one of the Java Framework to simplify the java development. Why Spring Boot ? Lot of Autoconfiguration. So it improves productivity Developer can focus on business logic.  For example, you no need to setup the tomcat in spring boot. It is embedded in Spring boot. Spring Boot Features: Starter Dependency Auto configuration Spring Initializer  @Spring Boot Application = @Configuration + @ComponentScan + @EnableAutoconfiguration

JPA

JPA: Java Persistance API JPA is not a tool or framework. It is a set of Concepts For Example, In you application you are using the ORM tool as Hibernate. In future if you wan to switch the ORM tool from hibernate to iBatics, you can switch easily if you are using JPA.

Spring - Flow

Image

Spring - Modules

Spring Core: Provide fundamental parts DI & IOC Data Access: It consists of JDBC, ORM & Transaction Management Web: Related to web application. It has Web Services, Web Servlet Module AOP: It means Aspect Oriented Programing. When you want to do some common operation for all the services then will use this. For Example, Logging, Authorization etc  Test: It is used in the part of Unit/Integration testing It is used in the Mocking as well.

Spring - @Component

What is the use of @Component?     Registered in context as a Bean.

Spring - Singleton & Prototype

Spring-Singleton:     If you set once, it will return when you are calling the same bean. Spring-Prototype:     It will create and return whenever you are calling the bean.

Spring - Types of DI

Types of DI: * Constructor Based If you achieve the DI using Constructor then it is called Constructor based DI Class Driver{ private Licence licence; @Autowired public Driver(Licence licence){ this.licence = licence; } } * Setter Based If you achieve the DI using Setter method then it is called Constructor based DI Class Driver{ private Licence licence; @Autowired public void setLicence(Licence licence){ this.licence = licence; } }

Spring - DI & IOC

Image
DI & IOC: * Dependency injection is the concept where one object is loosely coupling with another object is called DI. * In Spring with the help of IOC container we are achieving this. It is responsible to do for us to give DI in our application. * Dependency Invertion is the concept, that is where we are creating Interface or abstract class, then we will give the implementation, then using spring will autowired the bean. Advantages : 1. Loosely coupling. 2. Testing

Spring - What is Spring & Advantages of Spring ?

What is Spring? Light weight framework It supports other frameworks like Struts, Hibernate etc., It supports modules like IOC, AOP, ORM, MVC etc., Advantages? It provides predefined templates We can achieve Loosely couple using DI It is used to developers to focus more on Business part. Easy to test the application

Java - Versions

Java 1.1: Inner Class JDBC RMI Java 1.2: Swing Set, Map, Collection Java 1.3: HotSpot JVM JNDI Java 1.4: IPV6 Regular Expression Java 1.5: Generics (Type Safety) Auto Boxing & Auto Unboxing Enumeration Var args For-each Static import Java 1.6: JDBC 4 Scriplet Language Support Java 1.7: Switch in String Automatic resource management Catch multiple exception Improved type interface Java 1.8: We can define a method inside the interface Lambda expression Stream API Date & Time API Embed JavaScript code with application Repeating Annotation

Java - Allow Duplicate in HashMap

Map<String, List<String>> map = new HashMap<>(); List<String> list = new ArrayList<>(); Java 7: Adding: map.put ( "key1", list ); map.get( "key1" ). add ("value1"); map.get( "key1" ). add ("value2"); Retrieving: map.get( "key1" ).get(0); map.get( "key1" ).get(1); Java 8: map.computeIfAbsent ( "key1", k -> new ArrayList<>()).add( "value1" );

Java - Blocking Queue

Blocking Queue:    It is a queue. It will work as a producer consumer concept queue. BlockingQueue<Message> queue = new ArrayBlockingQueue<>(10);

Java - Cyclic Barrier

Cyclic Barrier:   When multiple threads carry a different sub tasks and the output of these sub tasks need to be combined in the form of final output. public static CyclicBarrier newBarrier = new CyclicBarrier(3); Tester newBarrier.await();

Database - TRUNCATE & DELETE

create table cric ( id int identity ( 1 , 2 ), cname varchar ( 30 )) insert into cric values ( 'siva' ) insert into cric values ( 'Ranbhir' ) insert into cric values ( 'Karthik' ) select * from cric --the identity automatically assigns the value to the id. it starts with 1 and increment by 2. delete from cric insert into cric values ( 'siva' ) insert into cric values ( 'Ranbhir' ) insert into cric values ( 'Karthik' ) select * from cric --delete does not deletes the identity of the table. truncate table cric insert into cric values ( 'siva' ) insert into cric values ( 'Ranbhir' ) insert into cric values ( 'karthik' ) select * from cric --truncate deletes the identity of the table.

Database- VIEWS

A view is an "Virtual Table" . It is not like a simple table , this is an virtual   table which contains columns and data from different table ( may be one or more   tables ) . View does not contain any data directly , it is a set of query that are   applied to one or more tables that is stored within the database as object . After creating a view from some Table , it just used as a reference of those table and when executed shows only those data which are already mention in query during the creation   of View .   use of view :-       Views are used as Security Mechanism of Database . Because it restricts user to view certain column and Rows .   Views display only those data which are mentioned in the query ,   so its shows only those data which returns by the query that is defined   at the time of creation of view . So rest data are t...

Database - CURSOR

  Cursor is a pointer for easy traversal . There are two types of cursor . 1.ANSI Cursor --> Single row Forward only Cursor -- It will return -1 (You can move next(forward)only 2.Enhanced Cursor ( scroll cursor ) --> Multiple rows.It can move either direction. You can use Next , Prior , last , first , Absoloute , relative Life Cycle of Cursor :- ~~~~~~~~~~~~~~~~       1. Declare the cursor       2. Open the cursor       3. fetch the cursor          4. close the cursor       5. deallocate the cursor create table empsiva3 ( empno int , ename varchar ( 20 )) insert into empsiva3 values ( 1 , 'siva' ) insert into empsiva3 values ( 2 , 'Ranbhir' ) insert into empsiva3 values ( 3 , 'Imrankhan' ) insert into empsiva3 values ( 4 , 'Karthik' ) select * from empsiva3 De...

Database - TRIGGERS

Trigger is a special type of store procedure which will "fire" automatically . T riggers are used to assess/evaluate data before or after data modification using DDL and DML statements. 3 main types of triggers are :       1. Insert Trigger       2. Update Trigger       3. Delete Trigger create table empsiva ( empno int , ename varchar ( 20 )) insert into empsiva values ( 1 , 'Vinoth' ) insert into empsiva values ( 2 , 'Ranbhir' ) insert into empsiva values ( 3 , 'Raju' ) insert into empsiva values ( 4 , 'Kumar' ) select * from empsiva delete   from empsiva 'Insert Trigger'      - trigger for insert statement create trigger Emp_trs on empsiva for insert As if ( select count (*) from empsiva a , inserted b where a . empno = b . empno )> 1 Begin       Print ' Employee No...