Immutable Classes and REST API Guide
Immutable Classes and REST API Guide
Ans) a. Make your class final, so that no other classes can extend it.
[Link] all your fields final, so that they’re initialized only once inside
the constructor and never modified afterward.
[Link]’t expose setter methods.
[Link] exposing methods which modify the state of the class, you must
always return a new instance of the class.
3. it must be reflexive and transitive: that is, [Link](y) must return the
same value as [Link](x), and if [Link](y) and [Link](z), then
[Link](z) must also be true (see below for what this actually means in
real terms!).
In this tutorial you will learn how to identify and implement a set of REST
endpoints that expose your module features through web-services.
books
requisitions
…
These resources identify the data entities that your user interface will
need to display to the user so that he can interact with the application
and perform all the necessary use cases.
Now that you identified all the necessary resources to expose, you need
to identify their respective locations.
{
"title": "The Hobbit",
"isbn": 3423123421213
}
{
"id": 1542341141,
"title": "The Hobbit",
"isbn": 3423123421213
}
A REST API normally operates with the exchange of resources that are
externalized through a particular data notation. As you’ve seen in the
previous steps, we are big fans of the JSON (JavaScript Object Notation).
This is because our client-side front-end technologies are mainly
Javascript-based, and it becomes easier to create and parse data in this
JSON format.
Before you get to implement the endpoints that you identified in the
previous step, you must provide externalizations of your application
resources using an interchangeble notation like JSON. The Bennu
infrastructure provides a library that eases that externalization through
the implementation of three interfaces:
@DefaultJsonAdapter([Link])
public class BookAdapter implements JsonAdapter<Book> {
@Override
public Book create(JsonElement jsonElement, JsonBuilder ctx) {
final JsonObject json = [Link]();
String name = [Link]("title");
String isbn = [Link]("isbn");
return [Link](title, isbn);
}
@Override
public Book update(JsonElement jsonElement, Book book, JsonBuilder
ctx) {
final JsonObject json = [Link]();
String name = [Link]("title");
String isbn = [Link]("isbn");
return [Link](title, isbn);
}
@Override
public JsonElement view(Book book, JsonBuilder ctx) {
final JsonObject json = new JsonObject();
[Link]("id", [Link]());
[Link]("title", [Link]());
[Link]("isbn", [Link]());
return json;
}
}
Now that you identified the necessary endpoints, you should implement
them on the server side, consuming the domain information in order to
produce JSON responses to invocations on those endpoints. The Bennu
infrastructure uses a library that eases this task, which is the bennu-json
library.
@POST
@Path("/orders")
@Produces(MediaType.APPLICATION_JSON)
public String createOrder(JsonElement jsonElement) {
accessControl("#users");
return create(jsonElement);
}
...
}
Ans) In an left outer join, all rows from the first table mentioned in the
SQL query is selected, regardless whether there is a matching row on the
second table mentioned in the SQL query. Let's assume that we have the
following two tables,
Table Store_Information
Store_Nam Sale
Txn_Date
e s
Jan-05-
Los Angeles 1500
1999
Jan-07-
San Diego 250
1999
Jan-08-
Los Angeles 300
1999
Jan-08-
Boston 700
1999
Table Geography
Region_Nam Store_Nam
e e
East Boston
East New York
West Los Angeles
West San Diego
We want to find out sales by store, and we want to see the results for all
stores regardless whether there is a sale in
the Store_Information table. To do this, we can use the following SQL
statement using LEFT OUTER JOIN:
SALE
STORE
S
Los
1800
Angeles
San Diego 250
New York NULL
Boston 700
By using LEFT OUTER JOIN, all four rows in the Geography table is
listed. Since there is no match for "New York" in
the Store_Information table, the Sales total for "New York" is NULL.
Note that it is NULL and not 0, as NULL indicates there is no match
@Controller
This annotation is used on Java classes that play the role of
controller in your application. The @Controllerannotation allows
autodetection of component classes in the classpath and auto-
registering bean definitions for them. To enable autodetection of
such annotated controllers, you can add component scanning to
your configuration. The Java class annotated with @Controller is
capable of handling multiple request mappings.
This annotation can be used with Spring MVC and Spring WebFlux.
@RequestMapping
This annotation is used both at class and method level.
The @RequestMapping annotation is used to map web requests
onto specific handler classes and handler methods.
When @RequestMapping is used on class level it creates a base
URI for which the controller will be used. When this annotation is
used on methods it will give you the URI on which the handler
methods will be executed. From this you can infer that the class
level request mapping will remain the same whereas each handler
method will have their own request mapping.
Sometimes you may want to perform different operations based on
the HTTP method used, even though the request URI may remain
the same. In such situations, you can use the method attribute
of @RequestMapping with an HTTP method value to narrow down
the HTTP methods in order to invoke the methods of your class.
Here is a basic example on how a controller along with request
mappings work:
@Controller
@RequestMapping("/welcome")
@RequestMapping(method = [Link])
@CookieValue
This annotation is used at method parameter
level. @CookieValue is used as argument of request mapping
method. The HTTP cookie is bound to the @CookieValue parameter
for a given cookie name. This annotation is used in the method
annotated with @RequestMapping.
Let us consider that the following cookie value is received with a
http request:
JSESSIONID=418AB76CD83EF94U85YD34W
To get the value of the cookie, use @CookieValue like this:
@RequestMapping("/cookieValue")
@CrossOrigin
This annotation is used both at class and method level to enable
cross origin requests. In many cases the host that serves JavaScript
will be different from the host that serves the data. In such a case
Cross Origin Resource Sharing (CORS) enables cross-domain
communication. To enable this communication you just need to add
the@CrossOrigin annotation.
By default the @CrossOrigin annotation allows all origin, all
headers, the HTTP methods specified in
the@RequestMapping annotation and maxAge of 30 min. You can
customize the behavior by specifying the corresponding attribute
values.
An example to use @CrossOrigin at both controller and handler
method levels is this.
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
@CrossOrigin(origins = "[Link]
@RequestMapping("/message")
// ...
@RequestMapping("/note")
// ...
}
Composed @RequestMapping
Variants
Spring framework 4.3 introduced the following method-level
variants of @RequestMapping annotation to better express the
semantics of the annotated methods. Using these annotations have
become the standard ways of defining the endpoints. They act as
wrapper to @RequestMapping.
These annotations can be used with Spring MVC and Spring
WebFlux.
@GetMapping
This annotation is used for mapping HTTP GET requests onto
specific handler methods. @GetMapping is a composed annotation
that acts as a shortcut
for @RequestMapping(method = [Link])
@PostMapping
This annotation is used for mapping HTTP POST requests onto
specific handler methods. @PostMapping is a composed annotation
that acts as a shortcut
for @RequestMapping(method = [Link])
@PutMapping
This annotation is used for mapping HTTP PUT requests onto
specific handler methods. @PutMapping is a composed annotation
that acts as a shortcut
for @RequestMapping(method = [Link])
@PatchMapping
This annotation is used for mapping HTTP PATCH requests onto
specific handler methods. @PatchMapping is a composed
annotation that acts as a shortcut for @RequestMapping(method =
[Link])
@DeleteMapping
This annotation is used for mapping HTTP DELETE requests onto
specific handler methods. @DeleteMapping is a composed
annotation that acts as a shortcut
for @RequestMapping(method = [Link])
@ExceptionHandler
This annotation is used at method levels to handle exception at the
controller level. The @ExceptionHandlerannotation is used to
define the class of exception it will catch. You can use this
annotation on methods that should be invoked to handle an
exception. The @ExceptionHandler values can be set to an array of
Exception types. If an exception is thrown that matches one of the
types in the list, then the method annotated with
matching @ExceptionHandler will be invoked.
@InitBinder
This annotation is a method level annotation that plays the role of
identifying the methods which initialize theWebDataBinder -
a DataBinder that binds the request parameter to JavaBean objects.
To customise request parameter data binding , you can
use @InitBinder annotated methods within our controller. The
methods annotated with @InitBinder all argument types that
handler methods support.
The @InitBinder annotated methods will get called for each HTTP
request if you don’t specify the value element of this annotation.
The value element can be a single or multiple form names or
request parameters that the init binder method is applied to.
@MatrixVariable
This annotation is used to annotate request handler method
arguments so that Spring can inject the relevant bits of matrix URI.
Matrix variables can appear on any segment each separated by a
semicolon. If a URL contains matrix variables, the request mapping
pattern must represent them with a URI template.
The@MatrixVariable annotation ensures that the request is
matched with the correct matrix variables of the URI.
@PathVariable
This annotation is used to annotate request handler method
arguments. The @RequestMapping annotation can be used to
handle dynamic changes in the URI where certain URI value acts as
a parameter. You can specify this parameter using a regular
expression. The @PathVariable annotation can be used declare this
parameter.
@RequestAttribute
This annotation is used to bind the request attribute to a handler
method parameter. Spring retrieves the named attributes value to
populate the parameter annotated with @RequestAttribute. While
the @RequestParamannotation is used bind the parameter values
from query string, the @RequestAttribute is used to access the
objects which have been populated on the server side.
@RequestBody
This annotation is used to annotate request handler method
arguments. The @RequestBody annotation indicates that a method
parameter should be bound to the value of the HTTP request body.
The HttpMessageConveter is responsible for converting from the
HTTP request message to object.
@RequestHeader
This annotation is used to annotate request handler method
arguments. The @RequestHeader annotation is used to map
controller parameter to request header value. When Spring maps
the request, @RequestHeader checks the header with the name
specified within the annotation and binds its value to the handler
method parameter. This annotation helps you to get the header
details within the controller class.
@RequestParam
This annotation is used to annotate request handler method
arguments. Sometimes you get the parameters in the request URL,
mostly in GET requests. In that case, along with
the @RequestMapping annotation you can use
the @RequestParam annotation to retrieve the URL parameter and
map it to the method argument. The@RequestParam annotation is
used to bind request parameters to a method parameter in your
controller.
@RequestPart
This annotation is used to annotate request handler method
arguments. The @RequestPart annotation can be used instead
of @RequestParam to get the content of a specific multipart and
bind to the method argument annotated with @RequestPart. This
annotation takes into consideration the “Content-Type” header in
the multipart(request part).
@ResponseBody
This annotation is used to annotate request handler methods.
The @ResponseBody annotation is similar to
the@RequestBody annotation. The @ResponseBody annotation
indicates that the result type should be written straight in the
response body in whatever format you specify like JSON or XML.
Spring converts the returned object into a response body by using
the HttpMessageConveter.
@ResponseStatus
This annotation is used on methods and exception
classes. @ResponseStatus marks a method or exception class with
a status code and a reason that must be returned. When the
handler method is invoked the status code is set to the HTTP
response which overrides the status information provided by any
other means. A controller class can also be annotated
with @ResponseStatus which is then inherited by
all @RequestMapping methods.
@ControllerAdvice
This annotation is applied at the class level. As explained earlier,
for each controller you can use@ExceptionHandler on a method
that will be called when a given exception occurs. But this handles
only those exception that occur within the controller in which it is
defined. To overcome this problem you can now use
the@ControllerAdvice annotation. This annotation is used to
define @ExceptionHandler, @InitBinder and@ModelAttribute meth
ods that apply to all @RequestMapping methods. Thus if you define
the @ExceptionHandlerannotation on a method
in @ControllerAdvice class, it will be applied to all the controllers.
@RestController
This annotation is used at the class level.
The @RestController annotation marks the class as a controller
where every method returns a domain object instead of a view. By
annotating a class with this annotation you no longer need to
add @ResponseBody to all the RequestMapping method. It means
that you no more use view-resolvers or send html in response. You
just send the domain object as HTTP response in the format that is
understood by the consumers like JSON.
@RestController is a convenience annotation which
combines @Controller and @ResponseBody .
@RestControllerAdvice
This annotation is applied on Java
classes. @RestControllerAdvice is a convenience annotation which
combines @ControllerAdvice and @ResponseBody. This annotation
is used along with the @ExceptionHandler annotation to handle
exceptions that occur within the controller.
@SessionAttribute
This annotation is used at method parameter level.
The @SessionAttribute annotation is used to bind the method
parameter to a session attribute. This annotation provides a
convenient access to the existing or permanent session attributes.
@SessionAttributes
This annotation is applied at type level for a specific handler.
The @SessionAtrributes annotation is used when you want to add a
JavaBean object into a session. This is used when you want to keep
the object in session for short lived. @SessionAttributes is used in
conjunction with @ModelAttribute.
Consider this example.
Just like above example, conversion between JSON to POJO also involves
only two steps,
e.g.
//JSON input
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
try
[Link](emp);
catch (JsonGenerationException e)
[Link]();
} catch (JsonMappingException e) {
[Link]();
} catch (IOException e) {
[Link]();
Output:
// Database credentials
try{
[Link]("[Link]");
stmt = [Link]();
[Link](sql);
[Link](sql);
[Link](sql);
[Link](sql);
}catch(SQLException se){
//Handle errors for JDBC
[Link]();
}catch(Exception e){
[Link]();
}finally{
try{
if(stmt!=null)
[Link]();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
[Link]();
}catch(SQLException se){
[Link]();
}//end try
[Link]("Goodbye!");
}//end main
}//end JDBCExample
[Link]
package [Link];
import [Link];
import [Link];
[Link](con, 1,
"Pankaj");
[Link](con, 1, "Albany
Dr", "San Jose", "USA");
} catch (SQLException e) {
[Link]();
try {
[Link]();
[Link]("JDBC Transaction
rolled back successfully");
} catch (SQLException e1) {
[Link]("SQLException in
rollback"+[Link]());
}
} catch (ClassNotFoundException e) {
[Link]();
} finally {
try {
if (con != null)
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}
8. How many types of statements are there in JDBC? What are they?
There are 3 types of Statements, as given below:
Statement:
It can be used for general-purpose access to the database. It is useful when you are
using static SQL statements at runtime.
PreparedStatement:
It can be used when you plan to use the same SQL statement many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement:
A few things are not clear from your question. My explanation follows based
on below assumptions -
<bean id="mySessionFactory"
class="[Link]">
<property name="dataSource" ref="myDataSource" />
<property name="mappingResources">
<list>
<value>[Link]</value>
</list>
</property>
<property name="hibernateProperties">
<value>
[Link]=[Link]
</value>
</property>
</bean>
<bean id="transactionManager"
class="[Link]">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
@Transactional(propagation=[Link])
public class MyTestDao extends HibernateDaoSupport {
public void saveEntity(Entity entity){
getHibernateTemplate().save(entity);
}
@Transactional(readOnly=true)
public Entity getEntity(Integer id){
return getHibernateTemplate().get([Link], id);
}
}
Below code shows how transaction management could be achieve using
spring's support for AOP rather than annotations.
<bean id="transactionManager"
class="[Link]">
<property name="sessionFactory" ref="mySessionFactory" />
<!-- this is the dao object that we want to make transactional -->
<bean id="testDao" class="[Link]" />
<!-- ensure that the above transactional advice runs for any execution of
a method in 'daos' package-->
<aop:config>
<aop:pointcut id="allDaoMethods"
expression="execution(* [Link].*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethods" />
</aop:config>
The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:
1. Servlet class is loaded.
public class Ex {
data = values;
[Link]( [Link](data) );
Deep Copy
Whenever we need own copy not to use default implementation we call it as deep
copy, whenever we need deep copy of the object we need to implement according
to our need.
So for deep copy we need to ensure all the member class also implement the
Cloneable interface and override the clone() method of the object class.
A deep copy means actually creating a new array and copying over the
values.
// Code explaining deep copy
public class Ex {
It's too risky to rely on Java Serialization mechanism for generating this
id, and that's why it's recommended to declare explicit SerialVersionUID
in your Serializable class. I strongly suggest to read Joshua Bloch's
classic Java title, Effective Java to understand Java Serialization and
issues of incorrect handling it.
14. Difference between Truncate and Delete.
TRUNCATE
DELETE
2. In Table Designer, click the row selector for the database column
you want to define as the primary key. If you want to select multiple
columns, hold down the CTRL key while you click the row selectors
for the other columns.
3. Right-click the row selector for the column and select Set Primary
Key.
20. What is anonymous class in java how to create it.
A class that have no name is known as anonymous inner class in java. It should be used
if you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:
2. Interface
3. abstract class Person{
4. abstract void eat();
5. }
6. class TestAnonymousInner{
7. public static void main(String args[]){
8. Person p=new Person(){
9. void eat(){[Link]("nice fruits");}
10. };
11. [Link]();
12. }
13. }
Java inner class or nested class is a class which is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data
members and methods.
There are two types of nested classes non-static and static nested [Link] non-static
nested classes are also known as inner classes.
ServletConfig
ServletConfig available in [Link].*; package
ServletConfig object is one per servlet class
Object of ServletConfig will be created during initialization process of the
servlet
This Config object is public to a particular servlet only
Scope: As long as a servlet is executing, ServletConfig object will be
available, it will be destroyed once the servlet execution is completed.
We should give request explicitly, in order to create ServletConfig object
for the first time
In [Link] – <init-param> tag will be appear under <servlet-class> tag
Here's how it looks under [Link] : (Source)
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-
value>
</init-param>
</servlet>
ServletContext
ServletContext available in [Link].*; package
ServletContext object is global to entire web application
Object of ServletContext will be created at the time of web application
deployment
Scope: As long as web application is executing, ServletContext object will
be available, and it will be destroyed once the application is removed
from the server.
ServletContext object will be available even before giving the first request
In [Link] – <context-param> tag will be appear under <web-app> tag
Here's how it looks under [Link] :
<context-param>
<param-name>globalVariable</param-name>
<param-value>[Link]</param-value>
</context-param>