New Features in Java 13

 

New Features in Java 13


  • We initially saw switch expressions in JDK 12 itself, build on the previous version by adding a new yield statement.
  • Text Blocks - To embed JSON , XML etc to avoid escaping in the strings.
  • Class data sharing (CDS) 
  • ZGC: Uncommit Unused Memory 
  • Reimplement the Legacy Socket API 

Read more


GIT Eclipse usage basic

GIT- Basics & Eclipse Usage
This post aim at very basic usage of using GIT based tools and eclipse configurations for the same. 

  • create a new repository : create a new directory, open it and perform a
    • git init
to create a new git repository.

  • checkout a repository : Create a working copy of a local repository by running the command 
    • git clone /path/to/repository 
when using a remote server, your command will be
git clone username@host:/path/to/repository

  • Goto project dir 
1. git init
2. git status
3.git add .
4. git status
5. git commit -m "first commit"
6. Create an empty repo in GITHUB
7.copy clone url
8.git remote add origin << URL >>
9.git push -u origin master
10. Check your files are there on GIT remote

To add more / update files

  • git add . 
  • git status 
  • git commit -m "second commit"
  • git push -u origin master

Read more


Static keyword in java

Static keyword in java

The static keyword in java is used for memory management in JAVA. Static keywords belong to the class rather than the instance/object of a class.
We can use static keywords with:
  1. Variable
  2. Method
  3. Block
  4. Class

1. Static variable in Java

You can declare a static variable by simply use of static keyword with a variable. 
  • Static variables are also known as a class variable because they are associated with the class and common for all the objects of a class.
  • Static variables are declared using the static keyword within a class outside any method/constructor/block.
  • When a class created then one copy of a static variable created in memory. Static variables would be common for all objects of class because a static variable is associated with a class. 
  • Static variables are created at the start of program execution and destroyed automatically when execution ends.
  • Initialization of Static Variable is not Mandatory. Its default value is depending on the data type of variable.
  • If we access the static variable through an object the compiler will show the warning message. The compiler will replace the object name to the class name automatically.
  • We can create static variables at class-level only.

2. Static method in Java

You can declare a static method by using of static keyword.
1. Static methods are belonging to a class.
2. You can access a static method by using the class name. You do not have the need to create an object.
3. A static method can access only static variables. If you write any non-static variable in a static method, then it will throw an exception at compilation time.
Why a static method is important: Static method can access without any object. They can access directly by class name. The most common example of a static method is main( ) method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.

3. Static block in Java

If you want to do some calculation and initialize the static variables you can use static block. The static block is get executed once when the class is first loaded.

4. Static class in Java

You can read the static class from my previous post
--
Cheers
Krishna babu Ghanta
Mobile : 303-886-1490 
Time zone : CST

Read more


Spring architecture and Spring boot

Spring is well-organized architecture consisting  of seven modules. Modules in the Spring framework are:


Spring AOP
One of the key components of Spring is the AOP framework. AOP is used in Spring:

To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring’s transaction abstraction.
To allow users to implement custom aspects, complementing their use of OOP with AOP
Spring ORM
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.

Spring Web
The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.

Spring DAO
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.

Spring Context
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.

Spring Web MVC
This is the Module which provides the MVC implementations for the web applications.

Spring Core
The Core package is the most import component of the Spring Framework.
This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.

Read more


Java Springboot Microservices FAQs

  • Is Spingboot thread-safe? 

It depends. The main factor which determines the thread-safety of a component is its scope.

In a standard servlet-based Spring web application, every new HTTP request generates a new thread. If the container creates. a new bean instance just for that particular request, we can say this bean is thread-safe.

Is Spring singleton thread-safe?
The short answer is: no, it isn't.

Reference:  http://dolszewski.com/spring / spring-bean-thread-safety-guide /

  • What are the disadvantages of Springboot? 
Usually, it loads unwanted dependencies sometimes not of any use also, so it will create bulky jars for no use. 
  • What are different design patterns you use in the Microservices ?
 Decomposition Patterns:
Decompose by Business Capability
Decompose by Subdomain
Strangler Pattern
 Integration Patterns:
API Gateway Pattern
Aggregator Pattern
Client-Side UI Composition Pattern
 Database Patterns
  Database per Service
One database per microservice must be designed; it must be private to that service only. It should be accessed by the microservice API only. It cannot be accessed by other services directly. For example, for relational databases, we can use private-tables- Each microservice should have a separate database id so that separate access can be given to put up a barrier and prevent it from using other service tables. per-service, schema-per-service, or database-server-per-service.
  Shared Database per Service
A shared database per service is not ideal, but that is the working solution for the above scenario. Most people consider this an anti-pattern for microservices, but for brownfield applications, this is a good start to break the application into smaller logical pieces. This should not be applied for greenfield applications. In this pattern, one database can be aligned with more than one microservice, but it has to be restricted to 2-3 maximum, otherwise scaling, autonomy, and independence will be challenging to execute.
  Command Query Responsibility Segregation (CQRS)
CQRS suggests splitting the application into two parts — the command side and the query side. The command side handles the Create, Update, and Delete requests. The query side handles the query part by using the materialized views. The event sourcing pattern is generally used Materialized views are kept updated by subscribing to the stream of events.
  Saga Pattern
A Saga represents a high-level business process that consists of several sub requests, which each update data within a single service. Each request has a compensating request that is executed when the request fails. It can be implemented in two ways:

Choreography — When there is no central coordination, each service produces and listens to another service's events and decides if an action should be taken or not.

Orchestration — An orchestrator (object) takes responsibility for a saga's decision making and sequencing business logic.
  Observability Patterns
Log Aggregation 
Performance Metrics: AppDynamics, Prometheus, Grafana
Distributed Tracing: Zipkins, Slueth
Health Check: Spring Boot Actuator 
  Cross-Cutting Concern Patterns:
External Configuration:
Externalize all the configuration, including endpoint URLs and credentials. The application should load them either at startup or on the fly.
Service Discovery Pattern 
Circuit Breaker Pattern
Blue-Green Deployment Pattern
  • How do we implement spring security?
Dependency:

    org.springframework.boot
    spring-boot-starter-security

start by creating a Spring Security configuration class that extends WebSecurityConfigurerAdapter . By adding @EnableWebSecurity, we get Spring Security and MVC integration support.

rest security

security config class- 

basic auth 

authentication filter-> authentication object-> not validated-> authentication manager builder-> 

finds authetication providers-> like DAO or custom authentication provider 

we can pass JWT token in header for authentication. 

server validates if it is generated by itself.


session-based vs token based security. 

tokens are stateless 

requests can go to any node which doesn't understand previous session settings.


What is Bearer (ur the owner of the token) Vs Basic 


after authentication is done only we get JWT token which is used for authorization 


JWT --OAUTH Grant Types:


implicit --Implicit Grant

authorization_code --Authorization Code Grant-  This grant type flow is also called "three-legged" OAuth.

     You've seen this flow anytime your app opens a browser to the resource server's login page and invites you log in to your actual account (for example, Facebook or Twitter).

If you successfully log in, the app will receive an authorization code that it can use to negotiate an access token with the authorization server. 


client_credentials --Client Credentials Grant

password --Resource Owner Password Grant

refresh_token --Use Refresh Tokens

urn: ietf: params: oauth: grant-type: device_code --Device Authorization Grant




Reference:  https://developer.okta.com/blog/2018/10/05/build-a-spring-boot-app-with-user-authentication

3. How to cancel an order for user-specific settings at the spring level? 

3b. Multi calls between ms to ms? 
Using discovery services like Eureka we can route calls between internal microservices effectively.



  • How do we resolve cyclic dependency issues in Springboot? 
By using @Lazy annotation on the dependency we can resolve
or avoid constructor based injection in SB and use setter based injection 
  • Tomcat Max Threads settings in Springboot application? 


server.tomcat.max-connections
8192
Maximum number of connections that the server accepts and processes at any given time. Once the limit has been reached, the operating system may still accept connections based on the "acceptCount" property.
server.tomcat.max-http-form-post-size
2MB
Maximum size of the form content in any HTTP post request.
server.tomcat.max-swallow-size
2MB
Maximum amount of request body to swallow.
server.tomcat.max-threads
200
Maximum amount of worker threads.
server.tomcat.mbeanregistry.enabled
false
Whether Tomcat's MBean Registry should be enabled.
server.tomcat.min-spare-threads
10
Minimum amount of worker threads.
server.tomcat.port-header
X-Forwarded-Port
Name of the HTTP header used to override the original port value.
server.tomcat.processor-cache
200
Maximum number of idle processors that will be retained in the cache and reused with a subsequent request. When set to -1 the cache will be unlimited with a theoretical maximum size equal to the maximum number of connections.
server.tomcat.protocol-header
Header that holds the incoming protocol, usually named "X-Forwarded-Proto".
Reference:
https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html

  • Sort Employee salary using Java Streams and display salary which is greater than X amount? Java 8 --streams, lambda expression

// find employees whose salaries are above 10000
        empList.stream().filter(emp->emp.getSalary() > 10000).forEach(System.out::println);

Reference:
https://www.java2novice.com/java-8/streams/filter-method-example/

  • Spring boot --Dependency injection types? 

There are basically three types of dependency injection:
constructor injection: the dependencies are provided through a class constructor.
setter injection: the client exposes a setter method that the injector uses to inject the dependency.
Interface injection: the dependency provides an injector method that will Clients must implement an interface that exposes a setter method that accepts the dependency.

So now its the dependency injection's responsibility to:
  • Create the objects
  • Know which classes require those objects
  • And provide them all those objects
Reference : https://java2blog.com/introduction-to-spring-framework/#Spring_Boot
  • How do we do monitoring of REST APIS ? 
Appdynamics like tools helps to do this monitoring

  • How do we call External Microservices in Springboot REST APIS ?

Using Rest Template or Feign clients 

Resttemplate : getForEntity(gets full responseEntity) vs getForObject (only object we get)

  exchange also do the same


  • What are status codes for DELETE API ?


Right Status codes for delete - 204 - content not found

                                          200 - OK 


  • Why Do we need Timeout setting in REST APIs ? 

For each request, a thread is blocked.

at one point in time threads will be out. so time out is needed to release threads. Default is 200 threads in thread pool.

Ex :Read time out(not able to complete reading data) , server time out (not able to get connection)



  • Versioning in REST APIs ?

the new functionality will be rolled with new version apis

using request param or path param

also using headers 

uri @Getmapping


  • What is content negotiation in the REST ? 

 mediatype : Produces or consumes is nothing but content negotiation.



  • What are cross-cutting concerns?

 AOP - for logging purposes

security setup using Request Filters, and Interceptors for managing requests and response data


  • How do you create custom annotation in spring boot? 


STEP1: Create an interface with the annotation name

STEP2: Create an Aspect

STEP3: Add the annotation


@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface Traceable {

 

}


  • @autowire Vs @Inject

 @Autowired is Spring's own annotation. @Inject is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations work the same way as Spring has decided to support some JSR-299 annotations in addition to their own.


  • Tell me some important annotations in springboot? 


@SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration.

@Controller  
@RequestMapping("books")  :
@Controller: The @Controller is a class-level annotation. It is a specialization of @Component. It marks a class as a web request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with @RequestMapping annotation.
@Service: It is also used at the class level. It tells the Spring that the class contains the business logic.

@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the database directly. The repository does all the operations related to the database.

@ConditionalOnClass and @ConditionalOnMissingClass
Using these conditions, Spring will only use the marked auto-configuration bean if the class in the annotation's argument is present/absent:

@ConditionalOnBean and @ConditionalOnMissingBean
We can use these annotations when we want to define conditions based on the presence or absence of a specific bean:

@ConditionalOnProperty
With this annotation, we can make conditions on the values of properties:

@ConditionalOnProperty
The @ConditionalOnProperty annotation is, in my experience, the most commonly used conditional annotation in Spring Boot projects. It allows to load beans conditionally depending on a certain environment property:

@Configuration
@ConditionalOnProperty(
    value="module.enabled", 
    havingValue = "true", 
    matchIfMissing = true)

 @Required : This annotation is applied to bean setter methods. It indicates that the required property must be filled at the configuration time in the affected bean, or else it throws an exception: BeanInitializationException.
@Qualifier :

It is used along with @Autowired annotation. It is used when more control is required over the dependency injection process. Individual constructor arguments or method parameters can be specified by using this annotation. Confusion arises when more than one bean of the same type is created, and only one of them is to be wired with a property, @Qualifier is used to get rid of the confusion.
@CookieValue : 
It is used at the method parameter level as an argument of the request mapping method. For a given cookie name, the HTTP cookie is bound to a @CookieValue parameter.
@Lazy 
It is used in the component class. At startup, all auto-wired dependencies are created and configured. But a @Lazy annotation can be created if a bean is to be initialized lazily. This means that only if it is requested for a bean will be created. It can also be used on @Configuartion classes. It’s an indication that all @Bean methods within that @Configuration should be lazily initialized.
@Configuration
@ComponentScan(basePackages="org.mavin.krishna")
public class Config {
}

@Primary
we use @Primary to give higher preference to a bean when there are multiple beans of the same type.

@Order

    The @Order annotation defines the sorting order of an annotated component or bean.
supports the ordering of injected components to a collection. As a result, Spring will inject the auto-wired beans of the same type based on their order value.

Ordered.LOWEST_PRECEDENCE. 
Ordered.HIGHEST_PRECEDENCE 

@Order(1)
@Component
@Order(Ordered.LOWEST_PRECEDENCE)

@EnableAsync

With this annotation, we can enable asynchronous functionality in Spring.

We must use it with @Configuration:

@EnableScheduling
With this annotation, we can enable scheduling in the application.

We also have to use it in conjunction with @Configuration:


@Async
We can define methods we want to execute on a different thread, hence run them asynchronously.

To achieve this, we can annotate the method with @Async:

@Scheduled
If we need a method to execute periodically, we can use this annotation:

@Scheduled(fixedRate = 10000)

@PostConstruct
Spring calls methods annotated with @PostConstruct only once, just after the initialization of bean properties.

@PreDestroy
A method annotated with @PreDestroy runs only once, just before Spring removes our bean from the application context.




Read more


JBOSS start and stop shell scripts - domain mode - host controller - domain controller

 JBOSS start and stop shell scripts - domain mode - host controller - domain controller
===========START DOMAIN CONTROLLER MACHINE JBOSS=================
echo "Setting JBOSS Env"
export JAVA_HOME=/opt/app/java/jdk/jdk160
export PATH=$PATH:/opt/app/jboss/jboss-eap-6.3/bin:$JAVA_HOME/bin
echo "PATH is : $PATH"

echo "JBOSS Environment is ready and starting jboss in domain mode"
echo "MY:JAVA_OPTS: $JAVA_OPTS"
export JAVA_OPTS="$JAVA_OPTS -DASOCPropsFile=/abc/etc/abc.props -DLNSPropsFile=/pns/etc/pns.props -DAVSPropsFile=/bvs/etc/bvs.props -DEOTPropsFile=/toe/etc/toe.props -DLPSPropsFile=/psl/etc/psl.props -DADLPropsFile=/hfl/etc/hfl.props -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true"
echo "MY AFTER:JAVA_OPTS: $JAVA_OPTS"

/export/opt/jboss/jboss-eap-6.3/bin/domain.sh -b cldv0015.abc.cpf.com -bmanagement cldv0015.abc.cpf.com &
=============================================
============START HOST CONTROLLER==========
=============================================

==========STOP JBOSS Process harshly==============
echo "Stopping JBOSS JAVA processes"

for i in `ps -eaf | grep jboss | grep java | cut -d " " -f6`
{
        kill -9 $i
    echo "Killing: $i"
}
ps -eaf | grep jboss | grep java
echo "Stop completed"
============================================

Read more

Popular Posts

Enter your email address:

Buffs ...

Tags


Powered by WidgetsForFree