| ๐ฅ Issue | ๐ญ Easy Story | ๐ Hikari Metrics | ✅ Fix | ๐ง Memory Magic |
|---|---|---|---|---|
| ๐ Slow SQL | Customer sits in restaurant for 1 hour | Active=100%, Idle=0 | Add Index, Optimize Query | Connection Busy Too Long |
| ⏳ Long Transaction | Customer eating + watching movie | Active High, Tx Duration High | Short Transactions | Never Hold Connection During API Calls |
| ๐ฐ Connection Leak | Customer takes table home | Active Never Decreases | Close Resources | Borrow → Return |
| ๐ Pool Too Small | 100 Customers, 5 Tables | Pending Threads High | Increase Pool Carefully | More Tables Needed |
| ๐ฅ Pool Too Large | 1000 Tables in Small Restaurant | DB CPU 100% | Reduce Pool | Big Pool ≠ Fast System |
| ⚔️ Deadlock | Two Customers Fighting For Same Table | DB Lock Wait | Fix SQL Order | Everyone Waiting |
| ☸️ Too Many Pods | 20 Restaurants Sharing One Kitchen | DB Connection Limit Hit | Reduce Pool/Scale DB | Pods × Pool = Total Connections |
| ๐งต Thread Pool > DB Pool | 500 People Standing Outside | Pending Threads Skyrocket | Align Pools | Threads Fight For Connections |
| ๐ DB Restart/Stale Connection | Kitchen Closed Suddenly | Connection Validation Failures | Keepalive + MaxLifetime | Refresh Connections |
Sidebar content
Wednesday, September 16, 2026
HikariCP "Connection Not Available" Troubleshooting Matrix
Monday, August 17, 2026
Java 8 Complete Reference
Java 8 Complete Feature Guide
A practical, detailed guide to the release that changed modern Java development. Learn lambdas, functional interfaces, streams, Optional, the Date and Time API, CompletableFuture, collection enhancements, common mistakes, and senior-level interview questions.
1What Changed in Java 8?
Java 8 brought functional-style programming to Java while retaining its object-oriented foundation. The major changes include lambda expressions, method references, functional interfaces, default methods, streams, Optional, a modern Date and Time API, and asynchronous composition through CompletableFuture.
2Lambda Expressions
A lambda expression provides an implementation for the single abstract method of a functional interface.
(parameters) -> expression
(parameters) -> {
statements;
}Before Java 8
Collections.sort(employees, new Comparator<Employee>() {
@Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});Using a lambda
employees.sort((first, second) ->
first.getName().compareTo(second.getName()));Variable capture
int minimumSalary = 50_000; // Effectively final
employees.stream()
.filter(employee -> employee.getSalary() > minimumSalary)
.forEach(System.out::println);3Functional Interfaces
@FunctionalInterface
interface SalaryRule {
boolean test(Employee employee);
}| Interface | Input and output | Method | Use |
|---|---|---|---|
| Predicate<T> | T to boolean | test() | Filtering |
| Function<T,R> | T to R | apply() | Transformation |
| Consumer<T> | T to void | accept() | Performing an action |
| Supplier<T> | No input to T | get() | Lazy object creation |
| UnaryOperator<T> | T to T | apply() | Same-type transformation |
| BinaryOperator<T> | T and T to T | apply() | Combining values |
Predicate<Employee> highPaid =
employee -> employee.getSalary() > 100_000;
Function<Employee, String> employeeName = Employee::getName;
Consumer<Employee> printEmployee = System.out::println;
Supplier<List<Employee>> listFactory = ArrayList::new;
Predicate<Employee> highPaidITEmployee = highPaid.and(
employee -> "IT".equals(employee.getDepartment()));4Method and Constructor References
Static method
numbers.stream()
.reduce(Integer::sum);Bound instance method
employees.forEach(
System.out::println);Unbound instance method
employees.stream()
.map(Employee::getName);Constructor reference
Supplier<List<Employee>> factory =
ArrayList::new;5Default and Static Interface Methods
interface Auditable {
default String auditMessage() {
return "Audited at " + Instant.now();
}
static boolean isValid(String value) {
return value != null && !value.trim().isEmpty();
}
}Conflict-resolution rules
- A concrete class method wins over an interface default method.
- A method from a more specific child interface wins over its parent interface.
- If unrelated interfaces declare conflicting defaults, the implementing class must override the method.
interface A {
default void print() { System.out.println("A"); }
}
interface B {
default void print() { System.out.println("B"); }
}
class Example implements A, B {
@Override
public void print() {
A.super.print();
}
}6Stream API Deep Dive
List<String> names = employees.stream()
.filter(employee -> employee.getSalary() > 80_000)
.sorted(Comparator.comparing(Employee::getSalary).reversed())
.map(Employee::getName)
.collect(Collectors.toList());Stateless
filter, map and flatMap process elements independently.
Stateful
distinct and sorted may retain information about previously seen elements.
Terminal
collect, reduce, count, match, find and forEach trigger execution.
map() versus flatMap()
List<String> uniqueSkills = employees.stream()
.flatMap(employee -> employee.getSkills().stream())
.map(String::toUpperCase)
.distinct()
.sorted()
.collect(Collectors.toList());reduce()
double totalSalary = employees.stream()
.map(Employee::getSalary)
.reduce(0.0, Double::sum);
int total = IntStream.rangeClosed(1, 100).sum();Short-circuit operations
boolean anyHighPaidEmployee = employees.stream()
.anyMatch(employee -> employee.getSalary() > 200_000);
Optional<Employee> firstITEmployee = employees.stream()
.filter(employee -> "IT".equals(employee.getDepartment()))
.findFirst();7Collectors and Employee Examples
Group by department
Map<String, List<Employee>> byDepartment =
employees.stream().collect(Collectors.groupingBy(
Employee::getDepartment));Count per department
Map<String, Long> countByDepartment =
employees.stream().collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()));Maximum salary employee
Map<String, Optional<Employee>> highestPaid =
employees.stream().collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.maxBy(Comparator.comparing(
Employee::getSalary))));Average salary
Map<String, Double> averageSalary =
employees.stream().collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(
Employee::getSalary)));Third-highest distinct salary, department-wise
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment))
.forEach((department, employeeList) -> {
Double salary = employeeList.stream()
.map(Employee::getSalary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(2)
.findFirst()
.orElse(null);
System.out.println(department + " -> " + salary);
});Why distinct? The third-highest salary normally means the third distinct salary. Duplicate salary values should share the same rank.
toMap() with duplicate-key handling
Map<String, Employee> employeeByName = employees.stream()
.collect(Collectors.toMap(
Employee::getName,
Function.identity(),
BinaryOperator.maxBy(
Comparator.comparing(Employee::getSalary))));8Parallel Streams and Spliterator
double totalSalary = employees.parallelStream()
.mapToDouble(Employee::getSalary)
.sum();Consider parallel streams when
- The dataset is large and in memory.
- Work is CPU-intensive and independent.
- The source can be split efficiently.
- Reduction is associative.
Avoid them when
- Operations perform blocking I/O.
- The collection is small.
- Shared mutable state is involved.
- Ordering costs dominate.
- Common-pool contention is risky.
Spliterator supports both traversal and partitioning. Characteristics such as ORDERED, DISTINCT, SORTED, SIZED and SUBSIZED help the stream framework understand a data source.
9Optional
Optional<Employee> employeeOptional = repository.findById(id);
String name = employeeOptional
.filter(employee -> employee.getSalary() > 50_000)
.map(Employee::getName)
.orElse("Unknown");orElse()
value.orElse(createDefault());
// createDefault() is called eagerlyorElseGet()
value.orElseGet(this::createDefault);
// Supplier runs only when emptyFlatten nested Optional values
Optional<String> city = employeeOptional
.flatMap(Employee::getAddress)
.map(Address::getCity);10Modern Date and Time API
| Type | Purpose |
|---|---|
| LocalDate | Date without time or zone |
| LocalTime | Time without date or zone |
| LocalDateTime | Date and time without a zone |
| Instant | A point on the UTC timeline |
| ZonedDateTime | Date and time with a region-based zone |
| OffsetDateTime | Date and time with a numeric UTC offset |
| Period | Date-based amount |
| Duration | Time-based amount |
LocalDate joiningDate = LocalDate.of(2020, Month.JANUARY, 15);
long years = ChronoUnit.YEARS.between(
joiningDate, LocalDate.now());
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = joiningDate.format(formatter);
Instant currentInstant = Instant.now();
ZonedDateTime indiaTime = currentInstant.atZone(
ZoneId.of("Asia/Kolkata"));11CompletableFuture
CompletableFuture<Employee> employeeFuture =
CompletableFuture.supplyAsync(
() -> loadEmployee(id), executor);
CompletableFuture<String> result = employeeFuture
.thenApply(Employee::getName)
.exceptionally(exception -> "Unknown");Combine independent calls
CompletableFuture<Profile> profileFuture =
CompletableFuture.supplyAsync(this::loadProfile, executor);
CompletableFuture<Salary> salaryFuture =
CompletableFuture.supplyAsync(this::loadSalary, executor);
CompletableFuture<EmployeeView> viewFuture =
profileFuture.thenCombine(
salaryFuture, EmployeeView::new);| Method | Purpose |
|---|---|
| thenApply() | Transform a completed result |
| thenCompose() | Chain and flatten a dependent future |
| thenCombine() | Combine two independent results |
| allOf() / anyOf() | Coordinate multiple futures |
| handle() | Process either a result or exception |
| exceptionally() | Recover from a failure |
12Collection, Map and Comparator Improvements
Collection operations
employees.forEach(System.out::println);
employees.removeIf(employee -> !employee.isActive());
employees.replaceAll(this::normalize);Map operations
employeeMap.forEach((id, employee) ->
System.out.println(employee));
Employee employee = employeeMap.getOrDefault(id, defaultEmployee);
employeeMap.putIfAbsent(id, newEmployee);
departmentEmployees
.computeIfAbsent(department, key -> new ArrayList<>())
.add(employee);
wordCount.merge(word, 1, Integer::sum);Put Map values into another list
List<Employee> employeeList =
new ArrayList<>(employeeMap.values());Comparator composition
Comparator<Employee> employeeComparator =
Comparator.comparing(Employee::getDepartment)
.thenComparing(
Employee::getSalary,
Comparator.reverseOrder())
.thenComparing(
Employee::getName,
Comparator.nullsLast(
String.CASE_INSENSITIVE_ORDER));HashSet.add() return value
Set<Integer> seen = new HashSet<>();
numbers.stream()
.filter(number -> !seen.add(number))
.forEach(System.out::println);HashSet.add() returns true when the element is inserted and false when an equal element already exists. Therefore, !seen.add(number) selects duplicates.
13Other Important Java 8 Features
Base64
String encoded = Base64.getEncoder()
.encodeToString("Java 8".getBytes(
StandardCharsets.UTF_8));
String decoded = new String(
Base64.getDecoder().decode(encoded),
StandardCharsets.UTF_8);StringJoiner
StringJoiner joiner =
new StringJoiner(", ", "[", "]");
joiner.add("Java").add("Spring");Repeatable annotations
@Repeatable(Roles.class)
@interface Role { String value(); }
@interface Roles { Role[] value(); }
@Role("ADMIN")
@Role("AUDITOR")
class UserService {}Files.lines()
try (Stream<String> lines =
Files.lines(logFilePath)) {
long errors = lines
.filter(line -> line.contains("ERROR"))
.count();
}- Metaspace: Native-memory Metaspace replaced PermGen for class metadata.
- Target-type inference: Generic type inference was improved in more invocation contexts.
- Parameter names: Reflection can read parameter names when compiled using
-parameters. - Concurrency: Java 8 added classes such as StampedLock, LongAdder and LongAccumulator.
- Nashorn: Java 8 included a JavaScript engine, but it should not be chosen for modern application designs.
14Common Java 8 Mistakes
Reusing a stream
A stream is consumed after a terminal operation and cannot be reused.
Shared mutation
Avoid updating external mutable collections from a stream pipeline.
Optional.get()
Prefer map, flatMap, orElseGet or orElseThrow.
Assuming null safety
Streams do not make null elements or mappers automatically safe.
Incorrect time type
Do not use LocalDateTime when you need a global timestamp.
Blind parallelization
Measure before using parallel streams and avoid blocking calls.
15Java 8 Interview Questions
Why can a functional interface contain default and static methods?
The single-abstract-method rule counts abstract instance methods. Default and static methods already have implementations.
What is the difference between a collection and a stream?
A collection stores elements and supports repeated traversal. A stream is a consumable, normally lazy computation pipeline using internal iteration.
What is the difference between map() and flatMap()?
map() transforms each input into one result. flatMap() transforms inputs into streams and flattens those streams into one pipeline.
Why must reduce operations be associative?
Parallel execution can combine partitions in different groupings. Associativity ensures those groupings produce the same result.
findFirst() versus findAny()?
findFirst() respects encounter order. findAny() allows more freedom and may be useful when any matching result is acceptable.
orElse() versus orElseGet()?
orElse() evaluates its argument eagerly. orElseGet() invokes its supplier only when the Optional is empty.
thenApply() versus thenCompose()?
thenApply() maps a value to another value. thenCompose() chains a function that returns a future and flattens the nested future.
Why can parallelStream() be risky in a web application?
It commonly uses the shared ForkJoin common pool. Blocking work, request concurrency, small tasks and ordering requirements can create unpredictable performance.
What is the difference between intermediate and terminal stream operations?
Intermediate operations return another stream and are normally lazy. Terminal operations produce a result or side effect and trigger execution.
What happens when toMap() receives duplicate keys?
It throws an exception unless a merge function is supplied to decide how duplicate values should be combined or selected.
Saturday, July 13, 2024
Java Unit Test MCQ
Question 1
Which framework is most commonly used for unit testing in Java?
JUnit
TestNG
Mockito
Selenium
Answer:
JUnit
Question 2
In JUnit 5, which annotation is used to indicate a test method?
@TestCase
@RunWith
@Test
@Before
Answer:
@Test
Question 3
Which JUnit annotation is used to execute some code before each test method?
@BeforeAll
@After
@BeforeEach
@BeforeTest
Answer:
@BeforeEach
Question 4
Which method in JUnit is used to check if two objects are equal?
assertSame
assertTrue
assertEquals
assertNotNull
Answer:
assertEquals
Question 5
Which of the following is a mocking framework often used in Java unit tests?
TestNG
Mockito
JUnit
Cucumber
Answer:
Mockito
Question 6
In Mockito, which method is used to create a mock object?
mock()
createMock()
mockObject()
newMock()
Answer:
mock()
Question 7
What does the @Mock annotation do in Mockito?
It creates a real object
It creates a mock object
It verifies a method call
It initializes a mock object
Answer:
It creates a mock object
Question 8
Which JUnit annotation is used to run a piece of code after all tests in the test class have been run?
@AfterEach
@AfterAll
@AfterTest
@After
Answer:
@AfterAll
Question 9
In TestNG, which annotation is equivalent to JUnit's @BeforeEach?
@BeforeTest
@BeforeMethod
@BeforeClass
@BeforeSuite
Answer:
@BeforeMethod
Question 10
Which Mockito method is used to verify that a method was called with specific arguments?
verify()
check()
assert()
confirm()
Answer:
verify()
Question 11
In JUnit 5, which annotation is used to disable a test method?
@Ignore
@Disabled
@Skip
@Deactivate
Answer:
@Disabled
Question 12
Which of the following is not a lifecycle method in JUnit 5?
@BeforeEach
@AfterEach
@BeforeClass
@BeforeAll
Answer:
@BeforeClass
Question 13
Which of the following assertions is used to check if a condition is false in JUnit?
assertTrue()
assertFalse()
assertNull()
assertNotNull()
Answer:
assertFalse()
Question 14
What is the primary purpose of unit testing?
To test the entire application as a whole
To test individual units or components in isolation
To test the user interface
To test the performance of the application
Answer:
To test individual units or components in isolation
Question 15
In Mockito, which method is used to return a specific value when a method is called?
when().thenReturn()
doReturn().when()
mock().thenReturn()
verify().thenReturn()
Answer:
when().thenReturn()
Question 16
Which JUnit annotation is used to provide a timeout for a test method?
@Timeout
@Test(timeout = 1000)
@TimeLimit
@Test(timeout = 1)
Answer:
@Timeout
Question 17
Which of the following is not a valid JUnit assertion?
assertEquals()
assertNotNull()
assertThrows()
assertEmpty()
Answer:
assertEmpty()
Question 18
Which JUnit 5 annotation is used to run a test multiple times?
@Repeat
@RepeatedTest
@LoopTest
@TestRepeat
Answer:
@RepeatedTest
Question 19
In TestNG, which annotation is used to indicate that a method should be executed before any test methods in the current class?
@BeforeTest
@BeforeClass
@BeforeMethod
@BeforeSuite
Answer:
@BeforeClass
Question 20
In Mockito, how can you mock a method to throw an exception?
when(methodCall).thenThrow(new Exception())
doThrow(new Exception()).when(methodCall)
throwException(new Exception()).when(methodCall)
when(methodCall).throw(new Exception())
Answer:
when(methodCall).thenThrow(new Exception())
Friday, July 12, 2024
Create a function that checks the connection status and reconnects if necessary
const redis = require('redis');
const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { client.quit(); client.connect((err) => { if (err) { console.error('Failed to reconnect to Redis:', err); reject(err); } else { console.log('Reconnected to Redis'); resolve(); } }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });- Use the following code to check the connection and reconnect if necessary:
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) let client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Connection check timed out')); }, 5000); // 5 seconds timeout for the connection check pingAsync().then(pong => { clearTimeout(timeout); if (pong === 'PONG') { console.log('Redis connection is healthy'); resolve(); } else { console.log('Unexpected response from Redis:', pong); reconnect().then(resolve).catch(reject); } }).catch(err => { clearTimeout(timeout); console.error('Redis connection error:', err); reconnect().then(resolve).catch(reject); }); }); } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Reconnection timed out')); }, 10000); // 10 seconds timeout for reconnection // Quit the current client client.quit(() => { // Create a new client instance client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client client.on('connect', () => { clearTimeout(timeout); console.log('Reconnected to Redis'); resolve(); }); client.on('error', (err) => { clearTimeout(timeout); console.error('Failed to reconnect to Redis:', err); reject(err); }); }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });
FlushDB in Redis in node js
const express = require('express');
const redis = require('redis'); const { promisify } = require('util'); const app = express(); const PORT = 3000; // Replace with your desired port // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `flushdb` method const flushdbAsync = promisify(client.flushdb).bind(client); // Function to flush the Redis database async function flushRedisDatabase() { try { const result = await flushdbAsync(); return { message: 'Database flushed successfully', result }; } catch (err) { console.error('Error flushing database:', err); throw err; } } // REST endpoint to flush the Redis database app.post('/flushdb', async (req, res) => { try { const response = await flushRedisDatabase(); res.status(200).json(response); } catch (err) { res.status(500).json({ error: 'Error flushing database', details: err.message }); } }); // Start the Express server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); // Additional Redis client event handlers for better debugging client.on('connect', () => { console.log('Connected to Redis'); }); client.on('error', (err) => { console.error('Redis error:', err); }); client.on('ready', () => { console.log('Redis client ready'); }); client.on('reconnecting', () => { console.log('Reconnecting to Redis...'); }); client.on('end', () => { console.log('Redis connection closed'); });
Wednesday, July 10, 2024
Redis connection in node js
import redis from 'redis';
// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { // options.error contains the error object returned by the last attempt to connect if (options.error && options.error.code === 'ECONNREFUSED') { // If the connection was refused by the server, log the error and stop retrying console.error('The server refused the connection'); return new Error('The server refused the connection'); } // options.total_retry_time is the total time (in milliseconds) that the client has been trying to reconnect if (options.total_retry_time > 1000 * 60 * 60) { // If the total retry time exceeds 1 hour, log the error and stop retrying console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } // options.attempt is the number of retry attempts so far if (options.attempt > 10) { // If the number of retry attempts exceeds 10, log the error and stop retrying console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time, which increases with each attempt // options.attempt * 100 gives a delay that increases by 100ms with each attempt // Math.min ensures the delay does not exceed 3000ms (3 seconds) return Math.min(options.attempt * 100, 3000); } }); // Event listener for successful connection client.on('connect', function() { console.log('Redis client connected'); }); // Event listener for errors client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;Redis connection in node js
import redis from 'redis';
// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { if (options.error && options.error.code === 'ECONNREFUSED') { // End reconnecting on a specific error and flush all commands with a individual error console.error('The server refused the connection'); return new Error('The server refused the connection'); } if (options.total_retry_time > 1000 * 60 * 60) { // End reconnecting after a specific timeout and flush all commands with a individual error console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } if (options.attempt > 10) { // End reconnecting with built in error console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time return Math.min(options.attempt * 100, 3000); } }); client.on('connect', function() { console.log('Redis client connected'); }); client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;Thursday, June 13, 2024
Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws
Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws
const express = require('express');
const redis = require('redis'); const app = express(); const port = 3000; // Replace with your actual hostname and port const client = redis.createClient({ host: 'your-elasticache-hostname', port: your-elasticache-port }); client.on('error', (err) => { console.log("Error " + err); }); app.get('/flushall', (req, res) => { client.flushdb((err, succeeded) => { if (err) { res.status(500).send({ error: 'Failed to flush Redis cache' }); } else { res.send({ message: 'Redis cache successfully flushed' }); } }); }); app.listen(port, () => { console.log(`App running on port ${port}`); });Sunday, May 19, 2024
Friday, February 16, 2024
what is meant by --max-request-journal-entries and --no-request-journal in wiremock configuration
max-request-journal-entries and no-request-journal in wiremock configuration
In WireMock, the request journal is a built-in feature that keeps a record of incoming requests and their corresponding responses. It can be helpful for debugging and analysis purposes.
--max-request-journal-entries is an option that allows you to set a limit on the number of requests that the request journal stores. When this limit is reached, older requests will be removed from the journal to make room for new ones. By setting this option, you can control the memory usage of the request journal.
For example, using --max-request-journal-entries=10000 will limit the request journal to store a maximum of 10,000 requests.
--no-request-journal is an option that disables the request journal entirely. When this option is used, WireMock will not store any requests or responses in the request journal. Disabling the request journal can help reduce memory consumption and improve performance, especially during load testing or in production environments where request logging is not necessary.
In summary:
--max-request-journal-entries: Sets a limit on the number of requests stored in the request journal.
--no-request-journal: Disables the request journal completely.
Thursday, January 18, 2024
Sort an array of 0s, 1s and 2s | Dutch National Flag problem
Sort an array of 0s, 1s and 2s |
Dutch National Flag problem
๐๐๐๐๐
/*
* This program defines a sortArray() method that sorts
* an array of 0s, 1s, and 2s using
* the Dutch National Flag algorithm.
*/
public class Sort012 {
public static void swap(int[] arr,int i,int j) {
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void sortArray(int[] arr) {
int low =0;
int mid =0;
int high =arr.length-1;
while(mid<=high) {
switch (arr[mid]) {
case 0:
swap(arr,low,mid);
low++;
mid++;
break;
case 1:
mid++;
break;
case 2:
swap(arr,mid,high);
high--;
break;
default:
break;
}
}
}
public static void main(String... aa) {
int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};
sortArray(arr);
for(int i:arr) {
System.out.print(i+" ");
}
}
}
Output:
0 0 0 0 1 1 1 1 2 2 2 2
Wednesday, January 17, 2024
Merge two sorted linked lists
Merge two sorted linked lists
public class MergeLinkedLists {
static class ListNode {
int val;
ListNode next;
public ListNode() {}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode mergedList = new ListNode();
ListNode current = mergedList;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
current.next = list1;
list1 = list1.next;
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next;
}
if (list1 != null) {
current.next = list1;
} else {
current.next = list2;
}
return mergedList.next;
}
public static void main(String[] args) {
// Example usage:
ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
ListNode mergedList = mergeTwoLists(list1, list2);
while (mergedList != null) {
System.out.print(mergedList.val + " ");
mergedList = mergedList.next;
}
}
}
Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space
Output:
1 1 2 3 4 4
Geeks link:
Monday, January 15, 2024
Python script to automate login and extract cookie
pip install requests
*****************create file*****************
import requests
url_login = "https://example.com/login" # Replace with the actual login URL url_after_login = "https://example.com/next" # Replace with the actual URL after login # Replace with your actual username and password payload = { "username": "your_username", "password": "your_password" } # Create a session to persist cookies session = requests.Session() # Perform the login response_login = session.post(url_login, data=payload) # Check if login was successful (replace '200' with the appropriate success status code) if response_login.status_code == 200: print("Login successful") # Perform the action after login (e.g., skip OTP) response_after_login = session.get(url_after_login) # Get the value of the desired cookie (replace 'cookie_name' with the actual cookie name) cookie_value = session.cookies.get("cookie_name") if cookie_value: print(f"The value of the cookie is: {cookie_value}") else: print("The desired cookie was not found.") else: print("Login failed.")Thursday, January 4, 2024
Graph QL Simple working example
Here's a simple working tutorial on creating a GraphQL server using Node.js and Express, with a basic query and mutation. We'll be using the Apollo Server Express library to create the GraphQL server.
- Install Node.js: If you don't have Node.js installed, download and install it from the official website: https://nodejs.org/
- Create a new project folder: Create a new folder for your project and navigate to it in your terminal or command prompt.
- Initialize the project: Run the following command to initialize a new Node.js project:
npm init -y
- Install required packages: Install Express, Apollo Server Express, and GraphQL using the following command:
npm install express apollo-server-express graphql
- Create the GraphQL schema: Create a file named
schema.graphqlin your project folder and add the following schema definition:
type Query { hello: String } type Mutation { setMessage(message: String!): String }
Here we define a simple query hello that returns a string and a mutation setMessage that takes a string as input and returns a string.
- Create the server: Create a file named
index.jsin your project folder and add the following code:
const express = require("express"); const { ApolloServer, gql } = require("apollo-server-express"); const fs = require("fs"); // Read the schema from the schema.graphql file const typeDefs = gql(fs.readFileSync("schema.graphql", "utf8")); // Set up the resolvers const resolvers = { Query: { hello: () => "Hello, world!", }, Mutation: { setMessage: (_, { message }) => message, }, }; // Create the Apollo Server const server = new ApolloServer({ typeDefs, resolvers }); // Create the Express app const app = express(); // Apply the Apollo middleware to the Express app server.applyMiddleware({ app }); // Start the server const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log(`GraphQL server running at http://localhost:${PORT}${server.graphqlPath}`) );
In this code, we create a simple Express app and an Apollo Server with the schema and resolvers. The hello query returns a static string, and the setMessage mutation returns the input message.
- Start the server: Run the following command in your terminal or command prompt:
node index.js
Your GraphQL server should now be running at http://localhost:4000/graphql.
- Test your GraphQL server: Open a web browser and navigate to http://localhost:4000/graphql. You should see the GraphQL Playground interface. Run the following query and mutation in the playground:
query { hello } mutation { setMessage(message: "This is a test message!") }
You should see the appropriate responses for the query and mutation.
That's it! You now have a simple working GraphQL server using Node.js, Express, and Apollo Server Express. You can expand the schema and resolvers to handle more complex data and operations as needed.
Create a Digital Clock using HTML and JavaScript
Create a Digital Clock using HTML and JavaScript <! DOCTYPE html> < html > < head > ...
Followers
Search This Blog
Popular Posts
-
Software Development Tools Presentation From the moment you begin developing software, whether as a freelancer for a startup or wo...
-
CDAC Certifications Courses List IT Applications Certificate Course in Business Computing Certificate Course in Global su...
-
MG-CEIT Course Feedback Form Step1: Like below three pages for the updated course information ...
-
Merge two sorted linked lists public class MergeLinkedLists { static class ListNode { int val ; ListNode next ; ...
-
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout...
-
Question 1 Which framework is most commonly used for unit testing in Java? JUnit TestNG Mockito Selenium Answer: JUnit Question 2 I...
-
max-request-journal-entries and no-request-journal in wiremock configuration In WireMock, the request journal is a built-in feature that ke...
-
import redis from 'redis'; // Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhos...
-
const express = require('express'); const redis = require('redis'); const { promisify } = require('util'); const ...
-
import redis from 'redis'; // Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhos...