Thursday, March 2, 2017
Run tomcat on SSL or https
Generate self signed cert
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-using-java-keytool.html
Saturday, February 25, 2017
Java Recap 2017
The try-with-resources Statement
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
in Java SE 7 and later, implements the interface java.lang.AutoCloseable.
Classes That Implement the AutoCloseable or Closeable Interface
See the Javadoc of theAutoCloseableandCloseableinterfaces for a list of classes that implement either of these interfaces. TheCloseableinterface extends theAutoCloseableinterface. Theclosemethod of theCloseableinterface throws exceptions of typeIOExceptionwhile theclosemethod of theAutoCloseableinterface throws exceptions of typeException. Consequently, subclasses of theAutoCloseableinterface can override this behavior of theclosemethod to throw specialized exceptions, such asIOException, or no exception at all.
Spring JPA
- Spring jpa jars as dependecies in pom.xml
- Create an interface ParticipantRepository extends JPARepository
- Add
@Entity @Table @EntityListner - Advantages JPA spring data
- No need to write queries or biolerplate code.. like resultset, connection, transaction
- Pagination
Q1: Create common methods for repositories
1. @NoRepositoryBean
public interface BaseRepository <T, ID extends Serializable>
extends JpaRepository<T, ID>
2. public class BaseRepositoryImpl<T, ID extends Serializable>
extends SimpleJpaRepository<T, ID>; implements BaseRepository<T, ID> {
private JpaEntityInformation entityInformation;
private EntityManager entityManger;
3.
@Overridepublic List
Query query = this.entityManger.createQuery("select e from " + this.entityInformation.getEntityName()
+ " e where e." + this.entityInformation.getIdAttribute().getName() + " in :ids");
query.setParameter("ids", Arrays.asList(ids));
return (List
}
@Configuration @EnableTransactionManagement @EnableJpaRepositories( basePackages = "${entityManager.packagesToScan:com.mycompany.entity}", repositoryBaseClass = BaseRepositoryImpl.class ) public class SpringConfiguration {
Q2: Auditable fields1. Add @EntityListeners(AuditingEntityListener.class)
2.@CreatedBy
private String createdBy;
@LastModifiedBy
private String lastModifiedBy;
@CreatedDate
private Date createdDate;
@LastModifiedDate
private Date lastModifiedDate;
Reference
https://www.youtube.com/watch?v=9Nopu8hRKq4&t=319s
Q3: JPA Key components
-
JPA Provider : The vendor product which contains JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc.
-
Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database.
-
JPA Loader : The JPA loader works like cache memory, which can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (Attributes of POJO class).
-
Object Grid : The Object grid is a temporary location which can store the copy of relational data, i.e. like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it effects the main database.
@Entity
@EntityListeners(AuditableListener.class)
@Table(name = "ADDRESS")
public class Address implements Auditable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ADDRESS_ID", insertable = false, updatable = false)
private Long addressId;
@NotNull
@Column(name="PARTICIPANT_ID")
private Long participantId;
Q4: Advantages of JPA
- 1. Database Independent: You can quickly switch your JPA implementation, as long as you’re not using any proprietary features.
- 2. Developer productivity: No need to write boiler plate code
- 3. ORM: Object Relational mapping.. you just deal with objects and it internally reflects
- 4. Writing queries with method names:
- 5. Avoid Unnecessary Queries:
The write-behind optimization is one of several performance optimizations you get with JPA. The basic idea is to delay all write operations as long as possible so that multiple update statements can be combined into one. Your JPA implementation, therefore, stores all entities that were used within one transaction in the first level cache.Due to this, the following code snippet requires only one SQLUPDATEstatement, even though the entity gets changed in different methods within the application. This reduces the number of SQL statements massively, especially in complex, modularized applications.
- 5. Caching:
https://www.sitepoint.com/5-reasons-to-use-jpa-hibernate/
Sunday, February 19, 2017
Design pattern composite
What is Composite Design Pattern
Composite Design pattern is ideal for designing a system where part-whole hierarchies exist, and where the part and the whole components are to be treated in the system uniformly.
Composite design pattern treats both the parts and the whole in the same way. This is very beneficial for handling hierarchical part-whole hierarchies which are recursive in nature.
Consider a binary tree. The left sub-tree and right sub-tree are themselves full-fledged binary trees. Traversals of these trees is recursive in nature due to this part-whole similarity.
Another ubiquitous example is a UML editor, every element of the diagram is treated(drawn) in the editor the same way as the whole UML diagram.
Composite Design pattern is ideal for designing a system where part-whole hierarchies exist, and where the part and the whole components are to be treated in the system uniformly.
Composite design pattern treats both the parts and the whole in the same way. This is very beneficial for handling hierarchical part-whole hierarchies which are recursive in nature.
Consider a binary tree. The left sub-tree and right sub-tree are themselves full-fledged binary trees. Traversals of these trees is recursive in nature due to this part-whole similarity.
Another ubiquitous example is a UML editor, every element of the diagram is treated(drawn) in the editor the same way as the whole UML diagram.
Composite Pattern consists of following objects.
- Base Component – Base component is the interface for all objects in the composition, client program uses base component to work with the objects in the composition. It can be an interface or an abstract class with some methods common to all the objects.
- Leaf – Defines the behaviour for the elements in the composition. It is the building block for the composition and implements base component. It doesn’t have references to other Components.
- Composite – It consists of leaf elements and implements the operations in base component.
References:
http://www.javabrahman.com/design-patterns/composite-design-pattern-in-java/
http://www.journaldev.com/1535/composite-design-pattern-in-java
Design pattern Adapter
Adapters in the Real World
A real world analogy always helps with the understanding of a design pattern. The best example for the adapter pattern is based around AC power adapters. Say you're visiting Europe from the US, with your laptop, which expects a US power supply. To get your laptop plugged in, you're going to need to get a power adapter that accepts your US plug and allows it to plug in to the European power outlet. The AC adapter knows how to deal with both sides, acting as a middleman - this is the adapter pattern.
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
The Adapter Pattern
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
The Adapter Pattern
The Adapter is known as a structural pattern,as it's used to identifying a simple way to realize relationships between entities. Thedefinition of Adapter provided in the original Gang of Four book on DesignPatterns states:
The Target interface defines the domain specific interface that the Client used, so the client collaborates with objects that implement the Target interface. On the other side of things, the Adaptee is the existing interface that needs adapting in order for our client to interact with it. The Adapter adapts the Adaptee to the Target interface - in other words, it translates the request from the client to the adaptee.
Realtime:
- java.util.Arrays#asList()
Reference: https://dzone.com/articles/design-patterns-uncovered-0
https://www.javacodegeeks.com/2015/09/adapter-design-pattern.htmlAll design patterns : https://www.youtube.com/watch?v=0jjNjXcYmAU
Design patterns observer
1. Observer design pattern
Observer Pattern is one of the behavioral design pattern. Observer design pattern is useful when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the object that watch on the state of another object are called Observer and the object that is being watched is called Subject.
Realtime used: Badge creation
a. public class BadgeResultEvent extends ApplicationEvent {
b. @EventListener
public void handleBadgeEvent(BadgeResultEvent badgeResultEvent) {
c. applicationEventPublisher.publishEvent(new BadgeResultEvent(badgeTransaction));
Refernces:
http://www.journaldev.com/1739/observer-design-pattern-in-java
Subscribe to:
Posts (Atom)
