latest ECMAScript proposals and releases (as of ECMAScript 2024), several enhancements have been made to built-in objects like Set

JavaScript continues to evolve, and in the latest ECMAScript proposals and releases (as of ECMAScript 2024), several enhancements have been made to built-in objects like Set. Here are some new or recent features involving Set and other collections:

1. New Set Methods (Stage 4 — Finalized for ECMAScript 2024)

The following methods have been added to the Set prototype, making Set operations easier and more declarative:

a. Set.prototype.union(otherSet)

Returns a new set containing all elements from the original and the other set.

javascript

const a = new Set([1, 2]); const b = new Set([2, 3]); const result = a.union(b); // Set {1, 2, 3}

b. Set.prototype.intersection(otherSet)

Returns a new set with only the elements common to both sets.

javascript

const result = a.intersection(b); // Set {2}

c. Set.prototype.difference(otherSet)

Returns a new set with elements from the original set that are not in the other set.

javascript

const result = a.difference(b); // Set {1}

d. Set.prototype.symmetricDifference(otherSet)

Returns a new set with elements that are in either of the sets, but not both.

javascript

const result = a.symmetricDifference(b); // Set {1, 3}

e. Set.prototype.isSubsetOf(otherSet)

Checks if all elements in the current set exist in the other set.

javascript

a.isSubsetOf(b); // false

f. Set.prototype.isSupersetOf(otherSet)

Checks if all elements in the other set exist in the current set.

javascript

a.isSupersetOf(b); // false

g. Set.prototype.isDisjointFrom(otherSet)

Checks if the two sets have no elements in common.

javascript

a.isDisjointFrom(b); // false

2. Map.prototype Additions (Bonus)

Although you asked about Set, it’s worth noting that similar convenience methods are proposed or being considered for Map (e.g., .mapValues(), .filter(), etc.).


new and upcoming methods for Map.prototype, based on current ECMAScript proposals (some already at Stage 3+ and widely supported via polyfills or in newer engines):


New Map Methods (Proposed — Stage 3)

These methods make working with Map objects more like working with arrays:


1. Map.prototype.map(callbackFn)

Returns a new Map with the same keys, but transformed values based on the callback.

javascript

const map1 = new Map([['a', 1], ['b', 2]]); const result = map1.map(([key, value]) => [key, value * 10]); // result: Map { 'a' => 10, 'b' => 20 }

2. Map.prototype.filter(callbackFn)

Returns a new Map with only the entries that pass the callback condition.

javascript

const result = map1.filter(([key, value]) => value > 1); // result: Map { 'b' => 2 }

3. Map.prototype.reduce(callbackFn, initialValue)

Reduces the map entries like Array.prototype.reduce.

javascript

const total = map1.reduce((acc, [key, value]) => acc + value, 0); // total: 3

4. Map.prototype.some(callbackFn)

Returns true if any entry passes the test.

javascript

map1.some(([key, value]) => value === 2); // true

5. Map.prototype.every(callbackFn)

Returns true if all entries pass the test.

javascript

map1.every(([key, value]) => typeof value === 'number'); // true

6. Map.prototype.find(callbackFn)

Returns the first entry (as [key, value]) that satisfies the callback.

javascript

map1.find(([key, value]) => value > 1); // ['b', 2]

Compatibility Note:

  • These methods are Stage 3 (as of 2024) and are not yet standard in all browsers.

  • You can polyfill them using libraries like core-js or use them in environments like Babel or TypeScript with appropriate settings.

Handling multiple devices for a single user in a token-based authentication system (like JWT or OAuth2)

 

1. Use Refresh Tokens with Access Tokens

  • Access tokens should be short-lived (e.g., 15 minutes).

  • Refresh tokens should be long-lived and tied to a specific device.

  • This prevents all sessions from being compromised if one token leaks.


2. Store Tokens Securely Per Device

  • Mobile apps: Use Secure Storage (e.g., Keychain on iOS, Keystore on Android).

  • Web apps: Prefer HTTP-only cookies for refresh tokens (avoid localStorage).


3. Track Devices with Unique Identifiers

  • Assign a device ID for each device upon login/registration.

  • Store it alongside the refresh token in your DB (e.g., { userId, deviceId, refreshToken, lastSeen, ipAddress }).


4. Allow Session Management

  • Provide users a “manage devices” interface.

  • Let them revoke sessions from specific devices.


5. Token Revocation Strategy

  • Use a server-side token store or blacklist mechanism to invalidate compromised tokens.

  • Maintain a list of valid refresh tokens per user/device.


6. Notify on New Device Logins

  • Alert users when a new device logs in or an existing session is reused from a different IP or location.


7. Rate Limiting & Device Limits

  • Optionally limit how many devices a user can log in to simultaneously.

  • Prevent abuse by rate-limiting login attempts.


Here's a practical example of handling multiple devices using token-based authentication (with access/refresh tokens and device tracking) using Node.js + Express + JWT + MongoDB.


1. Database Schema (MongoDB + Mongoose)

js

const mongoose = require('mongoose'); const RefreshTokenSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, deviceId: { type: String, required: true }, refreshToken: { type: String, required: true }, userAgent: String, ip: String, lastUsed: { type: Date, default: Date.now }, }); module.exports = mongoose.model('RefreshToken', RefreshTokenSchema);

2. Login Route (Issuing Tokens Per Device)

js

const jwt = require('jsonwebtoken'); const RefreshToken = require('./models/RefreshToken'); app.post('/login', async (req, res) => { const { email, password, deviceId } = req.body; const user = await User.findOne({ email }); if (!user || !(await user.comparePassword(password))) { return res.status(401).send('Invalid credentials'); } const accessToken = jwt.sign({ userId: user._id }, 'ACCESS_SECRET', { expiresIn: '15m' }); const refreshToken = jwt.sign({ userId: user._id, deviceId }, 'REFRESH_SECRET', { expiresIn: '7d' }); await RefreshToken.findOneAndUpdate( { userId: user._id, deviceId }, { refreshToken, ip: req.ip, userAgent: req.headers['user-agent'], lastUsed: new Date() }, { upsert: true } ); res.json({ accessToken, refreshToken }); });

3. Refresh Token Route (Per Device)

js

app.post('/token', async (req, res) => { const { refreshToken, deviceId } = req.body; if (!refreshToken) return res.status(401).send('Missing token'); try { const payload = jwt.verify(refreshToken, 'REFRESH_SECRET'); const storedToken = await RefreshToken.findOne({ userId: payload.userId, deviceId, refreshToken }); if (!storedToken) return res.status(403).send('Invalid session'); const newAccessToken = jwt.sign({ userId: payload.userId }, 'ACCESS_SECRET', { expiresIn: '15m' }); storedToken.lastUsed = new Date(); await storedToken.save(); res.json({ accessToken: newAccessToken }); } catch (err) { return res.status(403).send('Token expired or invalid'); } });

4. Logout from a Specific Device

js

app.post('/logout', async (req, res) => { const { deviceId } = req.body; const userId = req.user.userId; // from middleware await RefreshToken.deleteOne({ userId, deviceId }); res.send('Logged out from device'); });

5. Optional: Get All Logged-in Devices

js

app.get('/devices', async (req, res) => { const userId = req.user.userId; const devices = await RefreshToken.find({ userId }).select('-refreshToken'); res.json(devices); });

This structure supports:

  • Multiple devices per user.

  • Secure refresh token handling per device.

  • Manual session management (logout specific device, list devices).

  • Optional device fingerprinting or IP tracking.

Java Interview Questions: Security & API Implementation with Example Setup

 

Common Interview Questions on Security: Let’s break down Core JavaSpring BootJava/J2EE, and Spring with their relationships, key features, and examples to prepare you for interviews. I'll also include common interview questions and practical use cases.

  1. Authentication vs. Authorization

    • Authentication: Verifying user identity (e.g., username/password).

    • Authorization: Granting access to resources based on roles (e.g., ADMIN, USER).

  2. How to secure a Java web application?
    Use frameworks like Spring Security to enforce authentication, authorization, CSRF protection, and session management.

  3. Prevent SQL Injection
    Use prepared statements or JPA/Hibernate to avoid concatenating SQL queries.

  4. Explain CSRF Protection
    Spring Security provides CSRF tokens for state-changing requests (disabled for stateless APIs).

Common API Questions:

  1. REST Principles
    Stateless, resource-based URLs (e.g., /api/products), HTTP methods (GET, POST), JSON/XML responses.

  2. Create an API in Spring Boot
    Use @RestController, define endpoints with @GetMapping@PostMapping, etc.

  3. API Versioning
    URL path (/api/v1/products), headers, or media type versioning.


Full Example: Secured REST API with Spring Boot

Step 1: Project Setup (Spring Boot 3.x)

Dependencies (Maven pom.xml):

xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Step 2: Configure H2 Database (application.properties)

properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update

Step 3: Entity Class

java
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    // Getters and setters
}

Step 4: JPA Repository

java
public interface ProductRepository extends JpaRepository<Product, Long> { }

Step 5: Service Layer

java
@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    public Product createProduct(Product product) {
        return productRepository.save(product);
    }
}

Step 6: REST Controller

java
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.createProduct(product);
    }
}

Step 7: Security Configuration

java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/products").permitAll()
                .requestMatchers("/api/products/**").hasRole("ADMIN")
                .requestMatchers("/h2-console/**").permitAll()
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> csrf
                .ignoringRequestMatchers("/h2-console/**", "/api/**") // Disable CSRF for APIs
            )
            .headers(headers -> headers
                .frameOptions().disable() // Allow H2 console
            );

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder()
            .username("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .build();

        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN")
            .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Testing the API with Postman:

  1. GET /api/products

    • No authentication required (permitted to all).

  2. POST /api/products

    • Requires ADMIN role.

    • Headers: Authorization: Basic YWRtaW46YWRtaW4= (Base64 of admin:admin).


Explanation:

  • Security:

    • /api/products is public; /api/products/** requires ADMIN.

    • In-memory users with BCrypt password encoding.

    • CSRF disabled for APIs (stateless).

  • API Design:

    • RESTful endpoints for product management.

    • H2 database for easy setup.

1. Project Setup (Spring Boot 3.x)

Goal: Create a Spring Boot project with dependencies for web APIs, security, and database integration.

Dependencies (pom.xml):

  • Spring Web: For REST API development (@RestController@GetMapping, etc.).

  • Spring Security: For authentication/authorization.

  • Spring Data JPA: Simplifies database operations (e.g., JpaRepository).

  • H2 Database: In-memory database for quick setup (no external DB needed).

Interview Question:

  • Why use Spring Boot?
    Answer: Simplifies configuration with auto-configuration, embedded servers, and starter dependencies.


2. H2 Database Configuration (application.properties)

properties
spring.datasource.url=jdbc:h2:mem:testdb  # In-memory database
spring.h2.console.enabled=true           # Enable H2 web console
spring.jpa.hibernate.ddl-auto=update     # Auto-create tables from entities

Why:

  • ddl-auto=update: Automatically creates/updates database tables based on entity classes (useful for prototyping).

  • h2-console.enabled=true: Allows access to the H2 web console at http://localhost:8080/h2-console.

Interview Question:

  • What is ddl-auto?
    Answer: Configures Hibernate to auto-generate database schemas (options: createupdatevalidate, etc.).


3. Entity Class

java
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    // Getters/setters
}

Why:

  • @Entity: Maps the class to a database table.

  • @Id and @GeneratedValue: Auto-generates primary keys.

Interview Question:

  • What is JPA?
    Answer: Java Persistence API for ORM (Object-Relational Mapping).


4. JPA Repository

java
public interface ProductRepository extends JpaRepository<Product, Long> { }

Why:

  • Spring Data JPA provides CRUD operations out-of-the-box (e.g., save()findAll()).

  • No need to write SQL queries manually.

Interview Question:

  • What is JpaRepository?
    Answer: Interface providing CRUD and pagination methods for database operations.


5. Service Layer

java
@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
}

Why:

  • Business logic separation (controller handles HTTP, service handles logic).

  • @Autowired: Injects the repository dependency (Spring IoC container).

Interview Question:

  • What is dependency injection?
    Answer: Spring manages object creation and dependencies (e.g., @Autowired).


6. REST Controller

java
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }
}

Why:

  • @RestController: Combines @Controller and @ResponseBody (returns JSON/XML).

  • @GetMapping: Maps HTTP GET requests to /api/products.

Interview Question:

  • What is the difference between @Controller and @RestController?
    Answer: @RestController automatically serializes return objects to JSON/XML.


7. Security Configuration

java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/products").permitAll()  // Public access
                .requestMatchers("/api/products/**").hasRole("ADMIN")  // Admin-only
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults())  // Basic Auth
            .csrf(csrf -> csrf.ignoringRequestMatchers("/api/**"));  // Disable CSRF for APIs

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN")
            .build();
        return new InMemoryUserDetailsManager(admin);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Key Points:

  • authorizeHttpRequests: Defines URL-based access rules.

  • hasRole("ADMIN"): Restricts access to users with the ADMIN role.

  • httpBasic: Enables Basic Authentication (username/password in headers).

  • CSRF Disabled: APIs are stateless, so CSRF protection is unnecessary.

  • BCryptPasswordEncoder: Securely hashes passwords (never store plain text!).

Interview Questions:

  1. Why disable CSRF for APIs?
    Answer: CSRF protects against browser-based attacks. APIs (stateless) use tokens like JWT instead.

  2. What is UserDetailsService?
    Answer: Interface to load user-specific data (e.g., from a database or in-memory).


8. Testing with Postman

Example Requests:

  1. Public Endpoint (GET /api/products)

    • No authentication required.

  2. Admin-Only Endpoint (POST /api/products)

    • Headers:

      Authorization: Basic YWRtaW46YWRtaW4=

      (Base64-encoded admin:admin)

Interview Question:

  • How does Basic Authentication work?
    Answer: Credentials are sent in the Authorization header as Basic <base64(username:password)>.


Key Takeaways for Interviews

  1. Security:

    • Use Spring Security for RBAC (Role-Based Access Control).

    • Always hash passwords (e.g., BCrypt).

    • Disable CSRF for stateless APIs.

  2. APIs:

    • Follow REST conventions (resource URLs, HTTP methods).

    • Separate layers (Controller → Service → Repository).

  3. Database:

    • Use JPA/Hibernate to avoid SQL injection.

    • Prefer PreparedStatement over raw SQL.


Common Pitfalls to Mention

  • Hardcoding credentials (use environment variables or Spring Vault).

  • Storing plain-text passwords (always hash!).

  • Exposing sensitive endpoints without authorization.

This setup covers fundamental Java interview topics: securityAPI design, and database integration. Practice explaining each layer and its purpose!



1. Core Java

Key Concepts:

  • OOP Principles: Abstraction, Encapsulation, Inheritance, Polymorphism.

  • CollectionsListSetMapQueue, and their implementations (ArrayListHashMap, etc.).

  • MultithreadingThread class, RunnableExecutorService, synchronization.

  • Exception Handlingtry-catch-finally, custom exceptions.

  • JDBC: Connecting to databases using DriverManagerDataSource, etc.

Interview Questions:

  1. What is the difference between ArrayList and LinkedList?

    • ArrayList uses a dynamic array (faster for random access).

    • LinkedList uses a doubly linked list (faster for insertions/deletions).

  2. Explain polymorphism with an example.

    java
    class Animal { void sound() { System.out.println("Animal sound"); } }  
    class Dog extends Animal { void sound() { System.out.println("Bark"); } }  
    Animal a = new Dog(); // Runtime polymorphism  
    a.sound(); // Output: Bark  
  3. How does the final keyword work?

    • final variable: Value can’t change.

    • final method: Can’t be overridden.

    • final class: Can’t be inherited.


2. Java/J2EE (Jakarta EE)

Key Concepts:

  • Servlets: Java classes handling HTTP requests/responses (e.g., HttpServlet).

  • JSP: Java Server Pages for dynamic web content.

  • EJB: Enterprise JavaBeans for business logic (e.g., @Stateless@Stateful).

  • JPA: Java Persistence API for ORM (e.g., Hibernate).

  • JMS: Java Messaging Service for asynchronous communication.

Interview Questions:

  1. What is the difference between a servlet and a JSP?

    • Servlet: Java code with HTML (handles logic).

    • JSP: HTML with Java code (for presentation).

  2. What is a ServletContext?

    • Shared across the application (e.g., for storing global parameters).

  3. Explain the JPA lifecycle methods (@PrePersist@PostLoad).

    java
    @Entity
    public class Product {
        @PrePersist
        public void beforeSave() { /* Logic before saving */ }
    }

3. Spring Framework

Key Concepts:

  • Dependency Injection (DI): Inversion of Control (IoC) via @Autowired@Component, etc.

  • AOP: Aspect-Oriented Programming for cross-cutting concerns (logging, security).

  • Spring MVC: Model-View-Controller for web apps (e.g., @Controller@RequestMapping).

  • Spring Data: Simplifies database access (e.g., JpaRepository).

Interview Questions:

  1. What is the difference between @Component and @Bean?

    • @Component: Auto-detected by Spring scan (class-level).

    • @Bean: Manually defined in a @Configuration class (method-level).

  2. How does Spring MVC handle a request?

    • Request → DispatcherServlet → Controller → Model → ViewResolver → Response.

  3. What is a BeanFactory vs. ApplicationContext?

    • BeanFactory: Basic IoC container (lazy initialization).

    • ApplicationContext: Advanced (pre-loads beans, supports AOP, events, etc.).


4. Spring Boot

Key Concepts:

  • Auto-Configuration: Automatically configures beans based on classpath.

  • Starters: Pre-defined dependencies (e.g., spring-boot-starter-web).

  • Embedded Servers: Tomcat, Jetty, Undertow.

  • Actuator: Monitoring and metrics endpoints.

Example: Simple Spring Boot REST API

java
@SpringBootApplication
public class DemoApp {
    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class, args);
    }
}

@RestController
class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

Interview Questions:

  1. How does Spring Boot simplify development?

    • Auto-configuration, embedded servers, starter dependencies, and opinionated defaults.

  2. What is the purpose of spring-boot-starter-parent?

    • Parent POM for dependency management and default configurations.

  3. How to externalize configuration?

    • Use application.properties or application.yml for environment-specific settings.


5. Key Differences

Java/J2EESpringSpring Boot
Heavyweight (EJB, JNDI)Lightweight, modularZero-config, opinionated
XML configurationXML/AnnotationsAuto-configuration
Complex setupSimplified DI and AOPEmbedded server

6. Common Interview Scenarios

Scenario 1: Secure a Spring Boot API with JWT

Steps:

  1. Add spring-boot-starter-security and JWT library (e.g., jjwt).

  2. Create a JwtFilter to validate tokens.

  3. Configure SecurityFilterChain to authenticate requests.

Code Snippet:

java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/auth/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}

Scenario 2: Implement CRUD with Spring Data JPA

Steps:

  1. Define an Entity (e.g., User).

  2. Extend JpaRepository<User, Long>.

  3. Use @Service and @RestController to expose endpoints.


7. Best Practices

  1. Core Java:

    • Use try-with-resources for JDBC connections.

    • Prefer StringBuilder over String concatenation in loops.

  2. Spring:

    • Use constructor injection instead of field injection.

    • Leverage @Transactional for database operations.

  3. Spring Boot:

    • Use profiles (@Profile("dev")) for environment-specific config.

    • Monitor APIs with Spring Boot Actuator.


8. Common Tools & Frameworks

  • Build Tools: Maven, Gradle.

  • Testing: JUnit, Mockito, Testcontainers.

  • Security: Spring Security, OAuth2, JWT.

  • Database: Hibernate, Flyway, Liquibase.


9. Interview Prep Checklist

  1. Core Java: Practice multithreading, collections, and exception handling.

  2. Spring: Understand DI, AOP, and MVC flow.

  3. Spring Boot: Know auto-configuration, starters, and Actuator.

  4. Java/J2EE: Be ready to compare with Spring-based solutions.

latest ECMAScript proposals and releases (as of ECMAScript 2024), several enhancements have been made to built-in objects like Set

JavaScript continues to evolve, and in the latest ECMAScript proposals and releases (as of ECMAScript 2024), several enhancements have been ...

Best for you