Saturday, April 29, 2017

Java interview questions

1. How to create immutable objects and benefits of it?

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields. Use constructor to take the values required.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

      Benifits:
  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. The internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.

Refernces
http://okyasoft.blogspot.com/2014/05/6-benefits-of-programming-with_5146.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html



2. Collections overview and Big o notation?

The following table summarizes the principal classes in Java collections framework for quick reference:
Principal collection class
Base class
Base interfaces
Allow duplicate elements?
Ordered?
Sorted?
Thread-safe?
ArrayList
AbstractList
List
Yes
Yes
No
No
LinkedList
AbstractSequentialList
List;
Deque
Yes
Yes
No
No
Vector
AbstractList
List
Yes
Yes
No
Yes
HashSet
AbstractSet
Set
No
No
No
No
LinkedHashSet
HashSet
Set
No
Yes
No
No
TreeSet
AbstractSet
Set;
NavigableSet;
SortedSet
No
Yes
Yes
No
HashMap
AbstractMap
Map
No
No
No
No
LinkedHashMap
HashMap
Map
No
Yes
No
No
Hashtable
Dictionary
Map
No
No
No
Yes
TreeMap
AbstractMap
Map;
NavigableMap;
SortedMap
No
Yes
Yes
No

Refernces: http://www.codejava.net/java-core/collections/java-collections-framework-summary-table


List implementations:
                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)
Set implementations:
                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
Map implementations:
                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)
Queue implementations:
                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

Spring:

2. Spring scopes?

The scopes supported out of the box are listed below:

Table 4.4. Bean scopes
ScopeDescription
Scopes a single bean definition to a single object instance per Spring IoC container.
Scopes a single bean definition to any number of object instances.
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware SpringApplicationContext.
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware SpringApplicationContext.
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
Reference:
http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html


Tuesday, April 25, 2017

mc interview questions

1. Inheritance vs composition when to use
2. Abstarct examples
3. When to create Index
4. why are you software engineer
5. Method call with Object and String
6. Do you know microservices


7.  disadvanteages of recursive functions
8. Class A{
 B b = new B();

toStirng(){
return "from A+"b;
}
}

Class B{
 A a = new A();

toStirng(){
return "from B+"a;
}
}

9. Architecture
10. How you keep up with technologies
11. Transactions isolations level
12. Coupling vs Cohesive
13. Disadvantages of Micro service architecture

Monday, April 24, 2017

PI

I am Satya Sreenivas, I have total 12+ java experience..  I have been with Maritz Client  from past  6yrs.. I performed various roles Java Developer to architect roles.. was also Scrum master for PRNewswire project.

I have extensive knowledge on Java, J2EE, XML, XSL, SOAP, REST Webservices, Spring MVC, Spring Batch and Content Management Tools

I have used JBoss, Apache Tomcat, WAS servers.

I have worked on Amazon Cloud EC2, RDS and Linux Servers throughout my career.

I always exceeds expectation of my clients... my director VPs, Director.

My Current Project:

I am Project lead and java lead developer, we have team of 4 API, 2 UI, 3 QA, 1PM, 1BA

30% - Code reviews, Design meetings
70% - I work on coding


SalesNext Platform is the next generation rewards platform for agencies. Sales reps can enroll into the systemand points are awarded based on the sales activity. Badges are used to engage the sales reps in the rewards program. A healthy competition is created between agencies with the leaderboards for sub-region, region and organization level. A point bank system is used to redeem the award points. The Commercial Loyalty Platform, tracks earning and redemption transactions, generates and manages file loads and transmissions, configures promotions and feeds information for use by the operational center.



Strengths:
1. Problem Solver..
There is no problem.. without a solution.. you just need to think out of the box.. and I have solved so many problems

2. Good mentor - I helped interns and my team to perform best and give them design ideas.
I give very detail oriented details..

3. Keep up with Technology :

4. Quick leaner :

4. Smart work and Hard worker

5. Flexible in my

Weakness: 
1. Helping nature:

2. Unorganized tasks







Sunday, April 23, 2017

Spring

Spring JavaConfig is a product of the Spring community that provides a pure-Java approach to configuring the Spring IoC Container. It thus helps avoid using XML configurations. The advantages of using JavaConfig are
The advantages of JavaConfig are
  • Object-oriented configuration. Because configurations are defined as classes in JavaConfig, users can take full advantage of object-oriented features in Java. One configuration class may subclass another, overriding its @Bean methods, etc.
  • Reduced or eliminated XML configuration. The benefits of externalized configuration based on the principles of dependency injection have been proven. However, many developers would prefer not to switch back and forth between XML and Java. JavaConfig provides developers with a pure-Java approach to configuring the Spring container that is conceptually similar to XML configuration. It is technically possible to configure the container using only JavaConfig configuration classes, however in practice many have found it ideal to mix-and-match JavaConfig with XML.
  • Type-safe and refactoring-friendly. JavaConfig provides a type-safe approach to configuring the Spring container. For XML you won’t get errors before starting the Spring ApplicationContext, and sometimes even later. Typing errors may slow you down.

Thursday, March 2, 2017

Run tomcat on SSL or https


tomcat
tomcat-apr
5.5.23
 
 
api



               org.codehaus.mojo
               keytool-maven-plugin
               1.1
               
                   
                       generate-resources
                       clean
                       
                           clean
                     
                 
                   
                       generate-resources
                       genkey
                       
                           genkey
                     
                 
             
               
                   ${project.build.directory}/keystore.jks
                   cn=d-libertymutual-api.salesnext.com
                   password
                   password
                   selfsigned
                   RSA
             
         
           
               org.apache.tomcat.maven
               tomcat7-maven-plugin
               2.2
               
                   80
                   UTF-8
                   443
                   ${project.build.directory}/tomcat-ssl.keystore
                   password
                   /api
             
         
       
     
 
 

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 the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

Spring JPA




  1. Spring jpa jars as dependecies in pom.xml
  2. Create an interface ParticipantRepository extends JPARepository
  3. Add @Entity  @Table @EntityListner 
  4. 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.
@Override
public List findByIds(ID... ids) {
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) query.getResultList();
}

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
 basePackages = "${entityManager.packagesToScan:com.mycompany.entity}",
 repositoryBaseClass = BaseRepositoryImpl.class
)
public class SpringConfiguration {

Q2: Auditable fields
1. 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. 1. Database Independent: You can quickly switch your JPA implementation, as long as you’re not using any proprietary features.
  2. 2. Developer productivity: No need to write boiler plate code
  3. 3. ORM:  Object Relational mapping.. you just deal with objects and it internally reflects
  4. 4. Writing queries with method names:
  5. 5. Avoid Unnecessary Queries: 
  6. 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 SQL UPDATE statement, 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.
  1. 5. Caching: 

https://www.sitepoint.com/5-reasons-to-use-jpa-hibernate/