Sunday, September 29, 2024

Resolving Issues with regular Java Programming

 SQL Injection

       SQL Injection is done by tricking the database by giving a valid condition to any SQL query on a table. It may be creatively done in many ways. More than 50% of the hacking attacks are done through SQL injection.

PREVENTION:
Use SQL filters to avoid "LIKE", single or double quotes, baclslashes, colons and special characters in SQL query.
Maintain previleges and strict user control over the database by creating lot of views/schemas for each operations.
Use ORACLE's dynamic query escaper - ESAPI

Tuesday, September 24, 2024

coding question in streams


JPMC Interview Questions

List of numbers, find starting with 1

List<Integer> start1List = intList.stream().map(num -> (String.valueOf(num).startsWith("1") == true ? num : null)).filter(n -> n != null).collect(Collectors.toList());

 

find three maximum and three minimum numbers from the list you can use the same list

intList.stream().sorted().limit(3).forEach(System.out::println);

intList.stream().sorted(Comparator.reverseOrder()).limit(3).forEach(System.out::println);


Program to filter even numbers from an array using Java streams

  • Use Java streams to filter even numbers from an array

  • Use filter() method with lambda expression to check if a number is even

  • Arrays.asList(intArr).stream().filter(num -> num%2 == 0).forEach(System.out::println);



  • Collect the filtered numbers into a new array using collect() method

  • Arrays.asList(intArr).stream().filter(num -> num%2 == 0).collect(Collectors.toList());



SUM of list

System.out.println(intList.stream().reduce(0, (x, y)->x+y));


flatMap -> data flattening -> streams of streams will be converted to stream


//find duplicates values

intList.stream().filter(s -> Collections.frequency(intList, s) > 1).forEach(System.out::print);

// use hashset

HashSet<Integer> set1 = new HashSet<Integer>();

intList.stream().filter(s -> !set1.add(s)).forEach(System.out::print);


//find highest nos

System.out.println(intList.stream().sorted(Comparator.reverseOrder()).findFirst().get());


//find second highest nos

System.out.println(intList.stream().sorted(Comparator.reverseOrder()).limit(2).skip(1).findFirst().get());


//Find the intersection of two lists using Java streams:

intList.stream().filter(intList1::contains).forEach(System.out::println);


// Max integer from list

int max = myList.stream()
.max(Integer::compare)
.get();



PROGRAM:


package java8sample;


import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashSet;

import java.util.List;

import java.util.stream.Collectors;


public class streammain {


public static void main(String[] args) {

// Given a list of integers, find out all the even numbers that exist in the list using Stream functions?

List<Integer> intList = Arrays.asList(1,4,6,7,8,9,1,7);

List<Integer> intList1 = Arrays.asList(1,4,6);

List<Integer> evenList = intList.stream().filter(num -> num%2 == 0).collect(Collectors.toList());

// System.out.println("find out all the even numbers - "+evenList);

//multile by 2

// intList.stream().map(a -> a*2).forEach(System.out::print);

//sort

// StringBuilder s =

//filter and sort

List<Integer> l1 = intList.stream().filter(s -> s<=9).sorted().collect(Collectors.toList());

// System.out.println("filter and sort =- "+l1);

//Integer to string list, concat last but 1

List<String> s1 = l1.parallelStream().map(Object::toString).collect(Collectors.toList());

// System.out.println("Integer to string list, concat:");

// s1.stream().map(a -> a == s1.get(s1.size()-1)?a:a.concat(",")).forEach(System.out::print);

//Program to filter even numbers from an array using Java streams

Integer[] intArr = {1,3,12,5,6};

// Arrays.asList(intArr).stream().filter(num -> num%2 == 0).forEach(System.out::println);

Arrays.asList(intArr).stream().filter(num -> num%2 == 0).collect(Collectors.toList());

// List of numbers, find starting with 1

List<Integer> start1List = intList.stream().map(num -> (String.valueOf(num).startsWith("1") == true ? num : null)).filter(n -> n != null).collect(Collectors.toList());

// System.out.println(start1List);

// find three maximum and three minimum numbers from the list you can use the same list

// intList.stream().sorted().limit(3).forEach(System.out::println);

// intList.stream().sorted(Comparator.reverseOrder()).limit(3).forEach(System.out::println);

//add all values

// System.out.println(intList.stream().reduce(0, (x, y)->x+y));

//find duplicates values

// intList.stream().filter(s -> Collections.frequency(intList, s) > 1).forEach(System.out::print);

// use has set

HashSet<Integer> set1 = new HashSet<Integer>();

// intList.stream().filter(s -> !set1.add(s)).forEach(System.out::print);

//find second highest nos

// System.out.println(intList.stream().sorted(Comparator.reverseOrder()).limit(2).skip(1).findFirst().get());

// streammain sm = new streammain();

// sm.printPrime();

// Find the intersection of two lists using Java streams:

intList.stream().filter(intList1::contains).forEach(System.out::println);

}

// public boolean isPrime(Integer in) {

// if(in <= 1)

// return false;

// for(int i=2;i<in;i++) {

// if(in%i == 0)

// return false;

// }

// return true;

// }//end isPrime


public boolean isPrime(int number) {

if (number <= 1) {

return false;

}

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

return false;

}

}

return true;

}

private void printPrime() {

List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10, 11, 12, 13, 14, 15);

boolean containsPrime = numbers.stream()

.anyMatch(this::isPrime);

System.out.println("List contains a prime number: " + containsPrime);


}


}

design pattern

Design pattern - set of rules and setting we need to follow to improve our application standard 

Refresh duplicate save - post redirect and get - prg

MVC pattern

Singleton - every class in springboot is singleton

IOC - constructor injection - complex configuratiin - reason immutability
@autowire - not immutable 
Builder pattern


Spring Boot

spring boot lifecycle or components

Spring Boot Lifecycle:

  1. Initialization: The application is initialized, and the Spring Boot context is created.
  2. Bean Definition: Bean definitions are loaded from configuration files, annotations, and other sources.
  3. Bean Creation: Beans are created and instantiated based on their definitions.
  4. Bean Post-processing: Beans are post-processed, and any necessary initialization is performed.
  5. Application Startup: The application is started, and any necessary startup tasks are performed.
  6. Application Running: The application is running, and requests are being processed.
  7. Application Shutdown: The application is shut down, and any necessary shutdown tasks are performed.

Spring Boot Components:

  1. Application: The main application class, annotated with @SpringBootApplication.
  2. Configurations: Configuration classes, annotated with @Configuration, that define beans and their dependencies.
  3. Beans: Components that are instantiated and managed by the Spring Boot context.
  4. Controllers: Components that handle incoming requests and return responses.
  5. Services: Components that encapsulate business logic and provide services to controllers.
  6. Repositories: Components that encapsulate data access logic and provide data to services.
  7. Entities: Components that represent data models and are used by repositories.
  8. Listeners: Components that listen for events and perform actions in response.
  9. Filters: Components that filter incoming requests and modify responses.
  10. Interceptors: Components that intercept incoming requests and modify responses.

Spring Boot Annotations:

  1. @SpringBootApplication: Indicates the main application class.
  2. @Configuration: Indicates a configuration class.
  3. @Bean: Defines a bean and its dependencies.
  4. @Component: Indicates a component that can be autowired.
  5. @Controller: Indicates a controller that handles incoming requests.
  6. @Service: Indicates a service that encapsulates business logic.
  7. @Repository: Indicates a repository that encapsulates data access logic.
  8. @Entity: Indicates an entity that represents a data model.
  9. @Listener: Indicates a listener that listens for events.
  10. @Filter: Indicates a filter that filters incoming requests.

Spring Boot Events:

  1. ApplicationStartedEvent: Fired when the application is started.
  2. ApplicationReadyEvent: Fired when the application is ready to receive requests.
  3. ApplicationFailedEvent: Fired when the application fails to start.
  4. ContextRefreshedEvent: Fired when the Spring Boot context is refreshed.
  5. ContextClosedEvent: Fired when the Spring Boot context is closed.

@configuration mark class as source of bean definition
@componentscan

@autowired- wires the application parts of a component fields 

@actuator health of rest api

@Enablewebsecurity http authorize .hasipaddress()
Http csrf().disable - cross site request forgery
Password encryption - 
Rate limiter - limit no of hits from one ip
Http.Cors() - cross-origin resource sharing
Http.Oauth2login().user endpoint URL()

@transactional - if one failed it will rollback the whole transaction

Can transaction managed externally  - supports
JMS Transactions - jtatransactionmanager
Spring Cloud Stream Transaction @enablekafka
Chained transactionmanager

Validation - @restcontrolleradvice
Global handler class  @handleairthmeticexception
API error advice - contains binding exception 
aop crosscuts the exception 

Advantages of springboot
Embedded tomcat

Securing rest API - authorized - 403 - Jwt -- TTL - 

Internalization
@messagesource local resolver
Local context localeinterceptor

Evendriven -- @async - @eventlistener
ApplicationEvent - class -appication event publisher - 
springcloudstream - for event driven microservices

Cache - @rediscache - 
default cache - limitations - limited annotations - cache size limited - no distributed cache - no clustering - no cache events - no cache statistics - limited configuration options

Embedded server - no smooth control for config changes - simplified deployment - easier deployment 
Pom - exclude or include which webserver tomcat jetty

Docker - jar - CD - container - from there we run - docker compose multicontainer docker applications - docker swarm cluster orchestrate - use kubernetis - automate deploy, scaling and management of container

Rebase - update my feature Branch with the latest from the main branch without creating additional commits

how can you optimize a maven build for a large project? - base image docker file - plugins - create jar - maven assembly plugin - maven shade plugin 

Maven Lifecycle - validate compile test package integration test verify install deploy clean site

What is difference between @Controller and @RestController annotation?

Feature@Controller@RestController
View vs. DataReturns a view (e.g., HTML, JSP)Returns data (e.g., JSON, XML)
ResponseBodyRequires @ResponseBody for sending response bodyImplicitly adds @ResponseBody
Use CaseTraditional web applications (with view rendering)RESTful web services or APIs
View ResolutionUses view resolvers to map the response to a viewSkips view resolution; directly writes to response body

How can I tell my REST API method that I need to return response in which format?
// Return XML when requested @GetMapping(value = "/greet", produces = "application/xml")

If I want to supply another parameter along with Response body, how can I do that?
Using ResponseEntity, you can include additional parameters like custom headers and HTTP status codes, along with the response body, in a clean and flexible way. This approach provides more control over the response structure compared to just returning a response body directly.

  • Serialization: Converting an object into a byte stream.
  • Deserialization: Converting a byte stream back into an object.
  • Serializable Interface: Required for making objects serializable.
  • transient: Fields marked with transient will not be serialized.

  • Does An abstract class required to have an abstract method inside ?Can we decla
    re a class as Abstract without having any abstract method?
  • Abstract class: Can be declared without abstract methods.
  • An abstract class without abstract methods is still useful for preventing instantiation and providing common functionality to subclasses.
  • Abstract methods: Must be implemented by any subclass of the abstract class, but they are not required to be present in every abstract class.

  • How one can pass the path parameter in URL of rest API?
    n Spring Boot, you can pass path parameters in the URL of a REST API using the @PathVariable annotation

    Why not serialize abstract classes in Java?
    1. Incomplete State: Abstract classes often represent incomplete entities, lacking the full implementation required for a meaningful object. Serializing such an object might lead to data loss or inconsistencies upon deserialization.
    2. Subclass Variations: The purpose of an abstract class is to provide a common base for various subclasses, each with its own unique implementation and state. Serializing the abstract class directly wouldn't capture the specific details of the subclass, leading to potential issues when deserializing.
    3. Implementation Flexibility: Serialization ties the structure of a class to its serialized form. If you serialize an abstract class, you restrict the ability to modify its structure in the future without breaking compatibility with existing serialized data.
    4. Design Considerations: Abstract classes are often designed for inheritance and polymorphism, not for data persistence. If you need to persist data related to an abstract class, it's typically better to serialize the concrete subclasses that implement it.
    Alternatives to Serializing Abstract Classes:
    • Serialize Subclasses:
    • Extract Data:
      Create a separate data transfer object (DTO) 
    Oauth

    OAuth (Open Authorization) is an industry-standard authorization framework that allows a client application to access a protected resource on behalf of a resource owner, without sharing the resource owner's credentials.

    Here's a simplified overview of the OAuth flow:

    1. Registration: The client application registers with the authorization server, providing a redirect URI and other details.
    2. Authorization Request: The client application requests authorization from the resource owner, who is redirected to the authorization server.
    3. User Authentication: The resource owner authenticates with the authorization server.
    4. Authorization Grant: The authorization server redirects the resource owner back to the client application with an authorization code.
    5. Token Request: The client application exchanges the authorization code for an access token.
    6. Access Token: The authorization server issues an access token to the client application.
    7. Protected Resource Access: The client application uses the access token to access the protected resource.

    OAuth provides several benefits, including:

    • Security: OAuth allows clients to access resources without sharing credentials.
    • Flexibility: OAuth supports multiple authorization flows and grant types.
    • Scalability: OAuth is widely adopted and supported by many platforms and services.

    Common OAuth grant types include:

    • Authorization Code Grant: Used for server-side applications.
    • Implicit Grant: Used for client-side applications.
    • Resource Owner Password Credentials Grant: Used for trusted applications.
    • Client Credentials Grant: Used for server-to-server authentication.

    OAuth is widely used in various industries, including:

    • Social Media: Facebook, Twitter, LinkedIn, etc.
    • Cloud Services: Google Cloud, Amazon Web Services, Microsoft Azure, etc.
    • APIs: Many APIs use OAuth for authentication and authorization.
    spring boot data migrations

    Spring Boot Data Migrations is a feature that allows you to manage changes to your database schema over time. It's a way to version control your database schema, making it easier to manage changes and collaborate with others.

    Here are some key concepts and features of Spring Boot Data Migrations:

    Key Concepts:

    1. Migration: A migration is a set of changes to the database schema, such as creating a new table or adding a column to an existing table.
    2. Version: Each migration is associated with a version number, which is used to track the order of migrations.
    3. Script: A script is a file that contains the SQL commands to apply a migration.

    Features:

    1. Automatic Migration: Spring Boot can automatically apply migrations when the application starts.
    2. Version Control: Spring Boot keeps track of the version number of the migrations that have been applied to the database.
    3. Rollback: Spring Boot allows you to roll back migrations to a previous version.
    4. Custom Scripts: You can write custom scripts to perform complex migrations.

    Types of Migrations:

    1. SQL Migrations: These are migrations that use SQL scripts to modify the database schema.
    2. Java-Based Migrations: These are migrations that use Java code to modify the database schema.

    Tools:

    1. Flyway: Flyway is a popular tool for managing database migrations. Spring Boot provides built-in support for Flyway.
    2. Liquibase: Liquibase is another popular tool for managing database migrations. Spring Boot provides built-in support for Liquibase.

    Best Practices:

    1. Use Version Control: Use version control to track changes to your migrations.
    2. Test Migrations: Test your migrations thoroughly before applying them to production.
    3. Use Rollback: Use rollback to revert changes if something goes wrong.
    4. Document Migrations: Document your migrations to make it easier for others to understand the changes.