<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:gd="http://schemas.google.com/g/2005" xmlns:georss="http://www.georss.org/georss" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-4382912182462653256</atom:id><lastBuildDate>Sat, 03 Oct 2026 16:05:54 +0000</lastBuildDate><category>java</category><category>Spring Boot</category><category>java 8</category><category>Microservices</category><category>Tech-Projects</category><category>String Handling</category><category>INTERVIEW</category><category>Hibernate</category><category>Java Networking</category><category>SQL</category><category>Servlets</category><category>Spring</category><category>java Netbeans</category><category>MAPPING</category><category>Multithreading</category><category>Rest API</category><category>SQL TUTORIAL</category><category>Encoding &amp; Decoding</category><category>Excel Code</category><category>Game</category><category>Interfaces</category><category>LDAP</category><category>OAuth2 Security</category><category>Packages and Interfaces</category><category>design patterns</category><category>AI-CHATBOT</category><category>Digital Clock</category><category>Email</category><category>Exceptions Handling</category><category>JAVA EXPLORING NIO</category><category>JWT Token</category><category>Single Sign-On (SSO)</category><category>Spring MVC</category><category>SpringAI</category><category>Stream API</category><category>Analog Clock</category><category>Angular</category><category>CONTROL STATEMENT</category><category>Clock</category><category>Collection</category><category>Constructor</category><category>Cross-Origin</category><category>DATABASE KEYS</category><category>DataBase Connection</category><category>Date Logic</category><category>Eureka Services</category><category>ExceptionHandler</category><category>External Jar</category><category>Factory Design Patterns</category><category>FingerPrint</category><category>Functional Interface</category><category>IOC</category><category>JPA</category><category>JSON</category><category>Javascript</category><category>Key Features</category><category>Lambda Lambda Expressions</category><category>Ludo Game</category><category>Maven</category><category>Metadata</category><category>Multiples DATABASE Connection</category><category>OOPs</category><category>PDF Code</category><category>PHP</category><category>Predicate In Java 8</category><category>RAG</category><category>SQL FUNCTION</category><category>SQL JOIN</category><category>SSL</category><category>Snake Game</category><category>Tomcat configuration</category><category>Type Casting</category><category>XML payload</category><category>cron job scheduler</category><category>iReport</category><category>java Sorting</category><category>jsp</category><category>log4j</category><category>smtp</category><category>zipCompress</category><title>software Programming</title><description>Development Learning</description><link>https://a143mk.blogspot.com/</link><managingEditor>noreply@blogger.com (A143MK PROGRAMMING)</managingEditor><generator>Blogger</generator><openSearch:totalResults>112</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><language>en-us</language><itunes:explicit>yes</itunes:explicit><itunes:subtitle>This is a a143mk blog based on experience and who are always passionate about their work. We are here to explore the knowledge, ideas and concepts behind new technologies like software development, web/desktop/mobile/applications, with knowledge skills li</itunes:subtitle><itunes:category text="Technology"><itunes:category text="Software How-To"/></itunes:category><itunes:owner><itunes:email>noreply@blogger.com</itunes:email></itunes:owner><xhtml:meta content="noindex" name="robots" xmlns:xhtml="http://www.w3.org/1999/xhtml"/><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5125387930905147209</guid><pubDate>Sun, 27 Sep 2026 09:12:12 +0000</pubDate><atom:updated>2026-09-27T05:14:12.763-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">AI-CHATBOT</category><category domain="http://www.blogger.com/atom/ns#">RAG</category><category domain="http://www.blogger.com/atom/ns#">SpringAI</category><title>How to create an AI and RAG chatbot using Spring AI and a Web HTML page.</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;R&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;etrieval-Augmented Generation (RAG)&lt;br /&gt;
First, you need to select an LLM (Large Language Model) that Spring AI will use to communicate: Instead of relying solely on an LLM's pre-trained knowledge, RAG fetches relevant context from your own data sources (like databases, PDFs, or internal documentation) at runtime and passes that information along with the user prompt to the LLM&lt;b&gt;.&lt;/b&gt;
&lt;br /&gt;&lt;b&gt;Step 1: Core Concepts of RAG&lt;/b&gt;
&lt;br /&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;&amp;nbsp;Ingestion &amp;amp; Embedding (Offline / Pre-processing):
&lt;/b&gt; Raw documents (PDF, TXT, HTML) are read and split into smaller text chunks. An Embedding Model converts these text chunks into numerical vectors. The vectors and text chunks are stored in a Vector Store (e.g., PgVector, ChromaDB, Pinecone, Redis).
&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;Retrieval (Runtime):&lt;/b&gt;
 When a user submits a query, Spring AI converts the query into a vector and searches the Vector Store for the most semantically relevant document chunks.
&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;Augmentation &amp;amp; Generation:&lt;/b&gt;
 Spring AI automatically combines the user query and the retrieved documents into an augmented prompt.  The augmented prompt is sent to the LLM, which uses the provided context to generate an accurate, hallucination-free answer.
&lt;/li&gt;&lt;/ol&gt;
&lt;b&gt;Key RAG Components in Spring AI:&lt;/b&gt;&lt;br /&gt;
Spring AI simplifies RAG integration through familiar Spring abstractions: DocumentReader &amp;amp; TextSplitter: Interfaces to ingest documents (e.g., using Apache Tika) and break them into processable chunks.
&lt;br /&gt;
&lt;b&gt;VectorStore:&lt;/b&gt; A unified Java abstraction for vector databases (supports pgvector, Redis, Pinecone, Qdrant, Milvus, ChromaDB, etc.).&lt;br /&gt;
&lt;b&gt;Advisor API (QuestionAnswerAdvisor):&lt;/b&gt; A high-level abstraction that automatically intercepts ChatClient prompts, queries the VectorStore, appends retrieved documents to the prompt context, and passes it to the LLM.
&lt;br /&gt;
&lt;b&gt;RetrievalAugmentationAdvisor:&lt;/b&gt; A modular API for advanced RAG patterns, enabling features like multi-query expansion, document re-ranking, and dynamic metadata filtering.
&lt;br /&gt;&lt;b&gt;
Step 2: Implementing Basic RAG with Spring AI
&lt;/b&gt;&lt;br /&gt;In this step, we configure the Spring Boot AI application using Spring Initializr (https://start.spring.io/); we have previously covered how to perform this configuration.
Here, we will explain the coding process step-by-step.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Step 2.1: Check the dependencies in the `pom.xml` file and ensure they match your project setup.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="40"&gt; &lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;parent&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
		&lt;version&gt;4.1.1&lt;/version&gt;
		&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
	&lt;/parent&gt;
	&lt;groupId&gt;a143mk.AI&lt;/groupId&gt;
	&lt;artifactId&gt;aiChatclient&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;name/&gt;
	&lt;description/&gt;
	&lt;url/&gt;
	&lt;licenses&gt;
		&lt;license/&gt;
	&lt;/licenses&gt;
	&lt;developers&gt;
		&lt;developer/&gt;
	&lt;/developers&gt;
	&lt;scm&gt;
		&lt;connection/&gt;
		&lt;developerConnection/&gt;
		&lt;tag/&gt;
		&lt;url/&gt;
	&lt;/scm&gt;
	&lt;properties&gt;
		&lt;java.version&gt;17&lt;/java.version&gt;
		&lt;spring-ai.version&gt;2.0.1&lt;/spring-ai.version&gt;
	&lt;/properties&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-webmvc&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
			&lt;artifactId&gt;spring-ai-starter-model-ollama&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
			&lt;artifactId&gt;spring-ai-vector-store&lt;/artifactId&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-webmvc-test&lt;/artifactId&gt;
			&lt;scope&gt;test&lt;/scope&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
	&lt;dependencyManagement&gt;
		&lt;dependencies&gt;
			&lt;dependency&gt;
				&lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
				&lt;artifactId&gt;spring-ai-bom&lt;/artifactId&gt;
				&lt;version&gt;${spring-ai.version}&lt;/version&gt;
				&lt;type&gt;pom&lt;/type&gt;
				&lt;scope&gt;import&lt;/scope&gt;
			&lt;/dependency&gt;
		&lt;/dependencies&gt;
	&lt;/dependencyManagement&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
				&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

&lt;/project&gt;

 &lt;/textarea&gt;
 &lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;b&gt;Step 2.2:&lt;/b&gt; We create a REST controller named `&lt;b&gt;RAGController.java&lt;/b&gt;`. 
 Here, we will see how to implement the LLM packages and classes, and we will also use `&lt;b&gt;@CrossOrigin&lt;/b&gt;` to facilitate the design of the web UI.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
 
&lt;textarea cols="90" name="converted_text" rows="60"&gt; 
package a143mk.AI.aiChatclient;
import a143mk.AI.Modal.QueryRequest;
import jakarta.annotation.PostConstruct;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*")
public class RAGController {

    private final ChatClient chatClient;
    private final EmbeddingModel embeddingModel;
    private final Map&lt;String, String&gt; responseCache = new ConcurrentHashMap&lt;&gt;();
    private VectorStore vectorStore;

    @Value("${file.path:classpath:data/data.text}")
    private Resource fileResource;

    private String template;

    public RAGController(ChatClient.Builder chatClientBuilder, EmbeddingModel embeddingModel) {
        this.chatClient = chatClientBuilder.build();
        this.embeddingModel = embeddingModel;
    }

    @PostConstruct
    public void init() {
        this.vectorStore = SimpleVectorStore.builder(this.embeddingModel).build();

        Resource resource = (fileResource != null &amp;&amp; fileResource.exists())
                ? fileResource
                : new ClassPathResource("data/data.text");

        if (resource.exists()) {
            try {
                TextReader textReader = new TextReader(resource);
                TokenTextSplitter tokenTextSplitter = new TokenTextSplitter();
                List&lt;Document&gt; documents = tokenTextSplitter.apply(textReader.get());
                if (documents != null &amp;&amp; !documents.isEmpty()) {
                    this.vectorStore.accept(documents);
                }
            } catch (Exception e) {
                throw new IllegalStateException("Failed to load the RAG knowledge base from data.text", e);
            }
        }

        this.template = "You are an internal local AI assistant. Use the provided context to answer the user's question. " +
                "If the answer is not in the context, say that the information is not available in the local knowledge base.\n\n" +
                "Context:\n{document}";
    }

    @PostMapping(value = "/rag", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
    public String rag(@RequestBody QueryRequest queryRequest) {
        String question = queryRequest == null ? null : (queryRequest.getQuestion() != null ? queryRequest.getQuestion() : queryRequest.getQuery());

        if (question == null || question.isBlank()) {
            throw new IllegalArgumentException("Request must contain a non-empty 'question' or 'query'.");
        }

        String cacheKey = question.trim().toLowerCase();
        String cachedResponse = responseCache.get(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }

        String retrievedDoc = readRelevantContext(question);

        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(template);
        Message systemMessage = systemPromptTemplate.createMessage(Map.of("document", retrievedDoc));

        Message userMessage = new UserMessage(question);
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));

        String response = chatClient.prompt(prompt)
                .call()
                .content();

        responseCache.put(cacheKey, response);
        return response;
    }

    private String readRelevantContext(String question) {
        if (vectorStore == null) {
            return readRawKnowledgeBase();
        }

        try {
            List&lt;Document&gt; similarDocuments = vectorStore.similaritySearch(
                    SearchRequest.builder().query(question).topK(3).build());

            if (similarDocuments == null || similarDocuments.isEmpty()) {
                return readRawKnowledgeBase();
            }

            String retrievedDoc = similarDocuments.stream()
                    .map(Document::getText)
                    .filter(text -&gt; text != null &amp;&amp; !text.isBlank())
                    .collect(Collectors.joining("\n\n"));

            return retrievedDoc.isBlank() ? readRawKnowledgeBase() : retrievedDoc;
        } catch (Exception e) {
            return readRawKnowledgeBase();
        }
    }

    private String readRawKnowledgeBase() {
        try {
            Resource resource = (fileResource != null &amp;&amp; fileResource.exists()) ? fileResource : new ClassPathResource("data/data.text");
            if (!resource.exists()) {
                return "No local context file was found.";
            }

            return new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            return "The local knowledge base could not be loaded.";
        }
    }
}
 &lt;/textarea&gt;
&lt;br /&gt;&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Step 2.3: &lt;/b&gt;We will configure the LLM model settings within the `&lt;b&gt;application.properties&lt;/b&gt;` file.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;

 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div style="background-color: #121314; color: #bbbebf; font-family: Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 14px; line-height: 19px; white-space: pre;"&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.application.name&lt;/span&gt;=aiChatclient&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;server.port&lt;/span&gt;=8082&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;span style="color: #8b949e;"&gt;# Use the local Ollama instance for both the LLM and embeddings.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.ai.ollama.base-url&lt;/span&gt;=http://localhost:11434&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.ai.ollama.chat.options.model&lt;/span&gt;=codellama:latest&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.ai.ollama.chat.options.num-predict&lt;/span&gt;=256&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.ai.ollama.chat.options.temperature&lt;/span&gt;=0.2&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.ai.ollama.embedding.options.model&lt;/span&gt;=mxbai-embed-large:latest&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;spring.ai.ollama.embedding.enabled&lt;/span&gt;=true&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;span style="color: #8b949e;"&gt;# Local knowledge base file used by the RAG controller.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="color: #ff7b72;"&gt;file.path&lt;/span&gt;=classpath:data/data.text&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;b&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;
Step 2.4: &lt;/b&gt;We implement RAG by taking raw documents (PDF, TXT, HTML) processed into `&lt;b&gt;data.text&lt;/b&gt;` format and breaking them down into smaller text chunks.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;Details:&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;Name: Manoj kumar Vishwakarms&amp;nbsp; &amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;address: 123 Main Street, City, Country&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;phone: +910000000000&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;email: manoj@example.com&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;job: Software Engineer&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;skills: Java, Spring Boot, SQL, JavaScript&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;//Something else can also be written in this RAG data file.&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;b&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;

Step 3: &lt;/b&gt;Finally, we create the web page (`&lt;b&gt;indexAIRAGCHAT.html&lt;/b&gt;`) and integrate the REST controller with the web UI.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;



 &lt;textarea cols="90" name="converted_text" rows="50"&gt; 
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;

    &lt;title&gt;AI Chat Bot&lt;/title&gt;

    &lt;!-- jQuery --&gt;
    &lt;script src="https://code.jquery.com/jquery-3.7.1.min.js"&gt;&lt;/script&gt;

    &lt;style&gt;
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            background: #f5f5f5;
        }

        .chat-container {
            max-width: 700px;
            margin: auto;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        #chatInput {
            width: 70%;
            padding: 10px;
            font-size: 16px;
        }
		 #chatInputRAG {
            width: 70%;
            padding: 10px;
            font-size: 16px;
        }


        #sendBtn {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
		
		 #sendStrimRAG {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
		
		
		 #sendStrim {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }

      /*  #response-display {
            margin-top: 20px;
            padding: 15px;
            background: #eee;
            min-height: 100px;
            white-space: pre-wrap;
            border-radius: 5px;
        }*/
		
		/* Your original container */
#response-display {
    margin-top: 20px;
    padding: 15px;
    background: #eee;
    min-height: 100px;
    white-space: pre-wrap;
    border-radius: 5px;
    font-family: sans-serif; /* Clean font for regular text */
	
	
	max-height: 300px;         /* Adjust maximum height as needed */
    overflow-y: auto;          /* Show vertical scrollbar only when content overflows */
    overflow-x: auto;          /* Add horizontal scrolling if JSON/lines are long */
    word-break: break-word;    /* Prevent text/strings from breaking layout */
    
    /* Optional visual styles for better readability */
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
	
}

/* New styles for the code block container */
#response-display pre {
    background: #272822;       /* Dark background for code contrast */
    color: #f8f8f2;            /* Light text color */
    padding: 12px;
    margin: 10px 0;
    border-radius: 4px;
    overflow-x: auto;          /* Adds horizontal scrollbar if code is too long */
}

/* New styles for the actual code text */
#response-display pre code {
    font-family: 'Courier New', Courier, monospace; /* Monospace font */
    font-size: 14px;
    white-space: pre;          /* Keeps code indentation exactly as written */
}


        .error {
            color: red;
        }
    &lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div class="chat-container"&gt;

    &lt;h2&gt;AI Chatbot&lt;/h2&gt;

    &lt;input   type="text"      id="chatInput"      value="hi"      placeholder="Enter your message"   &gt;
	    &lt;button id="sendBtn"&gt;Send Message ?&lt;/button&gt;
  &lt;!--  &lt;button id="sendStrim"&gt;Send Strim Message&lt;/button&gt;--&gt;
	 
	 &lt;br/&gt;
	 &lt;h2&gt;AI RAG Chatbot&lt;/h2&gt;
     &lt;input   type="text"      id="chatInputRAG"      value="My name is "      placeholder="Enter your RAG Question?"   &gt;
	
    &lt;button id="sendStrimRAG"&gt;Send RAG ?&lt;/button&gt;
  
  
  
  &lt;!--  &lt;button id="sendStrim"&gt;Send Strim Message&lt;/button&gt;--&gt;
    &lt;h3&gt;AI ChatBot &amp; RAG Response:&lt;/h3&gt;

    &lt;pre id="response-display"&gt;Waiting...&lt;/pre&gt;
&lt;!--&lt;em id="chat-container"&gt;Power by &lt;a href="https://a143mk.blogspot.com/"&gt;a143mk&lt;/a&gt;&lt;/em&gt;--&gt;
&lt;/div&gt;

&lt;script&gt;

    // Check jQuery
    console.log("jQuery version:", $.fn.jquery);


    $('#sendBtn').on('click', function () {

        // Get value from input
        var userInput = $('#chatInput').val().trim();

        // Validate input
        if (!userInput) {
            $('#response-display').text("Please enter a message.");
            return;
        }

        // API URL
        var targetUrl =
            "http://localhost:8082/chat/Message?q="+ encodeURIComponent(userInput);

        console.log("Calling API:", targetUrl);

        // Show loading
        $('#response-display').text("Sending To LLM ...");

        // POST request
        $.post(targetUrl).done(function (entityResponse) {

               // console.log("API Response:", entityResponse);

               // $('#response-display').text(JSON.stringify(entityResponse, null, 2));
			    $('#response-display').text(entityResponse);

            })

            .fail(function (xhr, status, error) {

                console.error("Request failed:", status, error);
                console.error("HTTP Status:", xhr.status);
                console.error("Response:", xhr.responseText);

                $('#response-display')
                    .addClass("error")
                    .text(
                        "Request failed" +
                        "HTTP Status: " + xhr.status + "\n" +
                        "Error: " + error
                    );
            });
    });
	 // Allow Enter key to send
    $('#chatInput').on('keypress', function (event) {

        if (event.which === 13) {
            $('#sendBtn').click();
        }

    });
	
	
	
	
    $('#sendStrim').on('click', function () {

        // Get value from input
        var userInput = $('#chatInput').val().trim();

        // Validate input
        if (!userInput) {
            $('#response-display')
                .text("Please enter a message.");
            return;
        }

        // API URL
        var targetUrl =
            "http://localhost:8082/chat/Message/stream?q="
            + encodeURIComponent(userInput);

       // console.log("Calling API:", targetUrl);

        // Show loading
        $('#response-display').text("Sending...");

        // POST request
        $.post(targetUrl).done(function (entityResponse) {

               // console.log("API Response:", entityResponse);

                $('#response-display').text(
                    JSON.stringify(entityResponse, null, 2)
                );

            })

            .fail(function (xhr, status, error) {

                console.error("Request failed:", status, error);
                console.error("HTTP Status:", xhr.status);
                console.error("Response:", xhr.responseText);

                $('#response-display')
                    .addClass("error")
                    .text(
                        "Request failed" +
                        "HTTP Status: " + xhr.status + "\n" +
                        "Error: " + error
                    );
            });
    });


    // Allow Enter key to send
    $('#chatInput').on('keypress', function (event) {

        if (event.which === 13) {
            $('#sendStrim').click();
        }

    });	
	/*RAg Coltrolling*/
$('#sendStrimRAG').on('click', function () {

    // Get value from input
    var userInputRGA = $('#chatInputRAG').val().trim();
    // Validate input
    if (!userInputRGA) {
        $('#response-display').text("Please enter RAG a message.");
        return;
    }
    // API URL (removed query string)
    var targetUrl = "http://localhost:8082/rag";
	    // Show loading
    $('#response-display').text("Sending to RAG...");
	
	var settings = {
  "url": targetUrl,
  "method": "POST",
  "timeout": 0,
  "headers": {
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({
    "question": userInputRGA
  }),
};

$.ajax(settings)
  .done(function (response) {
   // console.log("Success:", response);
	  $('#response-display').text(response);
  })
  .fail(function (xhr, status, error) {
    console.error("Request Failed!");
    console.error("HTTP Status Code:", xhr.status);
    console.error("Status Text:", status);
    console.error("Error Description:", error);
    console.error("Server Response:", xhr.responseText);
  });

});	
	

&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;

&lt;/textarea&gt;
&lt;/div&gt;
  Output:
  &lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitXwPnK44jIsugar3BiUrBDcbYczZ5ecf6xRZYzf19Nkd9qr6S3RRQqTddGvthlZ2pJA_bXgDcMVvu2dSQluWVNMH67jmyOIyDKgrUlBKyoUKnrUeSe1GxoDwEs5-rajF5ficAJ_VueJvg0tP_l9JA8005HHuYORo3IpT2oF08HLbE-b3P6Trp-3QoU5Ai/s974/RAG_PNG_2.gif" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="782" data-original-width="974" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitXwPnK44jIsugar3BiUrBDcbYczZ5ecf6xRZYzf19Nkd9qr6S3RRQqTddGvthlZ2pJA_bXgDcMVvu2dSQluWVNMH67jmyOIyDKgrUlBKyoUKnrUeSe1GxoDwEs5-rajF5ficAJ_VueJvg0tP_l9JA8005HHuYORo3IpT2oF08HLbE-b3P6Trp-3QoU5Ai/s1600/RAG_PNG_2.gif" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2026/09/how-to-create-ai-and-rag-chatbot-using.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitXwPnK44jIsugar3BiUrBDcbYczZ5ecf6xRZYzf19Nkd9qr6S3RRQqTddGvthlZ2pJA_bXgDcMVvu2dSQluWVNMH67jmyOIyDKgrUlBKyoUKnrUeSe1GxoDwEs5-rajF5ficAJ_VueJvg0tP_l9JA8005HHuYORo3IpT2oF08HLbE-b3P6Trp-3QoU5Ai/s72-c/RAG_PNG_2.gif" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5778148986524882692</guid><pubDate>Fri, 18 Sep 2026 05:42:07 +0000</pubDate><atom:updated>2026-09-18T07:51:13.093-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">AI-CHATBOT</category><category domain="http://www.blogger.com/atom/ns#">Spring Boot</category><category domain="http://www.blogger.com/atom/ns#">SpringAI</category><title>How to create an AI chatbot using Spring AI and a Web HTML page.</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;S&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;pring AI is an open-source application framework designed to easily integrate Artificial Intelligence (AI) features into Spring Boot applications. It functions as a standard middleware layer; rather than training or building AI models from scratch, it enables developers to seamlessly connect their enterprise code with existing AI models.
Below, we outline the step-by-step process for configuring and developing a chatbot. &lt;br /&gt;
First, you need to select an LLM (Large Language Model) that Spring AI will use to communicate&lt;b&gt;:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Step 1:&lt;/b&gt;We will use the standalone Ollama LLM model. To do this, install Ollama on your system (download via &lt;a href="https://ollama.com/download/windows"&gt;https://ollama.com/download/windows&lt;/a&gt;) 
and then download a free model from &lt;a href="https://ollama.com/search"&gt;https://ollama.com/search&lt;/a&gt;.
&lt;br /&gt;&lt;b&gt;
CMD:&lt;/b&gt;&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;1. widows CMD:&amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; irm https://ollama.com/install.ps1 | iex&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;2. mocOS CMD:&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; curl -fsSL https://ollama.com/install.sh | sh&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;3. Linux CMD:&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;curl -fsSL https://ollama.com/install.sh | sh&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
&lt;br /&gt;
Check Ollama Run using URL: &lt;a href="http://localhost:11434/"&gt;http://localhost:11434/
&lt;/a&gt;&lt;br /&gt;&lt;b&gt;
Step 2:
&lt;/b&gt;&lt;br /&gt;In this step, we configure the Spring Boot AI application using Spring Initializr (&lt;a href="https://start.spring.io/"&gt;https://start.spring.io/&lt;/a&gt;); we have previously covered how to perform this configuration.
Here, we will explain the coding process step-by-step.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Step 2.1:&lt;/b&gt; Check the dependencies in the `pom.xml` file and ensure they match your project setup.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="30"&gt; 
 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;parent&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
		&lt;version&gt;4.1.1&lt;/version&gt;
		&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
	&lt;/parent&gt;
	&lt;groupId&gt;a143mk.AI&lt;/groupId&gt;
	&lt;artifactId&gt;aiChatclient&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;name/&gt;
	&lt;description/&gt;
	&lt;url/&gt;
	&lt;licenses&gt;
		&lt;license/&gt;
	&lt;/licenses&gt;
	&lt;developers&gt;
		&lt;developer/&gt;
	&lt;/developers&gt;
	&lt;scm&gt;
		&lt;connection/&gt;
		&lt;developerConnection/&gt;
		&lt;tag/&gt;
		&lt;url/&gt;
	&lt;/scm&gt;
	&lt;properties&gt;
		&lt;java.version&gt;17&lt;/java.version&gt;
		&lt;spring-ai.version&gt;2.0.1&lt;/spring-ai.version&gt;
	&lt;/properties&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-webmvc&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
			&lt;artifactId&gt;spring-ai-starter-model-ollama&lt;/artifactId&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-webmvc-test&lt;/artifactId&gt;
			&lt;scope&gt;test&lt;/scope&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
	&lt;dependencyManagement&gt;
		&lt;dependencies&gt;
			&lt;dependency&gt;
				&lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
				&lt;artifactId&gt;spring-ai-bom&lt;/artifactId&gt;
				&lt;version&gt;${spring-ai.version}&lt;/version&gt;
				&lt;type&gt;pom&lt;/type&gt;
				&lt;scope&gt;import&lt;/scope&gt;
			&lt;/dependency&gt;
		&lt;/dependencies&gt;
	&lt;/dependencyManagement&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
				&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

&lt;/project&gt;
	
 &lt;/textarea&gt;
 &lt;br /&gt;&lt;b&gt;
 Step 2.2:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;We create a REST controller named `&lt;b&gt;ChatClientController.java&lt;/b&gt;`. 
 Here, we will see how to implement the LLM packages and classes, and we will also use `@CrossOrigin` to facilitate the design of the web UI.
 
&lt;textarea cols="90" name="converted_text" rows="25"&gt; 
 package a143mk.AI.aiChatclient;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import reactor.core.publisher.Flux;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*")
public class ChatClientControler {
    private final ChatClient chatClient;

    public ChatClientControler(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @PostMapping("/Message")
    public ResponseEntity&lt;String&gt; chat(@RequestParam(value="q") String message) {
        String response = this.chatClient.prompt(message).call().content();
        return ResponseEntity.ok(response);
    }

    @PostMapping(value = "/Message/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux&lt;String&gt; streamChat(@RequestParam(value = "q") String message) {
        return this.chatClient.prompt(message)
                .stream()
                .content();
    }
}
 &lt;/textarea&gt;
&lt;br /&gt;&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Step 2.3: &lt;/b&gt;We will configure the LLM model settings within the `application.properties` file.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;

 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;spring.application.name=aiChatclient&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;server.port=8081&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;spring.ai.ollama.base-url=http://localhost:11434&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;spring.ai.ollama.chat.options.model=codellama:latest&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;spring.ai.ollama.chat.options.num-predict=256&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;spring.ai.ollama.chat.options.temperature=0.2&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border-color: currentcolor; border-image: none; border-style: none; border-width: medium; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;b&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;


Step 3:&lt;/b&gt; Finally, we create the web page (`indexAI_CHAT.html`) and integrate the REST controller with the web UI.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;



 &lt;textarea cols="90" name="converted_text" rows="50"&gt; 
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;

    &lt;title&gt;AI ChatBot&lt;/title&gt;

    &lt;!-- jQuery --&gt;
    &lt;script src="https://code.jquery.com/jquery-3.7.1.min.js"&gt;&lt;/script&gt;

    &lt;style&gt;
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            background: #f5f5f5;
        }

        .chat-container {
            max-width: 700px;
            margin: auto;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        #chatInput {
            width: 70%;
            padding: 10px;
            font-size: 16px;
        }

        #sendBtn {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
		
		 #sendStrim {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }

      /*  #response-display {
            margin-top: 20px;
            padding: 15px;
            background: #eee;
            min-height: 100px;
            white-space: pre-wrap;
            border-radius: 5px;
        }*/
		
		/* Your original container */
#response-display {
    margin-top: 20px;
    padding: 15px;
    background: #eee;
    min-height: 100px;
    white-space: pre-wrap;
    border-radius: 5px;
    font-family: sans-serif; /* Clean font for regular text */
}

/* New styles for the code block container */
#response-display pre {
    background: #272822;       /* Dark background for code contrast */
    color: #f8f8f2;            /* Light text color */
    padding: 12px;
    margin: 10px 0;
    border-radius: 4px;
    overflow-x: auto;          /* Adds horizontal scrollbar if code is too long */
}

/* New styles for the actual code text */
#response-display pre code {
    font-family: 'Courier New', Courier, monospace; /* Monospace font */
    font-size: 14px;
    white-space: pre;          /* Keeps code indentation exactly as written */
}


        .error {
            color: red;
        }
    &lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div class="chat-container"&gt;

    &lt;h2&gt;AI Chatbot&lt;/h2&gt;

    &lt;input
        type="text"
        id="chatInput"
        value="hi"
        placeholder="Enter your message"
    &gt;

    &lt;button id="sendBtn"&gt;Send Message&lt;/button&gt;
    &lt;h3&gt;Response:&lt;/h3&gt;

    &lt;pre id="response-display"&gt;Waiting...&lt;/pre&gt;
&lt;em id="chat-container"&gt;Power by &lt;a href="https://a143mk.blogspot.com/"&gt;a143mk&lt;/a&gt;&lt;/em&gt;
&lt;/div&gt;

&lt;script&gt;

    // Check jQuery
    console.log("jQuery version:", $.fn.jquery);


    $('#sendBtn').on('click', function () {

        // Get value from input
        var userInput = $('#chatInput').val().trim();

        // Validate input
        if (!userInput) {
            $('#response-display').text("Please enter a message.");
            return;
        }

        // API URL
        var targetUrl =
            "http://localhost:8081/chat/Message?q="+ encodeURIComponent(userInput);

        console.log("Calling API:", targetUrl);

        // Show loading
        $('#response-display').text("Sending...");

        // POST request
        $.post(targetUrl).done(function (entityResponse) {

               // console.log("API Response:", entityResponse);

                $('#response-display').text(entityResponse);

            })

            .fail(function (xhr, status, error) {

                console.error("Request failed:", status, error);
                console.error("HTTP Status:", xhr.status);
                console.error("Response:", xhr.responseText);

                $('#response-display')
                    .addClass("error")
                    .text(
                        "Request failed" +
                        "HTTP Status: " + xhr.status + "\n" +
                        "Error: " + error
                    );
            });
    });
	 // Allow Enter key to send
    $('#chatInput').on('keypress', function (event) {

        if (event.which === 13) {
            $('#sendBtn').click();
        }

    });
	

&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;

&lt;/textarea&gt;
&lt;/div&gt;
  
  Output:&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='426' height='266' src='https://www.blogger.com/video.g?token=AD6v5dzWtdV-jN5ygekMP9MVq_abmc3Aw2yHA2Q1Sv6F2_TbfhQ88q_tleJpgcIwo3egQyjiGBYdmM9Ou7Tcq22PDw' class='b-hbp-video b-uploaded' frameborder='0'&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Step-by-step development video:&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;iframe allowfullscreen="" class="BLOG_video_class" height="266" src="https://www.youtube.com/embed/Frn3_cYeKAw" width="408" youtube-src-id="Frn3_cYeKAw"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;</description><link>https://a143mk.blogspot.com/2026/09/how-to-create-ai-chatbot-using-spring.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://img.youtube.com/vi/Frn3_cYeKAw/default.jpg" width="72"/><thr:total>1</thr:total><enclosure length="75752" type="application/vnd.initializr.v2.1+json" url="https://start.spring.io/"/><itunes:explicit>yes</itunes:explicit><itunes:subtitle>Spring AI is an open-source application framework designed to easily integrate Artificial Intelligence (AI) features into Spring Boot applications. It functions as a standard middleware layer; rather than training or building AI models from scratch, it enables developers to seamlessly connect their enterprise code with existing AI models. Below, we outline the step-by-step process for configuring and developing a chatbot. First, you need to select an LLM (Large Language Model) that Spring AI will use to communicate:&amp;nbsp;Step 1:We will use the standalone Ollama LLM model. To do this, install Ollama on your system (download via https://ollama.com/download/windows) and then download a free model from https://ollama.com/search. CMD: 1. widows CMD:&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; irm https://ollama.com/install.ps1 | iex2. mocOS CMD:&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; curl -fsSL https://ollama.com/install.sh | sh3. Linux CMD:&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;curl -fsSL https://ollama.com/install.sh | sh Check Ollama Run using URL: http://localhost:11434/ Step 2: In this step, we configure the Spring Boot AI application using Spring Initializr (https://start.spring.io/); we have previously covered how to perform this configuration. Here, we will explain the coding process step-by-step.&amp;nbsp;Step 2.1: Check the dependencies in the `pom.xml` file and ensure they match your project setup.&amp;nbsp; 4.0.0 org.springframework.boot spring-boot-starter-parent 4.1.1 a143mk.AI aiChatclient 0.0.1-SNAPSHOT 17 2.0.1 org.springframework.boot spring-boot-starter-webmvc org.springframework.ai spring-ai-starter-model-ollama org.springframework.boot spring-boot-starter-webmvc-test test org.springframework.ai spring-ai-bom ${spring-ai.version} pom import org.springframework.boot spring-boot-maven-plugin Step 2.2:&amp;nbsp;We create a REST controller named `ChatClientController.java`. Here, we will see how to implement the LLM packages and classes, and we will also use `@CrossOrigin` to facilitate the design of the web UI. package a143mk.AI.aiChatclient; import org.springframework.ai.chat.client.ChatClient; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import reactor.core.publisher.Flux; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/chat") @CrossOrigin(origins = "*") public class ChatClientControler { private final ChatClient chatClient; public ChatClientControler(ChatClient.Builder chatClientBuilder) { this.chatClient = chatClientBuilder.build(); } @PostMapping("/Message") public ResponseEntity chat(@RequestParam(value="q") String message) { String response = this.chatClient.prompt(message).call().content(); return ResponseEntity.ok(response); } @PostMapping(value = "/Message/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux streamChat(@RequestParam(value = "q") String message) { return this.chatClient.prompt(message) .stream() .content(); } } Step 2.3: We will configure the LLM model settings within the `application.properties` file.&amp;nbsp; spring.application.name=aiChatclientserver.port=8081spring.ai.ollama.base-url=http://localhost:11434spring.ai.ollama.chat.options.model=codellama:latestspring.ai.ollama.chat.options.num-predict=256spring.ai.ollama.chat.options.temperature=0.2 Step 3: Finally, we create the web page (`indexAI_CHAT.html`) and integrate the REST controller with the web UI.&amp;nbsp; AI ChatBot body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; } .chat-container { max-width: 700px; margin: auto; background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } #chatInput { width: 70%; padding: 10px; font-size: 16px; } #sendBtn { padding: 10px 20px; font-size: 16px; cursor: pointer; } #sendStrim { padding: 10px 20px; font-size: 16px; cursor: pointer; } /* #response-display { margin-top: 20px; padding: 15px; background: #eee; min-height: 100px; white-space: pre-wrap; border-radius: 5px; }*/ /* Your original container */ #response-display { margin-top: 20px; padding: 15px; background: #eee; min-height: 100px; white-space: pre-wrap; border-radius: 5px; font-family: sans-serif; /* Clean font for regular text */ } /* New styles for the code block container */ #response-display pre { background: #272822; /* Dark background for code contrast */ color: #f8f8f2; /* Light text color */ padding: 12px; margin: 10px 0; border-radius: 4px; overflow-x: auto; /* Adds horizontal scrollbar if code is too long */ } /* New styles for the actual code text */ #response-display pre code { font-family: 'Courier New', Courier, monospace; /* Monospace font */ font-size: 14px; white-space: pre; /* Keeps code indentation exactly as written */ } .error { color: red; } AI Chatbot Send Message Response: Waiting... Power by a143mk // Check jQuery console.log("jQuery version:", $.fn.jquery); $('#sendBtn').on('click', function () { // Get value from input var userInput = $('#chatInput').val().trim(); // Validate input if (!userInput) { $('#response-display').text("Please enter a message."); return; } // API URL var targetUrl = "http://localhost:8081/chat/Message?q="+ encodeURIComponent(userInput); console.log("Calling API:", targetUrl); // Show loading $('#response-display').text("Sending..."); // POST request $.post(targetUrl).done(function (entityResponse) { // console.log("API Response:", entityResponse); $('#response-display').text(entityResponse); }) .fail(function (xhr, status, error) { console.error("Request failed:", status, error); console.error("HTTP Status:", xhr.status); console.error("Response:", xhr.responseText); $('#response-display') .addClass("error") .text( "Request failed" + "HTTP Status: " + xhr.status + "\n" + "Error: " + error ); }); }); // Allow Enter key to send $('#chatInput').on('keypress', function (event) { if (event.which === 13) { $('#sendBtn').click(); } }); Output: Step-by-step development video:</itunes:subtitle><itunes:author>noreply@blogger.com (A143MK PROGRAMMING)</itunes:author><itunes:summary>Spring AI is an open-source application framework designed to easily integrate Artificial Intelligence (AI) features into Spring Boot applications. It functions as a standard middleware layer; rather than training or building AI models from scratch, it enables developers to seamlessly connect their enterprise code with existing AI models. Below, we outline the step-by-step process for configuring and developing a chatbot. First, you need to select an LLM (Large Language Model) that Spring AI will use to communicate:&amp;nbsp;Step 1:We will use the standalone Ollama LLM model. To do this, install Ollama on your system (download via https://ollama.com/download/windows) and then download a free model from https://ollama.com/search. CMD: 1. widows CMD:&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; irm https://ollama.com/install.ps1 | iex2. mocOS CMD:&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; curl -fsSL https://ollama.com/install.sh | sh3. Linux CMD:&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;curl -fsSL https://ollama.com/install.sh | sh Check Ollama Run using URL: http://localhost:11434/ Step 2: In this step, we configure the Spring Boot AI application using Spring Initializr (https://start.spring.io/); we have previously covered how to perform this configuration. Here, we will explain the coding process step-by-step.&amp;nbsp;Step 2.1: Check the dependencies in the `pom.xml` file and ensure they match your project setup.&amp;nbsp; 4.0.0 org.springframework.boot spring-boot-starter-parent 4.1.1 a143mk.AI aiChatclient 0.0.1-SNAPSHOT 17 2.0.1 org.springframework.boot spring-boot-starter-webmvc org.springframework.ai spring-ai-starter-model-ollama org.springframework.boot spring-boot-starter-webmvc-test test org.springframework.ai spring-ai-bom ${spring-ai.version} pom import org.springframework.boot spring-boot-maven-plugin Step 2.2:&amp;nbsp;We create a REST controller named `ChatClientController.java`. Here, we will see how to implement the LLM packages and classes, and we will also use `@CrossOrigin` to facilitate the design of the web UI. package a143mk.AI.aiChatclient; import org.springframework.ai.chat.client.ChatClient; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import reactor.core.publisher.Flux; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/chat") @CrossOrigin(origins = "*") public class ChatClientControler { private final ChatClient chatClient; public ChatClientControler(ChatClient.Builder chatClientBuilder) { this.chatClient = chatClientBuilder.build(); } @PostMapping("/Message") public ResponseEntity chat(@RequestParam(value="q") String message) { String response = this.chatClient.prompt(message).call().content(); return ResponseEntity.ok(response); } @PostMapping(value = "/Message/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux streamChat(@RequestParam(value = "q") String message) { return this.chatClient.prompt(message) .stream() .content(); } } Step 2.3: We will configure the LLM model settings within the `application.properties` file.&amp;nbsp; spring.application.name=aiChatclientserver.port=8081spring.ai.ollama.base-url=http://localhost:11434spring.ai.ollama.chat.options.model=codellama:latestspring.ai.ollama.chat.options.num-predict=256spring.ai.ollama.chat.options.temperature=0.2 Step 3: Finally, we create the web page (`indexAI_CHAT.html`) and integrate the REST controller with the web UI.&amp;nbsp; AI ChatBot body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; } .chat-container { max-width: 700px; margin: auto; background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } #chatInput { width: 70%; padding: 10px; font-size: 16px; } #sendBtn { padding: 10px 20px; font-size: 16px; cursor: pointer; } #sendStrim { padding: 10px 20px; font-size: 16px; cursor: pointer; } /* #response-display { margin-top: 20px; padding: 15px; background: #eee; min-height: 100px; white-space: pre-wrap; border-radius: 5px; }*/ /* Your original container */ #response-display { margin-top: 20px; padding: 15px; background: #eee; min-height: 100px; white-space: pre-wrap; border-radius: 5px; font-family: sans-serif; /* Clean font for regular text */ } /* New styles for the code block container */ #response-display pre { background: #272822; /* Dark background for code contrast */ color: #f8f8f2; /* Light text color */ padding: 12px; margin: 10px 0; border-radius: 4px; overflow-x: auto; /* Adds horizontal scrollbar if code is too long */ } /* New styles for the actual code text */ #response-display pre code { font-family: 'Courier New', Courier, monospace; /* Monospace font */ font-size: 14px; white-space: pre; /* Keeps code indentation exactly as written */ } .error { color: red; } AI Chatbot Send Message Response: Waiting... Power by a143mk // Check jQuery console.log("jQuery version:", $.fn.jquery); $('#sendBtn').on('click', function () { // Get value from input var userInput = $('#chatInput').val().trim(); // Validate input if (!userInput) { $('#response-display').text("Please enter a message."); return; } // API URL var targetUrl = "http://localhost:8081/chat/Message?q="+ encodeURIComponent(userInput); console.log("Calling API:", targetUrl); // Show loading $('#response-display').text("Sending..."); // POST request $.post(targetUrl).done(function (entityResponse) { // console.log("API Response:", entityResponse); $('#response-display').text(entityResponse); }) .fail(function (xhr, status, error) { console.error("Request failed:", status, error); console.error("HTTP Status:", xhr.status); console.error("Response:", xhr.responseText); $('#response-display') .addClass("error") .text( "Request failed" + "HTTP Status: " + xhr.status + "\n" + "Error: " + error ); }); }); // Allow Enter key to send $('#chatInput').on('keypress', function (event) { if (event.which === 13) { $('#sendBtn').click(); } }); Output: Step-by-step development video:</itunes:summary><itunes:keywords>AI-CHATBOT, Spring Boot, SpringAI</itunes:keywords></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5504199216819215004</guid><pubDate>Sun, 11 Jan 2026 16:35:00 +0000</pubDate><atom:updated>2026-01-11T12:10:34.039-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">JSON</category><category domain="http://www.blogger.com/atom/ns#">JWT Token</category><category domain="http://www.blogger.com/atom/ns#">OAuth2 Security</category><category domain="http://www.blogger.com/atom/ns#">Rest API</category><title>How to receive a JWT-based access token from the client, verify the token, and push data using the client's URL?</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div style="text-align: left;"&gt;&lt;b&gt;J&lt;/b&gt;WT OAuth2 Integration and JSON Payload Handling in Java: JWT (JSON Web Token) is a token format used in OAuth2.&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;A JWT is:&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;Stateless&lt;/li&gt;&lt;li&gt;Digitally signed&lt;/li&gt;&lt;li&gt;Self-contained&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;Integrating with client APIs using APIs and JSON-based payloads involves an end-to-end process that includes making API calls with JSON payloads and pushing master/other data to REST API endpoints.&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;
 Step 1: Obtain the authentication details/Requirements from the client as shown in the example below.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;

 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;

############_MK_TOKEN_CLIENT_SECRET_####################&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;TOKEN_URL=https://a143mk-uat.client.com/api/v1/client/authentication/generate_token
CLIENT_ID=AA143Mkbolgs&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;CLIENT_SECRET=testa143mk
&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp;####Example of Configure URL #############&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;CUST_URL=https://a143mk-uat.client.com/api/master/push_customer&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;CUST_USER_PASS_AUTH=useradmin:password //if it is required or not 
	
&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;br /&gt;
Step 2: Making an API call with an Json payload and pushing master data to the location.&lt;br /&gt;&lt;ol style="text-align: left;"&gt;
&lt;li&gt;A REST API Controller is responsible for handling HTTP requests (such as GET, POST, PUT, DELETE) 
from clients and routing them to the appropriate service methods.
It acts as the entry point for external clients to interact with the backend application.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Purpose: The main role of the controller is to manage incoming HTTP requests, 
map them to specific methods (often called endpoints), and return appropriate responses to the client.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Responsibilities:
Handle HTTP requests (e.g., GET, POST, PUT, DELETE).
Map the incoming requests to service methods.
Return HTTP responses, often in JSON or Json format.
Perform basic request validation or authentication.
Act as the "interface" between the client and the service layer.
In a Spring Boot application, for example, the controller is typically annotated with 
&lt;b&gt;@RestController&lt;/b&gt; and the request mappings are handled using annotations like 
&lt;b&gt;@GetMapping, @PostMapping,&lt;/b&gt; etc.&amp;nbsp;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Example "ClientApiController.java" of a REST Controller in Spring Boot with handlined Json Payload :&lt;/div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="30"&gt;package a143mk.a143mkCustMasterMaster.SystemClientcontroller;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import a143mk.a143mkCustMasterMaster.FromBean.APIResponseEntityBean;
import a143mk.a143mkCustMasterMaster.SystemClientServices.CustMastSysteCliService;
import org.apache.log4j.PropertyConfigurator;

@RestController
@RequestMapping("/CUST_T_API")
public class ClientApiController {
	private static final Logger logger = LoggerFactory.getLogger(CustomerMasterCoSysteCli.class);
	 @Autowired
	 private CustMastSysteCliService custMasteServ;
	
	 @RequestMapping(method = RequestMethod.POST, value="/cust") 
	 public ResponseEntity&lt;APIResponseEntityBean&gt; getCustMasterSysteCli() {
		 APIResponseEntityBean responseEntityBean = null;
		 Object retunResult=null;
		 try {
		 /*Log4je Config*/
	        ClassLoader loader = Thread.currentThread().getContextClassLoader();
			 URL url = loader.getResource("application.properties");
			 PropertyConfigurator.configure(url);
		     /* End Log4je Config*/
			 logger.info("Push A143mk Customer TO SysteCli  Method is getCustMasterSysteCli()"); 
			 retunResult=custMasteServ.CustMastSystemNameService();
		     responseEntityBean = new APIResponseEntityBean("SUCCESS", "Please check Log file For Success or not!", dtFormater.format(new Date()), retunResult);
		     
		 } catch (Exception e) {
		 // TODO: handle exception
		 responseEntityBean = new APIResponseEntityBean("ERROR", e.getMessage(),dtFormater.format(new Date()), retunResult);
		 logger.error(e.getMessage());
		 //e.printStackTrace();
		 }
		 return new ResponseEntity&lt;APIResponseEntityBean&gt;(responseEntityBean, HttpStatus.OK);

		 }	
}
&lt;/textarea&gt;
&amp;nbsp;&lt;/div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;The Service class is a part of the business logic layer of your application.
 It contains methods that implement the core functionality of the application (e.g., creating, reading, updating, deleting data).
 The service class is called by the controller to perform operations that are not directly related to the web request itself.&amp;nbsp;&lt;/div&gt;
 &lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ol style="text-align: left;"&gt;
 &lt;li&gt;Purpose: The service layer acts as a mediator between the controller and the data layer (such as a repository or database). 
 It focuses on business logic and operations.&amp;nbsp;&lt;/li&gt;
 &lt;li&gt;Responsibilities: Perform the core business logic of the application.
Interact with the database (via repositories or DAOs).
Provide methods for the controller to use (i.e., encapsulate business operations).
Handle any necessary validation or transformation before sending data back to the controller.
In a Spring Boot application, service classes are typically annotated with 
&lt;b&gt;@Service, &lt;/b&gt;and they are injected into the controller using &lt;b&gt;@Autowired&lt;/b&gt; (or constructor injection).&amp;nbsp;&lt;/li&gt;&lt;/ol&gt;
&lt;/div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Example "CustMastSystemNameService.java" of a Service Class in Spring Boot:&amp;nbsp;&lt;/div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;Method Internal Working  -&amp;gt;geta143mkCustMasterFOrSYS()
-&amp;gt;pusha143mkCustToSystemNameSystem().&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="50"&gt;package a143mk.a143mkCustMaster.SYSServices;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import a143mk.a143mkCustMaster.Entity.a143mkCustAddressMaster;
import a143mk.a143mkCustMaster.Entity.a143mkCustMaster;
import a143mk.a143mkCustMaster.Repository.a143mkCustAddressMasterRepository;
import a143mk.a143mkCustMaster.Repository.a143mkCustMasterRepository;
import a143mk.a143mkCustMaster.SYSConfig.SSLStopGetToken;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@SuppressWarnings("serial")
@Service
public class CustMastSystemNameService implements Serializable {
	private static final Logger logger = LoggerFactory.getLogger(CustMastSystemNameService.class);
	@Autowired
	private a143mkCustMasterRepository customerMastRepositM1Table;
	@Autowired
	private a143mkCustAddressMasterRepository custAdderssMastRepoM2Table;
	
	public List&lt;Map&lt;String, Object&gt;&gt; geta143mkCustMasterFOrSYS() {
	    List&lt;Map&lt;String, Object&gt;&gt; pusha143mkCustSystemNameList = new ArrayList&lt;&gt;();
	    try {
	        logger.info("Start a143mkCust_push");
	        List&lt;a143mkCustMaster&gt; getMasterV = customerMastRepositM1Table.mdmCustDetailsSystemName();        
	        if (getMasterV != null) {
	            for (a143mkCustMaster getCust : getMasterV) {
	                // Use a Map instead of JSONObject
	                Map&lt;String, Object&gt; customerMap = new HashMap&lt;&gt;();
	                customerMap.put("name", getCust.geta143mkCustName());
	                customerMap.put("type", "Business");
	                customerMap.put("sub_type", "a143mkCust");
	                customerMap.put("phone", Optional.ofNullable(getCust.getPhoneNo()).map(String::trim).filter(p-&gt;p.length()&gt;10).orElse("no"));
	                customerMap.put("email", Optional.ofNullable(getCust.getEmailId()).orElse("no"));
	                customerMap.put("code", Optional.ofNullable(getCust.getWhDepotStoreNo()).map(String::trim).filter(p-&gt;p.length()&gt;5).orElse("no"));
	                customerMap.put("user_id", "AA143Mkbolgs"); //Pass the client_id value or pass the value according to your client.
	                pusha143mkCustSystemNameList.add(customerMap);
	                // Address logic
	                List&lt;a143mkCustAddressMaster&gt; cutoAddressSystemName = 
	                        custAdderssMastRepoM2Table.geta143mkCustAddressTableList(getCust.getLegacyCustNo());
	                
	                List&lt;Map&lt;String, Object&gt;&gt; pushAddressList = new ArrayList&lt;&gt;();
	                if (cutoAddressSystemName != null) {
	                    for (a143mkCustAddressMaster custAdde : cutoAddressSystemName) {
	                        Map&lt;String, Object&gt; address = new HashMap&lt;&gt;();
	                        address.put("address_1", custAdde.getAddress1());
				            address.put("address_2", Optional.ofNullable(custAdde.getAddress2()).orElse(""));
				            address.put("address_3", Optional.ofNullable(custAdde.getAddress3()).orElse(""));
				            address.put("city", Optional.ofNullable(custAdde.getCityName()).orElse("no"));
				            address.put("state", Optional.ofNullable(custAdde.getStateCode()).orElse(""));
				            address.put("pincode", Optional.ofNullable(custAdde.getPincode()).orElse("") );
				            address.put("state_code", custAdde.getStateCode());
				          
	                        pushAddressList.add(address);
	                    }
	                } 
	                // Add the address list to the customer map
	                customerMap.put("address_details", pushAddressList);
	              
	            }
	            ResponseEntity&lt;String&gt;  returnto=pusha143mkCustToSystemNameSystem(pusha143mkCustSystemNameList);
	            if(returnto!=null) {
	            	 logger.info("Success:" +returnto);
	            }else {
	            	logger.error("Error to Push customer to SystemName", returnto);
	            }
	        }
	        
	    } catch (Exception e) {
	        logger.error("Error in geta143mkCustMasterFOrSYS", e);
	    }
	    
	    return pusha143mkCustSystemNameList;
	}
	
	private  ResponseEntity&lt;String&gt;  pusha143mkCustToSystemNameSystem(List&lt;Map&lt;String, Object&gt;&gt; pusha143mkCustSystemNameList) {
	    RestTemplate restTemplate = new RestTemplate();

	    try {
	        // 1. Get token
	        String getTokenTms = new SSLStopGetToken().GetToken();
	        if (getTokenTms == null) {
	            throw new RuntimeException("Failed to get SystemName token");
	        }
             // 2. Set headers
	        HttpHeaders headers = new HttpHeaders();
	        headers.set("Authorization", "Bearer " + getTokenTms);
	   
	        // 3. Build the request entity
	        HttpEntity&lt;List&lt;Map&lt;String, Object&gt;&gt;&gt; request = new HttpEntity&lt;&gt;(pusha143mkCustSystemNameList, headers);

	        // 4. This is the Client Master API URL through which client master data can be sent. This is a test URL; you can modify it according to your client's requirements.
	        String url = "https://a143mk-uat.client.com/api/master/push_customer";
	        ResponseEntity&lt;String&gt; response = restTemplate.postForEntity(url, request, String.class);
	        // 5. Get response body
	       /* responseObject = response.getBody();
	        System.out.println("Response: " + responseObject);
	        logger.info("statuse for  in geta143mkCustMasterFOrSYS: ", responseObject);*/
	        return response;
	    } catch (Exception e) {
	        logger.error("Error pushing customer to SystemName", e);
	        return null;
	    }  
	}
}
 &lt;/textarea&gt;
 &lt;br /&gt;
 
 &lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Step 3: The authorization server issues an access token in JWT format The client sends this token in requests using
Authorization:&lt;b&gt; Bearer&amp;lt;Token&amp;gt;&lt;/b&gt;&lt;token&gt;&lt;br /&gt;
The API validates the JWT by checking its signature, expiration, issuer, and audience 
See the example below for how to obtain an access token for the client: Use this for server-to-server authentication.&lt;/token&gt;&lt;/div&gt;
 &lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;Method Internal Working  -&amp;gt;geta143mkCustMasterFOrSYS()
-&amp;gt;pusha143mkCustToSystemNameSystem().&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;textarea cols="90" name="converted_text" rows="50"&gt;package a143mk.MdmCustomerMaster.SYSConfig;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SSLStopGetToken {
	public String GetToken() {
		try {
            disableSSL(); 
			// Only disable the SSL certificate if it is absolutely necessary 
		   //when using this method; otherwise, do not.
		   
            String apiUrl = "https://a143mk-uat.client.com/api/v1/client/authentication/generate_token";
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            String jsonInput = "{"
                    + "\"client_id\":\"AA143Mkbolgs\","
                    + "\"client_secret\":\"testa143mk\""
                    + "}";
	//The client_id and client_secret values ​​are examples
   // please ask the client for these as they are confidential 
  //information and should be changed.
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonInput.getBytes("UTF-8"));
            }
            BufferedReader br;
            if (conn.getResponseCode() &gt;= 200 &amp;&amp; conn.getResponseCode() &lt; 300) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
			
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(response.toString());
            System.out.println(jsonNode.get("access_token").asText());
            conn.disconnect();
            return jsonNode.get("access_token").asText();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
		}
	    
		// SSL bypass (TESTING ONLY)
	    private static void disableSSL() throws Exception {
	        TrustManager[] trustAll = new TrustManager[]{
	            new X509TrustManager() {
	                public X509Certificate[] getAcceptedIssuers() { return null; }
	                public void checkClientTrusted(X509Certificate[] c, String a) {}
	                public void checkServerTrusted(X509Certificate[] c, String a) {}
	            }
	        };
	        SSLContext sc = SSLContext.getInstance("TLS");
	        sc.init(null, trustAll, new java.security.SecureRandom());
	        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	        HttpsURLConnection.setDefaultHostnameVerifier((h, s) -&gt; true);
	    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
JWT-based access tokens are secure, stateless, and scalable, making them ideal for modern authentication and authorization systems.
&lt;/div&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2026/01/how-to-receive-jwt-based-access-token.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-217004802872567069</guid><pubDate>Sat, 13 Dec 2025 13:58:00 +0000</pubDate><atom:updated>2025-12-13T09:07:40.529-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">Rest API</category><category domain="http://www.blogger.com/atom/ns#">XML payload</category><title>API Integration and XML payload Handling</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;A&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;PI integration and XML payload handling in Java using HttpURLConnection 
and the Apache HttpClient library. To integrate with a client API using an API and XML-based payload, the entire process includes:&lt;br /&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;
ClientURLConfig.properties: Used to store client credential details
Making an API call with an JSON/XML payload and pushing data communication.&lt;/li&gt;&lt;li&gt;Data Communication&amp;nbsp;from the two Client API using the JSON/XML payload API.&lt;/li&gt;&lt;/ol&gt;
 Step 1: ClientURLConfig.properties&lt;br /&gt;

 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp;####Example of Configure URL #############&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;CUST_URL=https://a143mk.com:443/a143mk1_test/MK/api/init_stage_interface/
CUST_USER_PASS_AUTH=useradmin:password
	
&lt;/div&gt;&lt;/div&gt;
  &lt;br /&gt;
Step 2: Making an API call with an XML payload and pushing master data to the location.&lt;br /&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;A REST API Controller is responsible for handling HTTP requests (such as GET, POST, PUT, DELETE) from clients and routing them to the appropriate service methods. It acts as the entry point for external clients to interact with the backend application.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Purpose: The main role of the controller is to manage incoming HTTP requests, map them to specific methods (often called endpoints), and return appropriate responses to the client.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Responsibilities:
Handle HTTP requests (e.g., GET, POST, PUT, DELETE).
Map the incoming requests to service methods.
Return HTTP responses, often in JSON or XML format.
Perform basic request validation or authentication.
Act as the "interface" between the client and the service layer.
In a Spring Boot application, for example, the controller is typically annotated with &lt;b&gt;@RestController&lt;/b&gt; and the request mappings are handled using annotations like &lt;b&gt;@GetMapping, @PostMapping,&lt;/b&gt; etc.&amp;nbsp;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Example of a REST Controller in Spring Boot with handlined XML Payload :&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="30"&gt;@RestController
@RequestMapping("/api/users")
public class UserController {
private static final Logger logger = LogManager.getLogger(UserController.class);
    @Autowired
    private UserService customerServiceImpl;

   // controller class mathod 
  @PostMapping(value = "/pushCustomerToClient")
	    @ResponseBody
	    public ResponseEntity&lt;APIResponseEntityBean&gt; pushCustomerToClient() throws Exception {
	    	synchronized (this) {		
	    		 logger.info(" Running Block !");
	      APIResponseEntityBean responseEntityBean = null;
	      Object retunResult = null;
	      try {
	    	      retunResult = customerServiceImpl.getAllCustomerStores();;
	              responseEntityBean = new APIResponseEntityBean("SUCCESS", "Response Generated Successfully!", dtFormater.format(new Date()), retunResult);
	      } catch (Exception e) {
	           responseEntityBean = new APIResponseEntityBean("ERROR", e.getMessage(), dtFormater.format(new Date()), retunResult);
	           logger.error("Error In Method pushCustomerToClient of MasterAPIController.class :"		+ PrintStackTraceLogger.getStackTrace(e));
	          e.printStackTrace();
	      }
	      return new ResponseEntity&lt;APIResponseEntityBean&gt;(responseEntityBean, HttpStatus.OK);
	    }
	    }
}


&lt;/textarea&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;The Service class is a part of the business logic layer of your application. It contains methods that implement the core functionality of the application (e.g., creating, reading, updating, deleting data). The service class is called by the controller to perform operations that are not directly related to the web request itself.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;Purpose: The service layer acts as a mediator between the controller and the data layer (such as a repository or database). It focuses on business logic and operations.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Responsibilities:
Perform the core business logic of the application.
Interact with the database (via repositories or DAOs).
Provide methods for the controller to use (i.e., encapsulate business operations).
Handle any necessary validation or transformation before sending data back to the controller.
In a Spring Boot application, service classes are typically annotated with &lt;b&gt;@Service, &lt;/b&gt;and they are injected into the controller using &lt;b&gt;@Autowired&lt;/b&gt; (or constructor injection).&amp;nbsp;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Example of a Service Class in Spring Boot:&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;Method Internal Working  -&amp;gt;getAllCustomerStores()-&amp;gt;buildCustomerXmlPayload()-&amp;gt;pushCustomerXmlToa143mkClient().&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="50"&gt; 
@Service
public class UserService {

    @Autowired
    private UserRepository customerRepo;
//Create controller request services and have the controller send back an XML payload
     @Override
	 @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public String getAllCustomerStores() throws Exception {
		List&lt;MastBean&gt; customerList = customerRepo.getCustomerDataFromDB(); //get Date for DataBase
		if(customerList!=null) {
			String xmlPayload = buildCustomerXmlPayload(customerList); //Get Master Details form Database
	        return pushCustomerXmlToa143mkClient(xmlPayload);
		}
	}

public String buildCustomerXmlPayload(List&lt;MastBean&gt; list) throws Exception{
		StringBuilder sb = new StringBuilder();
		sb.append("&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n");
		sb.append("&lt;AmkfData&gt;\n&lt;Header&gt;\n");
		sb.append("&lt;DocumentVersion&gt;1V&lt;/DocumentVersion&gt;\n");
		sb.append("&lt;OriginSystem&gt;APPv3&lt;/OriginSystem&gt;\n");
		sb.append("&lt;ClientEnvCode&gt;a143mk1&lt;/ClientEnvCode&gt;\n");
		sb.append("&lt;ParentCompanyCode&gt;a143mk&lt;/ParentCompanyCode&gt;\n");
		sb.append("&lt;Entity&gt;store&lt;/Entity&gt;\n");
		sb.append("&lt;TimeStamp&gt;").append(java.time.LocalDateTime.now()).append("&lt;/TimeStamp&gt;\n");
		sb.append("&lt;MessageId&gt;").append("str").append(System.currentTimeMillis()).append("&lt;/MessageId&gt;\n");
		sb.append("&lt;/Header&gt;\n&lt;ListOfStores&gt;\n");

		for (MastBean customer : list) {
			sb.append("&lt;store&gt;\n");
			sb.append("&lt;c_code&gt;").append(nonNull(customer.getConceptCode())).append("&lt;/c_code&gt;\n");
			sb.append("&lt;code&gt;").append(nonNull(customer.getCustomerNo()))).append("&lt;/code&gt;\n");
			sb.append("&lt;name&gt;").append(nonNull(customer.getCustomerName())).append("&lt;/name&gt;\n");
			// Customer address
			// Split as per character limits
			String address1 = substringSafe(customer.getAddress(), 0, 60);
			String locality = substringSafe(customer.getLocality(), 60, 190);
			sb.append("&lt;address_1&gt;").append(address1.replace("&amp;",",")).append("&lt;/address_1&gt;\n");
			sb.append("&lt;locality&gt;").append(locality).append("&lt;/locality&gt;\n");
			sb.append("&lt;city&gt;").append(nonNull(customer.getCityName())).append("&lt;/city&gt;\n");
			sb.append("&lt;state&gt;").append(customer.getStateCode()).append("&lt;/state&gt;\n");
			sb.append("&lt;zip&gt;").append(nonNull(customer.getPinCode())).append("&lt;/zip&gt;\n");
			sb.append("&lt;country&gt;INDIA&lt;/country&gt;\n");
			sb.append("&lt;email&gt;").append(nonNull(customer.getEmailId())).append("&lt;/email&gt;\n");
			sb.append("&lt;contact&gt;&lt;/contact&gt;\n");
			sb.append("&lt;action_code&gt;CREATE&lt;/action_code&gt;\n");
			sb.append("&lt;lang&gt;es_IN&lt;/lang&gt;\n");
			sb.append("&lt;default_ship_via_code&gt;&lt;/default_ship_via_code&gt;\n");
			sb.append("&lt;a143mkClient_managed_flg&gt;&lt;/a143mkClient_managed_flg&gt;\n");
			sb.append("&lt;/store&gt;\n");
		}
		sb.append("&lt;/ListOfStores&gt;\n&lt;/AmkfData&gt;");
		System.out.println("Data payload \n" + sb);
		return sb.toString();
	}
	
	// create push "pushCustomerXmlToa143mkClient" Mathod. 
	public String pushCustomerXmlToa143mkClient(String xmlPayload) throws Exception{
		
		 InputStream input; 
    	 String CUST_URL ="";
    	 String CUST_USER_PASS_AUTH ="";
    	 Properties prop = new Properties();
		try {
			
			input = CustomerServiceImpl.class.getClassLoader().getResourceAsStream("a143mkClientURL.properties");
            prop.load(input);
			CUST_URL=prop.getProperty("CUST_URL");
			CUST_USER_PASS_AUTH=prop.getProperty("CUST_USER_PASS_AUTH");  
			String encodedAuth = Base64.getEncoder().encodeToString(CUST_USER_PASS_AUTH.getBytes(StandardCharsets.UTF_8));
			HttpPost post = new HttpPost(CUST_URL);
			post.setHeader("Authorization", "Basic " + encodedAuth);
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");
			List&lt;NameValuePair&gt; params = new ArrayList&lt;&gt;();
			params.add(new BasicNameValuePair("xml_data", xmlPayload));
			try (CloseableHttpClient client = HttpClients.createDefault()) {
				post.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
				try (CloseableHttpResponse response = client.execute(post)) {
					System.out.println("API response: " + response.getStatusLine());
					String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
					System.out.println("Response Body: " + responseBody);
					return responseBody;
				}
			} catch (IOException e) {
				logger.error("IOException of pushCustomerXmlToa143mkClient() "+e.toString());
				throw new RuntimeException("Error while sending XML to a143mkClient", e);
			}

		} catch (Exception e) {
			logger.error("Exception of pushCustomerXmlToa143mkClient() "+e.toString());
			return null;
		}
	}
	}
	
 &lt;/textarea&gt;
 &lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;To test an API endpoint URL like &lt;u&gt;&lt;b&gt;https://a143mk.com/api/puchCustData/pushCustomerToClient&lt;/b&gt;&lt;/u&gt; using Postman, refer to the image. This will allow you to verify the API's functionality and inspect the response.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/a/AVvXsEiqzN49ZLZFQYRkKwpqG1qroc7U8WhHWuXpxodJl2awismdxpAz741r2BEoBSfUo0m0fQwxLS-_4Dmo0Q6ckTNudO6fDHcLYzJfSGHPz7J8Vgrxb2UwtqLc9vqPdpsKnHkTh2gNafOFnk6tugswVfZLYu2h3LnGjotJP29NwVdiv_7sygwtd-jbGDrAL3IA" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img alt="" data-original-height="1020" data-original-width="1920" height="341" src="https://blogger.googleusercontent.com/img/a/AVvXsEiqzN49ZLZFQYRkKwpqG1qroc7U8WhHWuXpxodJl2awismdxpAz741r2BEoBSfUo0m0fQwxLS-_4Dmo0Q6ckTNudO6fDHcLYzJfSGHPz7J8Vgrxb2UwtqLc9vqPdpsKnHkTh2gNafOFnk6tugswVfZLYu2h3LnGjotJP29NwVdiv_7sygwtd-jbGDrAL3IA=w640-h341" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2025/12/api-integration-and-xml-payload-handling.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/a/AVvXsEiqzN49ZLZFQYRkKwpqG1qroc7U8WhHWuXpxodJl2awismdxpAz741r2BEoBSfUo0m0fQwxLS-_4Dmo0Q6ckTNudO6fDHcLYzJfSGHPz7J8Vgrxb2UwtqLc9vqPdpsKnHkTh2gNafOFnk6tugswVfZLYu2h3LnGjotJP29NwVdiv_7sygwtd-jbGDrAL3IA=s72-w640-h341-c" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-6971712323636203681</guid><pubDate>Tue, 25 Nov 2025 16:54:01 +0000</pubDate><atom:updated>2026-01-24T14:17:53.326-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cross-Origin</category><category domain="http://www.blogger.com/atom/ns#">java</category><title>Cross-Origin Resource Sharing</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;C&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;ROSS is a system that allows client web applications (such as JavaScript code) loaded on one domain to interact with resources located on a different domain.
 &lt;br /&gt;
&lt;b&gt;Origin:&lt;/b&gt;
An "Origin" (or source) URL consists of three parts:&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Protocol&lt;/b&gt; (scheme): Such as http or https.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Domain&lt;/b&gt; (host): Such as a143mk.blogspot.com or localhost.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Port&lt;/b&gt; (port number): Such as 8080 or 3000.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;If any of these three parts are different in a request, it is called a Cross-Origin request.
&lt;br /&gt;
Example:&lt;br /&gt;
If your frontend (endpoints.com) sends a request to a backend API (api.com), it is Cross-Origin and will be intercepted by the browser.
CORS is a way to relax this security restriction in a controlled manner, allowing legitimate cross-origin communication.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://localhost:3000") // Example: Allow only this Origin
public class MyController {
// ... methods
}	
 &lt;/textarea&gt;
 &lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
Configuring CORS globally in Spring Boot is the preferred approach, as it saves you from having to apply the &lt;b&gt;@CrossOrigin&lt;/b&gt; annotation to every controller or method and keeps the configuration centralized.
&lt;br /&gt;
Example: This method defines global CORS settings&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;addMapping("/**"):&lt;/b&gt; This indicates that the CORS mapping will apply to all paths.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;allowedOrigins:&lt;/b&gt; Defines the client origins that are allowed to access your API.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;allowedMethods:&lt;/b&gt; The HTTP methods that are allowed.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;allowedHeaders:&lt;/b&gt; Allows all headers sent by the client.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;allowedCredentials:&lt;/b&gt; Set this to 'true' if the client is using cookies or HTTP authentication.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;maxAge:&lt;/b&gt; The time (in seconds) to cache the results of a pre-flight request.
&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;textarea cols="90" name="converted_text" rows="15"&gt; 
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000", "https://your-client-app.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*") 
.allowCredentials(true).maxAge(3600); 
}
} 
&lt;/textarea&gt;
&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2025/11/cross-origin-resource-sharing.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5577487617272711346</guid><pubDate>Sat, 24 May 2025 10:46:00 +0000</pubDate><atom:updated>2025-05-24T20:17:56.044-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">JWT Token</category><title>Implementing JWT Token for secure authentication</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;I&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;mplementing JWT (JSON Web Token) in Java typically involves creating a secure authentication 
mechanism for your web applications. Below is a basic guide to implement JWT using Java, Spring MVC, and jjwt (a popular Java JWT library).&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;WorkFlow:&lt;/b&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjoDFwv7FHBEZXI2hx1yIfbFQMLPkGB615jJqc76PZi1_kmTQei9qq52iBmUZbKHlcQeyX5SmVe89oT_2v2K0LCjBV5SwrotFX-RC6LY-lb4soHRXiq9TD8_mm9C21fHmQ6Z6GLoPI3R6dp_7AwbpPmAWNgeABehw-fqMVpavNF1HmKBULT62dm9sy1_dK/s722/jwtWorkFlow.png" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="496" data-original-width="722" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjoDFwv7FHBEZXI2hx1yIfbFQMLPkGB615jJqc76PZi1_kmTQei9qq52iBmUZbKHlcQeyX5SmVe89oT_2v2K0LCjBV5SwrotFX-RC6LY-lb4soHRXiq9TD8_mm9C21fHmQ6Z6GLoPI3R6dp_7AwbpPmAWNgeABehw-fqMVpavNF1HmKBULT62dm9sy1_dK/s16000/jwtWorkFlow.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
The lifecycle of a JSON Web Token (JWT) typically involves several stages, from creation to expiration and validation. JWTs are widely used for securely transmitting information between parties in the form of a signed and optionally encrypted token. Here’s an overview of the typical lifecycle:

Token Creation&lt;br /&gt;&lt;b&gt;
Authentication:&lt;/b&gt; When a user logs in, they typically provide credentials (e.g., username and password).
&lt;br /&gt;&lt;b&gt;
Server Validation: &lt;/b&gt;The server validates these credentials (e.g., checks the database for the user’s password).
&lt;br /&gt;&lt;b&gt;
JWT Creation:&lt;/b&gt; If the credentials are correct, the server generates a JWT. The token contains:
&lt;br /&gt;&lt;b&gt;
Header:&lt;/b&gt; Describes the signing algorithm (e.g., HS256, RS256) and token type (JWT).
&lt;br /&gt;&lt;b&gt;
Payload:&lt;/b&gt; Contains the claims. Claims are pieces of information (e.g., user ID, expiration time) that are encoded in the token.
&lt;br /&gt;&lt;b&gt;
Signature:&lt;/b&gt; The header and payload are signed with a secret key (HMAC) or a private key (RSA or ECDSA) to ensure integrity.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;

&lt;b&gt;Download Jar file:&amp;nbsp;&lt;a href="https://drive.google.com/file/d/1F5KLm-lBHH8RB5qOWIZYhy02e_d0bj3P/view?usp=sharing"&gt;jjwt-api-0.10.5.jar&lt;/a&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
To create a &lt;b&gt;A143mk.JWTAPIConfig&lt;/b&gt;, we first need to define a package that will be handled in the configuration. 
 &lt;br /&gt;
Create classes name in the &lt;b&gt;A143mk.JWTAPIConfig&lt;/b&gt; package.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;&amp;nbsp;JwtRequestFilter&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;JwtUtil&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;SecurityConfig&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;AuthRequest&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;
1. JwtRequestFilter&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt; 
package a143mk.JWTAPIConfig;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@SuppressWarnings("unused")
@WebFilter(urlPatterns = "/api/*")
public class JwtRequestFilter extends OncePerRequestFilter {

    private JwtUtil jwtUtil = new JwtUtil();

    @Override
    protected void doFilterInternal(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        final String token = request.getHeader("Authorization");

        if (token != null &amp;&amp; token.startsWith("Bearer ")) {
            String username = jwtUtil.extractUsername(token.substring(7));
            if (username != null &amp;&amp; jwtUtil.validateToken(token, username)) {
                // Set user authentication here
            }
        }
        filterChain.doFilter(request, response);
    }
}

 &lt;/textarea&gt;
 &lt;br /&gt;&lt;b&gt;
 2.JwtUtil&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt; 
package a143mk.JWTAPIConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
public class JwtUtil {
    private String secretKey = "a143mkJWT3API"; // use a more secure key in production!
	// private Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    // Generate token
    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // Token expires in 1 hour
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }
    // Extract username from token
    public String extractUsername(String token) {
        return extractClaims(token).getSubject();
    }
    // Extract claims (payload)
    private Claims extractClaims(String token) {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
    }
    // Validate token
    public boolean validateToken(String token, String username) {
        return (username.equals(extractUsername(token)) &amp;&amp; !isTokenExpired(token));
    }
    // Check if token is expired
    private boolean isTokenExpired(String token) {
        return extractClaims(token).getExpiration().before(new Date());
    }
}

 &lt;/textarea&gt;
 &lt;br /&gt;&lt;b&gt;
3. SecurityConfig&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt; 
package a143mk.JWTAPIConfig;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // Disable CSRF
            .authorizeRequests()
            .antMatchers("/api/authenticate").permitAll() // Allow unauthenticated access to login endpoint
            .anyRequest().authenticated() // All other requests require authentication
            .and()
            .addFilterBefore(new JwtRequestFilter(), UsernamePasswordAuthenticationFilter.class); // Add JWT filter
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;&lt;b&gt;
 
4. AuthRequest/PayloderBeanClass&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt; 
package a143mk.JWTAPIConfig;
public class AuthRequest {
	private String username;
    private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
    
    
}

 &lt;/textarea&gt;
 &lt;br /&gt; 
 &lt;b&gt;Create a Controller class&lt;/b&gt;
create a simple controller name is &lt;b&gt;AuthController&lt;/b&gt; an endpoint is accessed.
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
package a143mk.JWTAPIController;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.directwebremoting.export.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import a143mk.JWTAPIConfig.AuthRequest;
import a143mk.JWTAPIConfig.JwtUtil;
import a143mk.service.InterTransferOutWardService;

@RestController
public class AuthController {
	private static final Logger logger = LogManager.getLogger(AuthController.class);
    private JwtUtil jwtUtil = new JwtUtil();
    @Autowired
	InterTransferOutWardService interOutward;
    @PostMapping("/api/authenticate")
     public String createToken(@RequestBody AuthRequest authRequest) {
    	String token=jwtUtil.generateToken(authRequest.getUsername());
    	logger.info("DATE_Time:"+new Data()+" Token Ganrate: "+token );
    	interOutward.tokenSave(token);
    	return jwtUtil.generateToken(authRequest.getUsername());
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
&lt;b&gt;Steps to Test JWT Token in Postman:&lt;/b&gt;&lt;br /&gt;
Obtain the JWT Token:
First, you need to obtain the JWT token from your authentication endpoint. Typically, 
this is done by making a POST request to your login endpoint with the correct user credentials (username, password, etc.).&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Example (login request):&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&amp;nbsp;Method: POST&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;URL: &lt;a href="#" rel="nofollow"&gt;http://localhost:8080/A143mk/api/authenticate&amp;nbsp;&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&amp;nbsp;Body (JSON):
 &lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;{&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; "username": "A143mk@Manoj"&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;}&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
Result :

&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJCQVRBQGRtc0Vjb20iLCJpYXQiOjE3NDc5MDc5MzYsImV4cCI6MTc0NzkxMTUzNn0.1eEK4gwwR3mr2bqcIoYYjxwpcTzUKOCtBMH-GBo6X_4
&lt;/div&gt;&lt;/div&gt;
 




&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2025/05/implementing-jwt-token-for-secure.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjoDFwv7FHBEZXI2hx1yIfbFQMLPkGB615jJqc76PZi1_kmTQei9qq52iBmUZbKHlcQeyX5SmVe89oT_2v2K0LCjBV5SwrotFX-RC6LY-lb4soHRXiq9TD8_mm9C21fHmQ6Z6GLoPI3R6dp_7AwbpPmAWNgeABehw-fqMVpavNF1HmKBULT62dm9sy1_dK/s72-c/jwtWorkFlow.png" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-8415361539469794757</guid><pubDate>Thu, 27 Mar 2025 11:27:00 +0000</pubDate><atom:updated>2025-03-27T12:40:47.786-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">LDAP</category><category domain="http://www.blogger.com/atom/ns#">Spring Boot</category><title>LDAP (Lightweight Directory Access Protocol) authentication in a Spring Boot.</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;L&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;DAP&lt;br /&gt;  
 (Lightweight Directory Access Protocol) authentication in a Spring Boot application typically involves using Spring Security to configure LDAP authentication properly, 
ensuring that sensitive data like passwords is protected and communication with the LDAP server is secure.
&lt;br /&gt;
Here’s a basic guide to securing LDAP authentication in a Spring Boot application:
&lt;br /&gt;
&lt;b&gt;Add Dependencies:&lt;/b&gt;In your pom.xml, add the following dependencies for Spring Security and LDAP:
 &lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt; 
&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-data-ldap&lt;/artifactId&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
 &lt;/textarea&gt;
 &lt;br /&gt;
 &lt;b&gt;LDAP Configuration:&lt;/b&gt; In your application.properties or application.yml, configure the LDAP server details:
 &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
 &lt;div style="text-align: left;"&gt;&lt;span style="font-weight: normal;"&gt;
# application.properties&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;span style="font-weight: normal;"&gt;spring.ldap.urls=ldap://localhost:389&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;span style="font-weight: normal;"&gt;spring.ldap.base=dc=example,dc=com&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;span style="font-weight: normal;"&gt;spring.ldap.username=uid=admin,ou=system&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;span style="font-weight: normal;"&gt;spring.ldap.password=password&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;span style="font-weight: normal;"&gt;spring.ldap.embedded.enabled=false
&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;br /&gt;&lt;b&gt;Spring Security Configuration&lt;/b&gt; :You can configure Spring Security to authenticate using LDAP by defining a SecurityConfig class.&lt;br /&gt;
&lt;b&gt;Here is an example:&lt;/b&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.authentication.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProviderConfigurer;
import org.springframework.security.ldap.core.LdapTemplate;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/login", "/error").permitAll()  // Allowing login and error pages
            .anyRequest().authenticated()  // Other requests require authentication
            .and()
            .formLogin()  // Enable form login
            .loginPage("/login")
            .permitAll()
            .and()
            .logout().permitAll();  // Allow logout
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // LDAP Authentication configuration
        auth
            .ldapAuthentication()
            .userDnPatterns("uid={0},ou=users")
            .groupSearchBase("ou=groups")
            .contextSource()
            .url("ldap://localhost:389/dc=example,dc=com")
            .managerDn("cn=admin,dc=example,dc=com")
            .managerPassword("adminpassword")
            .and()
            .passwordCompare()
            .passwordEncoder(new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder())
            .passwordAttribute("userPassword");
    }
}

 &lt;/textarea&gt;
 &lt;br /&gt;
 &lt;b&gt;Enable Secure LDAP Connections:&lt;/b&gt;
 &lt;br /&gt;
If you are using LDAP over TLS/SSL (LDAPS), it’s critical to ensure that your LDAP communication is secured. Change the URL to:
&lt;br /&gt;
&lt;b&gt;spring.ldap.urls=ldaps://localhost:636&lt;/b&gt;
&lt;br /&gt;
Ensure that your LDAP server supports LDAPS and that proper certificates are installed on the server. 
If you are using SSL, you can also import the certificate into your Java Keystore (JKS).
&lt;br /&gt;    
&lt;b&gt;Secure Password Handling:&lt;/b&gt;In the above configuration, passwords are compared using&lt;b style="font-weight: bold;"&gt; passwordCompare().&lt;/b&gt;
It's recommended to use a hashed password encoder like&lt;b style="font-weight: bold;"&gt; BCryptPasswordEncoder, &lt;/b&gt;which is configured in the example to secure the passwords.
&lt;br /&gt;
&lt;b style="font-weight: bold;"&gt;Customizing the Login Page:&lt;/b&gt;You can customize your login page if needed by creating a controller for the login and error handling views:&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt;@Controller
public class LoginController {
    @RequestMapping("/login")
    public String loginPage() {
        return "login";
    }
    @RequestMapping("/error")
    public String errorPage() {
        return "error";
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b style="font-weight: bold;"&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b style="font-weight: bold;"&gt;Role Mapping (Optional):&lt;/b&gt;If you want to map roles from LDAP groups or other attributes, you can use LdapAuthoritiesPopulator to fetch roles.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;

&lt;textarea cols="90" name="converted_text" rows="5"&gt;For example:
@Bean
public LdapAuthoritiesPopulator authoritiesPopulator(LdapTemplate ldapTemplate) {
    return new DefaultLdapAuthoritiesPopulator(ldapTemplate, "ou=groups");
}
&lt;/textarea&gt;
&lt;br /&gt;
This will ensure the roles are properly populated from LDAP.
&lt;br /&gt;
&lt;b style="font-weight: bold;"&gt;Test the Application:&lt;/b&gt;Start your Spring Boot application, and it should authenticate users against the LDAP server.
 Make sure you test with the proper credentials to confirm everything is working securely.
&lt;br /&gt;
&lt;b style="font-weight: bold;"&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b style="font-weight: bold;"&gt;Summary of Key Points:&lt;/b&gt;
&lt;br /&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;&amp;nbsp;LDAP Configuration: &lt;/b&gt;Use spring.ldap properties to configure the LDAP server details.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;&amp;nbsp;Spring Security: &lt;/b&gt;Configure Spring Security to handle LDAP authentication with ldapAuthentication().&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;&amp;nbsp;SSL/TLS:&lt;/b&gt; Ensure the LDAP communication is encrypted (use ldaps://).&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;&amp;nbsp;Password Encoding: &lt;/b&gt;Use a secure password encoder like BCryptPasswordEncoder.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;&amp;nbsp;Role Mapping: &lt;/b&gt;Map roles from LDAP as needed using LdapAuthoritiesPopulator. This setup will help you integrate LDAP securely in your Spring Boot application.
&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2025/03/ldap-lightweight-directory-access.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-6659335121284791836</guid><pubDate>Fri, 07 Mar 2025 12:07:00 +0000</pubDate><atom:updated>2025-03-07T07:07:15.083-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SSL</category><title>Configuration SSL Certificate in Tomcat server</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;T&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;o, configure SSL in the server.xml file for Apache Tomcat, follow these steps.
 &lt;br /&gt;&lt;b&gt;Steps:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;1. Generate or Obtain an SSL Certificate with Other Files.&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Required Files:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDOcLIA67cXOSHYR9X4C8wBhMSUE7jEV4a0YXySyl-NZVAxJtiP9p3UJknmE7dxgm6hemSB2kDPGMNCyHXB92csr5ic6GXsQR083cGtuFhJJ6_NX6kDJdYK0GqtgJaLCLp3_TwfL4HLggjB0ZOpn02Sexvdo6DCtKkp0wi_2SguhejJzPin7FtYuZaeyqd/s794/Screenshot%202025-03-07%20162244.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="375" data-original-width="794" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDOcLIA67cXOSHYR9X4C8wBhMSUE7jEV4a0YXySyl-NZVAxJtiP9p3UJknmE7dxgm6hemSB2kDPGMNCyHXB92csr5ic6GXsQR083cGtuFhJJ6_NX6kDJdYK0GqtgJaLCLp3_TwfL4HLggjB0ZOpn02Sexvdo6DCtKkp0wi_2SguhejJzPin7FtYuZaeyqd/s16000/Screenshot%202025-03-07%20162244.png" /&gt;&lt;/a&gt;&lt;/div&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;
2. Locate the server.xml file.&lt;/b&gt;&lt;br /&gt;
The server.xml file is typically located in the conf directory inside your Tomcat installation.
&lt;br /&gt;&lt;b&gt;
Path example:/path/to/tomcat/conf/server.xml&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;img /&gt;
 &lt;br /&gt;&lt;b&gt;
3. Edit server.xml&lt;/b&gt;&lt;br /&gt;
Open the server.xml file in a text editor and find the &lt;connector&gt; section for the HTTPS connector. By default, it may be commented out.
You need to configure this section to enable SSL.
Here’s an example of how to configure SSL for Tomcat:
&lt;br /&gt;
 
 &lt;textarea cols="90" name="converted_text" rows="5"&gt; 
 &lt;Connector port="443" protocol="HTTP/1.1" maxThreads="150" scheme="https" 
		   secure="true" SSLEnabled="true" keystoreFile="conf/JKS-keystore.jks" 
		   keystorePass="Password123" clientAuth="false" 
		   SSLProtocol="TLSv1+TLSv1.1+TLSv1.2+Example" keyAlias="4a0ed2df26274Exampl" 
		   ciphers="KeyValue" /&gt;
	
 &lt;/textarea&gt;
 &lt;br /&gt;
 4. Configure Redirect from HTTP to HTTPS (Optional)
To force all HTTP traffic to be redirected to HTTPS, you can add a redirect connector for HTTP (typically port 80). 
For example, below the HTTP connector section in the server.xml file:
&lt;br /&gt;
 
 &lt;textarea cols="90" name="converted_text" rows="5"&gt; 
&lt;Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" /&gt;
	
 &lt;/textarea&gt;
 &lt;br /&gt;
 This will redirect traffic from HTTP (port &lt;b&gt;8080&lt;/b&gt;) to HTTPS (port &lt;b&gt;8443&lt;/b&gt;).
 &lt;br /&gt;&lt;b&gt;
 5.&lt;/b&gt; Restart Tomcat After making these changes, restart your Tomcat server for the changes to take effect.
&lt;b&gt;..../bin/shutdown.sh&lt;/b&gt;&lt;br /&gt;&lt;b&gt;
..../bin/startup.sh
 &lt;/b&gt;&lt;br /&gt;&lt;b&gt;
6. Verify SSL Configuration &lt;/b&gt;&lt;br /&gt;
Open a browser and navigate to &lt;b&gt;https://&lt;/b&gt;&lt;your-domain&gt;&lt;b&gt;:8443. &lt;/b&gt;&lt;br /&gt;
Check for a secure connection (padlock symbol) in the browser's address bar.&lt;/your-domain&gt;&lt;/connector&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;connector&gt;&lt;your-domain&gt;&lt;br /&gt;&lt;b&gt;Additional Notes:&lt;/b&gt;&lt;br /&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;connector&gt;&lt;your-domain&gt;
You can use port &lt;b&gt;443 &lt;/b&gt;(standard HTTPS port) instead of &lt;b&gt;8443&lt;/b&gt;, but you may need root privileges to bind to port &lt;b&gt;443&lt;/b&gt;, or use a reverse proxy to map it.&lt;/your-domain&gt;&lt;/connector&gt;&lt;/li&gt;&lt;li&gt;&lt;connector&gt;&lt;your-domain&gt;If you're running Tomcat behind a reverse proxy (like Apache HTTPD), you may need to adjust the connector settings accordingly.
Let me know if you need further clarification or help!
&lt;/your-domain&gt;&lt;/connector&gt;&lt;/li&gt;&lt;/ul&gt;

&lt;/your-domain&gt;&lt;/connector&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2025/03/configuration-ssl-certificate-in-tomcat.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDOcLIA67cXOSHYR9X4C8wBhMSUE7jEV4a0YXySyl-NZVAxJtiP9p3UJknmE7dxgm6hemSB2kDPGMNCyHXB92csr5ic6GXsQR083cGtuFhJJ6_NX6kDJdYK0GqtgJaLCLp3_TwfL4HLggjB0ZOpn02Sexvdo6DCtKkp0wi_2SguhejJzPin7FtYuZaeyqd/s72-c/Screenshot%202025-03-07%20162244.png" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-1967160556130681675</guid><pubDate>Sat, 04 Jan 2025 09:24:00 +0000</pubDate><atom:updated>2025-01-04T04:24:19.207-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Angular</category><title>Introduction of Angular and AngularJS</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;H&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;ere’s a list of common Angular and AngularJS along with detailed examples to help you prepare.
&lt;br /&gt;
&lt;b&gt;Angular:&lt;/b&gt;
Angular is a platform and framework for building single-page client applications using HTML, CSS, and JavaScript/TypeScript. It is a complete rewrite of AngularJS, developed by Google. Angular uses TypeScript, which is a superset of JavaScript, offering strong typing, interfaces, and decorators.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;Key features of Angular:&lt;/li&gt;&lt;li&gt;
Two-way data binding&lt;/li&gt;&lt;li&gt;
Directives for extending HTML capabilities&lt;/li&gt;&lt;li&gt;
Dependency injection&lt;/li&gt;&lt;li&gt;
Routing and navigation&lt;/li&gt;&lt;li&gt;
Components-based architecture&lt;/li&gt;&lt;/ul&gt;
&lt;b&gt;Difference between AngularJS and Angular:&lt;/b&gt;
&lt;br /&gt;
AngularJS&amp;nbsp; is the original version of Angular, and Angular (2 and above) is a complete rewrite.&lt;br /&gt;
&lt;b&gt;Key differences:&lt;/b&gt;&lt;br /&gt;&lt;b&gt;
Architecture: &lt;/b&gt;Angular uses a component-based architecture, whereas AngularJS uses a directive-based architecture.&lt;br /&gt;&lt;b&gt;
Language: &lt;/b&gt;Angular uses TypeScript, while AngularJS uses JavaScript.&lt;br /&gt;&lt;b&gt;
Performance:&lt;/b&gt; Angular has better performance because of the use of a new change detection mechanism (in Angular 2+).&lt;br /&gt;&lt;b&gt;
Dependency Injection (DI):&lt;/b&gt; Angular's DI is more powerful and more flexible than AngularJS.&lt;br /&gt;
&lt;b&gt;Angular Components:&lt;/b&gt;&lt;br /&gt;
In Angular, a component is a building block of the application. It controls a portion of the user interface (UI), with each component consisting of:&lt;br /&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;
HTML template (view)&lt;/li&gt;&lt;li&gt;
CSS styles (view styles)&lt;/li&gt;&lt;li&gt;
TypeScript class (logic and data)&lt;/li&gt;&lt;/ul&gt;
&lt;b&gt;Example:&lt;/b&gt;
 &lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt; 
import { Component } from '@angular/core';
@Component({
  selector: 'app-hello',
  template: '&lt;h1&gt;{{ message }}&lt;/h1&gt;',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent {
  message = 'Hello, Angular!';
}
 &lt;/textarea&gt;
 &lt;br /&gt;
 In this example, &lt;b&gt;HelloComponent&lt;/b&gt; is an Angular component with a template displaying a message.
 &lt;br /&gt;
 &lt;b&gt;Data binding in Angular? Explain the types of data binding.&lt;/b&gt;
Data binding in Angular is the mechanism to synchronize the data between the component and the view. Angular supports several types of data binding:
&lt;br /&gt;
Interpolation: Binding data from the component to the view.&lt;br /&gt;

 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
 &lt;div style="text-align: left;"&gt;{{ title }}&lt;/div&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;br /&gt;     

Property Binding: Bind an element property to a component property.&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;lt;img [src]="imageUrl" alt="Image"&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;    

Event Binding: Bind an event (e.g., click) to a method in the component.&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;lt;button (click)="onClick()"&amp;gt;Click Me&amp;lt;/button&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;      

Two-Way Data Binding: Combines property and event binding.&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;lt;input [(ngModel)]="username"&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Dependency Injection (DI) in Angular?&lt;/b&gt;&lt;br /&gt;
Dependency Injection (DI) is a design pattern used in Angular to achieve Inversion of Control (IoC). It allows services or objects to be injected into components or other services rather than being created manually inside the component.
&lt;br /&gt;
Example:&lt;br /&gt;

&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class DataService {
  getData() {
    return 'Some data';
  }
}
@Component({
  selector: 'app-data',
  template: '&lt;p&gt;{{ data }}&lt;/p&gt;',
})
export class DataComponent {
  data: string;
  constructor(private dataService: DataService) {
    this.data = this.dataService.getData();
  }
} &lt;/textarea&gt;
 &lt;br /&gt;
In this example, the DataService is injected into DataComponent via DI, and its method getData() is used in the component.
&lt;br /&gt;
&lt;b&gt;Angular Routing:&lt;/b&gt;&lt;br /&gt;
Angular Routing allows you to define routes and navigate between different views or pages in a single-page application (SPA). The routing module helps handle navigation and deep linking.
&lt;br /&gt;&lt;b&gt;Example&lt;/b&gt;: Define routes in app-routing.module.ts:

&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
 &lt;/textarea&gt;
 &lt;br /&gt;
 Use the router-outlet in &lt;b&gt;app.component.html&lt;/b&gt;:
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;lt;router-outlet&amp;gt;&amp;lt;/router-outlet&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt; 
Navigating using the routerLink directive:
&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;lt;a routerLink="/about"&amp;gt;About&amp;lt;/a&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt; Service in Angular:&lt;/b&gt; 
&lt;br /&gt;
A service is a class in Angular used to handle logic that can be shared across multiple components. Services are commonly used for business logic, data fetching, and state management. Services are injected into components or other services using Angular’s Dependency Injection system.
&lt;br /&gt;Example:&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt; 
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class UserService {
  getUser() {
    return { name: 'John', age: 30 };
  }
}
 &lt;/textarea&gt;
&lt;br /&gt;
In the component, the service is injected:
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt; 
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
  selector: 'app-user',
  template: '&lt;p&gt;{{ user.name }}&lt;/p&gt;',
})
export class UserComponent {
  user: any;
  constructor(private userService: UserService) {
    this.user = this.userService.getUser();
  }
}
 &lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;Directives in Angular:&lt;/b&gt;&lt;br /&gt;
Directives are special markers in the DOM that allow Angular to modify the DOM structure. There are three types of directives in Angular:&lt;br /&gt;
&lt;b&gt;Component Directives:&lt;/b&gt; These are the most common type of directives and include templates and logic (e.g., &lt;b&gt;@Component&lt;/b&gt;).&lt;br /&gt;
&lt;b&gt;Structural Directives:&lt;/b&gt; These modify the structure of the DOM (e.g., &lt;b&gt;*ngIf,&lt;/b&gt; &lt;b&gt;*ngFor&lt;/b&gt;).&lt;br /&gt;
&lt;b&gt;Attribute Directives:&lt;/b&gt; These change the appearance or behavior of an element (e.g., &lt;b&gt;ngClass&lt;/b&gt;,&lt;b&gt; ngStyle&lt;/b&gt;).&lt;br /&gt;

&lt;b&gt;Example:&lt;/b&gt;
&lt;b&gt;*ngIf:&lt;/b&gt; Conditionally display an element.
&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
&lt;div ngif="isVisible"&gt;&amp;lt;div *ngIf="isVisible"&amp;gt;This content is visible.&amp;lt;/div&amp;gt;&lt;/div&gt;
&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Observables in Angular:&lt;/b&gt;
&lt;br /&gt;
Observables are a core part of Angular’s reactive programming. They represent a stream of asynchronous events. Angular uses RxJS (Reactive Extensions for JavaScript) for handling asynchronous operations like HTTP requests, user input, or timer events.
&lt;br /&gt;&lt;b&gt;
Example&lt;/b&gt;:&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt; 
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-data',
  template: `&lt;div&gt;{{ data | json }}&lt;/div&gt;`,
})
export class DataComponent implements OnInit {
  data: any;
  constructor(private http: HttpClient) {}
  ngOnInit() {
    this.http.get('https://api.example.com/data').subscribe((response) =&gt; {
      this.data = response;
    });
  }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
 In this example, the HttpClient service returns an Observable, and subscribe() is used to handle the response asynchronously.
 &lt;br /&gt;
 &lt;b&gt;Pipes in Angular:&lt;/b&gt;
 &lt;br /&gt;
 Pipes are used to transform data in the template before it is displayed. Angular provides several built-in pipes like DatePipe, UpperCasePipe, LowerCasePipe, and CurrencyPipe. You can also create custom pipes.
&lt;br /&gt;&lt;b&gt;
Example&lt;/b&gt;:&lt;br /&gt;

&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
&lt;div style="text-align: left;"&gt;{{ birthday | date: 'shortDate' }}&lt;/div&gt;
&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;
In this example, birthday will be transformed into a formatted date using the DatePipe.&lt;br /&gt;
You can also create custom pipes:&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt; 
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
&lt;/textarea&gt;&lt;br /&gt;
In the template:&lt;br /&gt;
&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
&lt;div style="text-align: left;"&gt;{{ 'Angular' | reverse }}&lt;/div&gt; &lt;!--Outputs 'ralugnA'--&gt;
&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;
These are some of the key Angular and AngularJS, along with practical examples.
 Practicing these concepts and writing code will help you to be more prepared for your Development!




&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2025/01/introduction-of-angular-and-angularjs.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5624973310649318969</guid><pubDate>Thu, 19 Dec 2024 05:18:00 +0000</pubDate><atom:updated>2024-12-19T00:18:36.574-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">Predicate In Java 8</category><title>How To Use Predicate In Java 8</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;I&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;n Java 8,&lt;br /&gt;  
  The Predicate is a functional interface that represents a single argument function that returns a boolean value. 
 It is widely used in functional programming, especially when working with streams, as it allows you to define conditions that can be tested.
 
 &lt;br /&gt;
&lt;b&gt;The Predicate Interface:&amp;nbsp;&lt;/b&gt;Let’s look at an example of how to use the &lt;b&gt;@FunctionalInterface&lt;/b&gt; annotation in a Spring Boot application:
&lt;br /&gt;
 
 &lt;textarea cols="90" name="converted_text" rows="14"&gt; 
 @FunctionalInterface
public interface Predicate&lt;T&gt; {
    boolean test(T t); 
    // Other default methods
    default Predicate&lt;T&gt; and(Predicate&lt;? super T&gt; other) {
        return (t) -&gt; test(t) &amp;&amp; other.test(t);
    }
    default Predicate&lt;T&gt; or(Predicate&lt;? super T&gt; other) {
        return (t) -&gt; test(t) || other.test(t);
    }
    default Predicate&lt;T&gt; negate() {
        return (t) -&gt; !test(t);
    }
    static &lt;T&gt; Predicate&lt;T&gt; isEqual(Object targetRef) {
        return (null == targetRef) ? Objects::isNull : targetRef::equals;
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
The Predicate interface contains a method called &lt;b&gt;test(T t)&lt;/b&gt; that evaluates a condition and returns a boolean. 
It also contains some useful default methods like:&lt;br /&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;
and(Predicate other):&lt;/b&gt; Combines two predicates with a logical AND.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;or(Predicate other):&lt;/b&gt; Combines two predicates with a logical OR.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;negate():&lt;/b&gt; Negates the result of the predicate.
&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;Example 1:&lt;/b&gt; Simple Predicate
In the following example, a Predicate is used to test whether a number is greater than 10
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import java.util.function.Predicate;
public class PredicateExample {
    public static void main(String[] args) {
        // Define a Predicate to check if a number is greater than 10
        Predicate&lt;Integer&gt; isGreaterThanTen = (n) -&gt; n &gt; 10;

        // Test the Predicate with different values
        System.out.println(isGreaterThanTen.test(5));   // output false
        System.out.println(isGreaterThanTen.test(15));  // output true
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
&lt;b&gt;Example 2: &lt;/b&gt; Combining Predicates with &lt;span style="color: #2b00fe;"&gt;and()&lt;/span&gt;, &lt;span style="color: #2b00fe;"&gt;or()&lt;/span&gt;, and &lt;span style="color: #2b00fe;"&gt;negate()&lt;/span&gt;
You can combine multiple predicates to create more complex conditions using &lt;span style="color: #2b00fe;"&gt;and()&lt;/span&gt;, &lt;span style="color: #2b00fe;"&gt;or()&lt;/span&gt;, and &lt;span style="color: #2b00fe;"&gt;negate()&lt;/span&gt;.

 &lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import java.util.function.Predicate;
    public class CombinedPredicateExample {
    public static void main(String[] args) {
        // Predicate to check if a number is greater than 10
        Predicate&lt;Integer&gt; isGreaterThanTen = (n) -&gt; n &gt; 10;

        // Predicate to check if a number is Mehuln
        Predicate&lt;Integer&gt; isMehuln = (n) -&gt; n % 2 == 0;

        // Combining predicates using 'and()' (number &gt; 10 and Mehuln)
        Predicate&lt;Integer&gt; isGreaterThanTenAndMehuln = isGreaterThanTen.and(isMehuln);

        // Combining predicates using 'or()' (number &gt; 10 or Mehuln)
        Predicate&lt;Integer&gt; isGreaterThanTenOrMehuln = isGreaterThanTen.or(isMehuln);

        // Negating the 'isGreaterThanTen' predicate
        Predicate&lt;Integer&gt; isNotGreaterThanTen = isGreaterThanTen.negate();

        // Test the combined predicates
        System.out.println(isGreaterThanTenAndMehuln.test(12));  // output true (12 &gt; 10 and 12 is Mehuln)
        System.out.println(isGreaterThanTenOrMehuln.test(8));   //output true (8 is Mehuln)
        System.out.println(isNotGreaterThanTen.test(8));      //output true (8 is not greater than 10)
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
&lt;b&gt;Example 3: &lt;/b&gt; Using Predicate with Collections and Streams
The Predicate interface is often used with the Streams API to filter collections based on certain conditions.
 &lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="15"&gt; import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateWithStreamExample {
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        
        // Predicate to check if a number is Mehuln
        Predicate&lt;Integer&gt; isMehuln = (n) -&gt; n % 2 == 0;
        
        // Using the 'filter' method in Stream with Predicate
        List&lt;Integer&gt; MehulnNumbers = numbers.stream()
                                           .filter(isMehuln) // Applying the Predicate
                                           .collect(Collectors.toList());

        System.out.println(MehulnNumbers);  // Output Prints: [2, 4, 6, 8, 10]
    }
}

 &lt;/textarea&gt;

&lt;br /&gt;
&lt;b&gt;Example 4: &lt;/b&gt; Predicate with &lt;b&gt;&lt;span style="color: #2b00fe;"&gt;isEqual&lt;/span&gt;&lt;/b&gt; Static Method
Java 8 introduces a static method &lt;b&gt;&lt;span style="color: #2b00fe;"&gt;isEqual&lt;/span&gt;&lt;/b&gt; in the Predicate interface, which is used to create a predicate that checks if two objects are equal.
 &lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="5"&gt; import java.util.function.Predicate;
public class PredicateIsEqualExample {
    public static void main(String[] args) {
        Predicate&lt;String&gt; isHello = Predicate.isEqual("Hello");

        System.out.println(isHello.test("Hello")); // Output true
        System.out.println(isHello.test("World")); // Output false
    }
}

 &lt;/textarea&gt;

&lt;br /&gt;
&lt;b&gt;Example 5: &lt;/b&gt; Using Predicate with a List of Objects
You can use predicates to filter lists of custom objects. 
Hare's an example where we filter a list of Person objects based on age.
 &lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="15"&gt;import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class PersonPredicateExample {
    public static void main(String[] args) {
        List&lt;Person&gt; people = Arrays.asList(
            new Person("John", 25),
            new Person("Manoj", 32),
            new Person("Bob", 17),
            new Person("Mehul", 6)
        );

        // Predicate to check if a person is over 18 years old
        Predicate&lt;Person&gt; isAdult = person -&gt; person.age &gt; 18;

        // Using the predicate with streams to filter the list
        List&lt;Person&gt; adults = people.stream()
                                    .filter(isAdult)  // Applying the Predicate
                                    .collect(Collectors.toList());

        System.out.println(adults); // output Prints: [John (25), Manoj (32), Mehul (6)]
    }
}

 &lt;/textarea&gt;
 &lt;br /&gt;
&lt;b&gt;Summary of Predicate Methods:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;test(T t): &lt;/b&gt;Evaluates the predicate on the given argument and returns true or false.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;and(Predicate other):&lt;/b&gt; Combines this predicate with another one using logical AND.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;or(Predicate other): &lt;/b&gt;Combines this predicate with another one using logical OR.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;negate():&lt;/b&gt; Reverses the result of the predicate (logical NOT).&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;isEqual(Object targetRef): &lt;/b&gt;Creates a predicate that checks if an object is equal to the given target.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;&lt;b&gt;* Common Use Cases:&amp;nbsp;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;Filtering collections with Stream.filter().
 Validating input, such as checking if a string matches a pattern or if a number falls within a range.
 Using complex conditional logic in combination with other predicates.&lt;br /&gt;
 Predicates are a powerful tool in functional programming and are heavily used in Java 8's Streams API to make code more readable and expressive.




&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/12/how-to-use-predicate-in-java-8.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5232794228945073080</guid><pubDate>Wed, 11 Dec 2024 12:30:00 +0000</pubDate><atom:updated>2024-12-11T07:30:06.372-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ExceptionHandler</category><category domain="http://www.blogger.com/atom/ns#">Exceptions Handling</category><title>Spring Framework  `@ExceptionHandler`  </title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;

&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;I&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;n Spring Framework, the `@ExceptionHandler` annotation is used to handle exceptions that occur during the execution of a controller method. This allows you to handle specific exceptions in a centralized manner without cluttering your code with `try-catch` blocks. 
 You can define exception handler methods in your controller or in a global exception handler class.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;b&gt;Example of using @ExceptionHandler:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Let’s look at an example of how to use the &lt;b&gt;`@ExceptionHandler`&lt;/b&gt; annotation in a Spring Boot application:
&lt;br /&gt;
 Create a custom exception class First, let's define a custom exception that we will handle in the controller.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
 &lt;br /&gt;
 
 &lt;textarea cols="90" name="converted_text" rows="5"&gt; 
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;
 &lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Create a Controller that throws the exception&lt;/b&gt;
In this step, we’ll create a simple controller that throws a `ResourceNotFoundException` when an endpoint is accessed.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/resource/{id}")
    public String getResourceById(int id) {
        if (id &lt;= 0) {
            throw new ResourceNotFoundException("Resource with ID " + id + " not found!");
        }
        return "Resource found with ID " + id;
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;

&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Handle the exception using `@ExceptionHandler`&amp;nbsp;&lt;/b&gt;
Now, let’s handle the &lt;b&gt;`ResourceNotFoundException` &lt;/b&gt;using the &lt;b&gt;`@ExceptionHandler`&lt;/b&gt; annotation in the same controller.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp; &lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt; 
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity&lt;String&gt; handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ResponseEntity&lt;&gt;(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}
 &lt;/textarea&gt;
 &lt;br /&gt;


&lt;b&gt;&lt;br /&gt; &lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;For Explanation :&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;@RestControllerAdvice&lt;/b&gt;: This is a specialized version of &lt;b&gt;@ControllerAdvice&lt;/b&gt; that is used for global exception handling in &lt;b&gt;@RestController&lt;/b&gt; methods. It allows you to handle exceptions across all controllers.&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;b&gt;@ExceptionHandler(ResourceNotFoundException.class)&lt;/b&gt;: This annotation tells Spring that whenever a `ResourceNotFoundException` is thrown, the `handleResourceNotFoundException` method should handle it.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;b&gt;ResponseEntity&lt;string&gt;&lt;/string&gt;&lt;/b&gt;: The method returns a &lt;b&gt;ResponseEntity&lt;/b&gt; with a custom message and HTTP status code (404 in this case).&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;b&gt;Running the Application&lt;/b&gt;
When you run this Spring Boot application and access the &lt;b&gt;/resource/{id}&lt;/b&gt; endpoint with an invalid ID (e.g., `/resource/0` or `/resource/-1`), 
it will return a response like:

&lt;br /&gt;
HTTP Status: 404 Not Found
Body: Resource with ID 0 not found!
&lt;br /&gt;

&lt;b&gt; Example Output:&lt;/b&gt;&lt;br /&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;
- When accessing &lt;b&gt;`/resource/1`&lt;/b&gt;, it will return &lt;b&gt;"Resource found with ID 1"&lt;/b&gt;.&amp;nbsp;&lt;/li&gt;&lt;li&gt;- When accessing &lt;b&gt;`/resource/0`&lt;/b&gt;, it will return a 404 response with the message &lt;b&gt;"Resource with ID 0 not found!"&lt;/b&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Advantages of using @ExceptionHandler&lt;/b&gt;:
&lt;br /&gt;&amp;nbsp;Centralized exception handling.
- Cleaner code with no need for `try-catch` blocks in each controller method.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;Ability to return custom error responses with HTTP status codes.

You can handle multiple exceptions in a similar way by adding more &lt;b&gt;`@ExceptionHandler`&lt;/b&gt; 
methods in the same class, or even define exception handling globally for all controllers using &lt;b&gt;`@ControllerAdvice`&lt;/b&gt; instead of &lt;b&gt;`@RestControllerAdvice`&lt;/b&gt;.





&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/12/spring-framework-exceptionhandler.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-7110526218684254856</guid><pubDate>Thu, 19 Sep 2024 01:25:00 +0000</pubDate><atom:updated>2024-09-21T08:41:06.731-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Exceptions Handling</category><title>Handling Exceptions in an API when Integrating with an API Gateway.</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;H&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;andling exceptions in an API when integrating with an API Gateway is crucial for maintaining robust, secure, and user-friendly services. The API Gateway often acts as a middleman between your clients and your backend services, so it needs to handle errors effectively to ensure that meaningful and actionable responses are provided to clients.
Here's a structured approach to handling exceptions from your API to the API Gateway:
&lt;br /&gt;
&lt;b&gt;Design Consistent Error Responses:&lt;/b&gt;&lt;br /&gt;
 Ensure that your backend APIs provide consistent and meaningful error responses. This helps the API Gateway understand and relay errors appropriately.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Example Error Response Structure: &lt;/b&gt;&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;json&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;{&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; "error": {&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; "code": "RESOURCE_NOT_FOUND",&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; "message": "The requested resource was not found.",&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; "details": "Resource ID: 12345"&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; }&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;}&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
 &lt;br /&gt;
 &lt;b&gt;Handle Exceptions in Backend Services:&lt;/b&gt;
Implement proper exception handling in your backend services. Catch exceptions and convert them into meaningful error responses.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Java Example: &lt;/b&gt;&lt;br /&gt;

 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import org.springframework.http.HttpStatus;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import org.springframework.http.ResponseEntity;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import org.springframework.web.bind.annotation.ExceptionHandler;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import org.springframework.web.bind.annotation.RestControllerAdvice;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;@RestControllerAdvice&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;public class GlobalExceptionHandler {&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; @ExceptionHandler(ResourceNotFoundException.class)&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleResourceNotFound(ResourceNotFoundException ex) {&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; ErrorResponse errorResponse = new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage());&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return new ResponseEntity&amp;lt;&amp;gt;(errorResponse, HttpStatus.NOT_FOUND);&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; }&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; @ExceptionHandler(Exception.class)&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleGeneralException(Exception ex) {&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; ErrorResponse errorResponse = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred.");&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return new ResponseEntity&amp;lt;&amp;gt;(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; }&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; // Define ErrorResponse class&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; public static class ErrorResponse {&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; private String code;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; private String message;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; // Constructor, getters, and setters&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; }&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;}&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
 &lt;br /&gt;
 &lt;b&gt;Configure API Gateway for Error Handling:&lt;/b&gt;&lt;br /&gt;
API Gateways like AWS API Gateway, Google Cloud Endpoints, or Azure API Management allow you to configure how errors are handled and transformed.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;AWS API Gateway Example:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Create Custom Error Responses:&lt;/b&gt;
Define custom error responses in the API Gateway settings. This includes mapping HTTP status codes from your backend to user-friendly messages or custom error codes.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Set Up Gateway Responses:&lt;/b&gt;
Configure Gateway Responses to handle specific HTTP status codes (e.g., 500 Internal Server Error) and provide custom error messages or redirection.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Use Integration Responses:&lt;/b&gt;
Map backend error responses to different HTTP status codes and customize the response format in the API Gateway
 &lt;br /&gt;
 &lt;b&gt;Logging and Monitoring:&lt;/b&gt;&lt;br /&gt;
Implement logging and monitoring to track and analyze errors. This helps in diagnosing issues and improving your API services.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Example Using AWS CloudWatch:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Enable Logging:&lt;/b&gt; Configure API Gateway to log request and response details.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Set Up Alarms:&lt;/b&gt; Create CloudWatch Alarms for specific error conditions (e.g., high 5xx error rates).
&lt;br /&gt;

&lt;b&gt;Testing and Validation:&lt;/b&gt; Thoroughly test your API error handling to ensure that errors are propagated and transformed correctly through the API Gateway.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Steps:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Unit Tests:&lt;/b&gt; Test backend error responses and exception handling.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Integration Tests:&lt;/b&gt; Test the full flow through the API Gateway to ensure errors are handled correctly and responses are as expected.&lt;br /&gt;

&lt;b&gt;Summary:&lt;/b&gt;
&lt;br /&gt;
&lt;b&gt;Backend Services:&lt;/b&gt; Handle exceptions and return consistent error responses.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;API Gateway Configuration:&lt;/b&gt; Map and customize error responses, configure Gateway Responses, and set up logging.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Logging and Monitoring:&lt;/b&gt; Track errors and performance using tools like AWS CloudWatch.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Testing:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Validate error handling through unit and integration tests.
By following these steps, you ensure that your API Gateway can effectively manage and relay errors, 
providing a better experience for clients and aiding in the maintenance and debugging of your services.
&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/09/handling-exceptions-in-api-when.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5363886093330642066</guid><pubDate>Sun, 08 Sep 2024 14:49:00 +0000</pubDate><atom:updated>2024-09-08T10:49:27.251-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Tomcat configuration</category><title>How to improve the performance of Tomcat service configuration for slow networks.</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;I&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;mproving the performance of Tomcat services over a slow network involves addressing multiple aspects of
 both Tomcat configuration and network conditions. Here are some strategies to consider:
&lt;br /&gt;
&lt;b&gt;Optimize Tomcat Configuration:&lt;/b&gt;&lt;br /&gt;
 &lt;b&gt;Increase Thread Pool Size:&lt;/b&gt; Ensure that your Tomcat’s connector thread pool is appropriately sized. You can adjust the 
`&lt;b&gt;maxThreads&lt;/b&gt;` attribute in your `&lt;b&gt;server.xml&lt;/b&gt;` file to handle more simultaneous requests.&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: left;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe89UhyphenhyphenenjS9A6CY_2ygsFV6sKo13N43I29iEJyDUc47VJjnEM643lDHvigw8HSfyFHfUstbsRDFlNBOy9qPjgi_MFvBX90AxVK0CejJIfIUoDbuupxiNC-u9JEOfF94D5r0iHuu6D-3-wHxgIPdMLjdwQi-F2vB-E3oQObTKH9FM1zak2-dcigE0Csy6p/s904/tom1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="619" data-original-width="904" height="438" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe89UhyphenhyphenenjS9A6CY_2ygsFV6sKo13N43I29iEJyDUc47VJjnEM643lDHvigw8HSfyFHfUstbsRDFlNBOy9qPjgi_MFvBX90AxVK0CejJIfIUoDbuupxiNC-u9JEOfF94D5r0iHuu6D-3-wHxgIPdMLjdwQi-F2vB-E3oQObTKH9FM1zak2-dcigE0Csy6p/w640-h438/tom1.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp;&amp;lt;Connector&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; port="8080"&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; protocol="HTTP/1.1"&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; maxThreads="200"&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; connectionTimeout="20000"&amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; redirectPort="8443"&amp;nbsp; /&amp;gt;&lt;/div&gt;&lt;/div&gt;
 &lt;br /&gt;
 &lt;b&gt;Connection Timeout Settings:&lt;/b&gt;
 Tune the `&lt;b&gt;connectionTimeout&lt;/b&gt;` attribute to be reasonable, considering network conditions. Setting it too high might lead to resource wastage on the server.&lt;br /&gt;&lt;b&gt;Disable Unnecessary Connectors:&amp;nbsp;&lt;/b&gt;&lt;br /&gt;
Disable any unused connectors (e.g., AJP or HTTP/2) if they are not needed to reduce the overhead. 
 &lt;br /&gt;
 &lt;b&gt;Enable Keep-Alive:&lt;/b&gt;
 &lt;br /&gt;Keep-alive allows a single TCP connection to remain open for multiple requests, reducing the overhead of opening new connections 
for each request.
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;lt;Connector&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; port="8080"&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; protocol="HTTP/1.1"&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; connectionTimeout="20000"&amp;nbsp; &amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; redirectPort="8443"&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; keepAliveTimeout="60000"&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; maxKeepAliveRequests="100" /&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
 &lt;b&gt;Optimize Garbage Collection:&lt;/b&gt;&lt;br /&gt;
Configure Java’s garbage collection parameters to reduce the impact of GC pauses. Depending on your workload, 
you might use the G1GC collector or other JVM options suitable for your application.
 &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
-XX:+UseG1GC -XX:MaxGCPauseMillis=200&lt;/div&gt;&lt;/div&gt;

 
 &lt;b&gt;Optimize Application Code:&lt;/b&gt;&lt;br /&gt;
 &lt;b&gt;Reduce Latency:&lt;/b&gt; Ensure that your application code is optimized for performance. Slow database queries, inefficient algorithms, or heavy computation can exacerbate the effects of a slow network.

&lt;b&gt;Asynchronous Processing:&lt;/b&gt; Where possible, use asynchronous processing to free up Tomcat threads for other requests while waiting for I/O operations to complete.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Caching:&lt;/b&gt; Implement caching strategies (e.g., HTTP caching, application-level caching) to minimize the number of times the application needs to generate the same responses or fetch the same data.
&lt;br /&gt;
&lt;b&gt;Improve Network Performance:&lt;/b&gt;
&lt;br /&gt;

&lt;b&gt;Network Bandwidth:&lt;/b&gt; Ensure that your network has adequate bandwidth to handle the traffic. If possible, increase the bandwidth or use a Content Delivery Network (CDN) to reduce the load on your server.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Latency Reduction:&lt;/b&gt; Consider using tools or techniques to reduce latency, such as optimizing DNS resolution, using faster network routes, or deploying edge servers closer to end users.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Compression:&lt;/b&gt; Enable response compression to reduce the amount of data transmitted over the network. &lt;b&gt;You can configure gzip compression in Tomcat:

 &lt;/b&gt;&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;lt;Connector&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;port="8080"&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;protocol="HTTP/1.1"&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;compression="on"&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;compressionMinSize="2048"&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;noCompressionUserAgents="gozilla, traviata"&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; compressableMimeType="text/html,text/xml,text/plain,text/css,text/javascript,application/javascript" /&amp;gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
 &lt;br /&gt;
 
&lt;b&gt;Monitor and Analyze&lt;/b&gt;

&lt;b&gt;Use Monitoring Tools:&lt;/b&gt; Implement monitoring and profiling tools to identify bottlenecks and performance issues. Tools like JVisualVM, JConsole, or commercial APM solutions can provide insights into how your application and Tomcat are performing.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Analyze Logs:&lt;/b&gt; Check Tomcat and application logs for any warnings or errors that could indicate performance issues. Look for patterns or recurring problems that could be addressed.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Regular Maintenance&lt;/b&gt;

&lt;b&gt;Keep Software Updated:&lt;/b&gt; Ensure that Tomcat, Java, and your application dependencies are up to date with the latest performance improvements and security patches.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Review Configuration:&lt;/b&gt; Periodically review and update your Tomcat and application configuration to ensure that they align with current performance and security best practices.

By combining these strategies, you should be able to mitigate the effects of a slow network and improve the performance of Tomcat services.&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/09/how-to-improve-performance-of-tomcat.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe89UhyphenhyphenenjS9A6CY_2ygsFV6sKo13N43I29iEJyDUc47VJjnEM643lDHvigw8HSfyFHfUstbsRDFlNBOy9qPjgi_MFvBX90AxVK0CejJIfIUoDbuupxiNC-u9JEOfF94D5r0iHuu6D-3-wHxgIPdMLjdwQi-F2vB-E3oQObTKH9FM1zak2-dcigE0Csy6p/s72-w640-h438-c/tom1.png" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-6218092729239508415</guid><pubDate>Sat, 24 Aug 2024 15:58:00 +0000</pubDate><atom:updated>2024-08-24T11:58:56.341-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>How to fetch current location at the time of loading a web page using Javascript</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;T&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;o search for a location code (such as a City, state, postal code) using JavaScript, you generally need 
to perform a forward geocoding operation. This involves converting a location name or address into geographic coordinates and then retrieving additional details,
 including the City,
 State and postal code, from those coordinates. You can achieve this using various geocoding APIs.&lt;br /&gt;	
 &lt;textarea cols="90" name="converted_text" rows="50"&gt; 
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Get City, state, postal code&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Welcome to A143mk. &lt;br/&gt;Current Location City, state, postal code&lt;/h1&gt;
    &lt;p id="pinCode"&gt;Fetching...&lt;/p&gt;

    &lt;script&gt;
        function getPinCode(lat, lon) {
            // URL for reverse geocoding
            const url = `https://nominatim.openstreetmap.org/reverse?lat=${lat}&amp;lon=${lon}&amp;format=json&amp;addressdetails=1`;

            fetch(url)
                .then(response =&gt; response.json())
                .then(data =&gt; {
                    if (data &amp;&amp; data.address &amp;&amp; data.address.postcode) {
                        document.getElementById('pinCode').innerText = `HOUSE NO: ${data.address.house_number}, City: ${data.address.city},\n State: ${data.address.state},\n Pin Code: ${data.address.postcode}`;
                    } else {
                        document.getElementById('pinCode').innerText = 'Pin Code not found.';
                    }
						
                })
                .catch(error =&gt; {
                    console.error('Error:', error);
                    document.getElementById('pinCode').innerText = 'Error fetching pin code.';
                });
        }

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(position =&gt; {
                const lat = position.coords.latitude;
                const lon = position.coords.longitude;
                getPinCode(lat, lon);
            }, () =&gt; {
                document.getElementById('pinCode').innerText = 'Geolocation not supported or permission denied.';
            });
        } else {
            document.getElementById('pinCode').innerText = 'Geolocation not supported.';
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;



&lt;/textarea&gt;

 &lt;br /&gt;
&lt;b&gt;output:&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo9RDIhjvZf_xaUFah-jJodMV8IiI1KkRdQm-1uN2s973rMkTRmgzhD3Mui2uTky6He7ORmQZ82UMJAguh-XCodrNdCTDOXYL0FXexqdyEB5mlZR2aytAtTdu7TlDiZzSsEyjTvUFsrTepNOzQqsxKgMQ8biiz4g8pTkEex1Ic7JMrv0rH0aWPHyY15cyh/s760/2222.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="295" data-original-width="760" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo9RDIhjvZf_xaUFah-jJodMV8IiI1KkRdQm-1uN2s973rMkTRmgzhD3Mui2uTky6He7ORmQZ82UMJAguh-XCodrNdCTDOXYL0FXexqdyEB5mlZR2aytAtTdu7TlDiZzSsEyjTvUFsrTepNOzQqsxKgMQ8biiz4g8pTkEex1Ic7JMrv0rH0aWPHyY15cyh/s16000/2222.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/b&gt;


		





&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/08/how-to-fetch-current-location-at-time.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo9RDIhjvZf_xaUFah-jJodMV8IiI1KkRdQm-1uN2s973rMkTRmgzhD3Mui2uTky6He7ORmQZ82UMJAguh-XCodrNdCTDOXYL0FXexqdyEB5mlZR2aytAtTdu7TlDiZzSsEyjTvUFsrTepNOzQqsxKgMQ8biiz4g8pTkEex1Ic7JMrv0rH0aWPHyY15cyh/s72-c/2222.png" width="72"/><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5587373189555357591</guid><pubDate>Sat, 10 Aug 2024 11:12:00 +0000</pubDate><atom:updated>2024-08-10T07:12:58.536-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">design patterns</category><category domain="http://www.blogger.com/atom/ns#">Spring Boot</category><title>How to Implement Design Patterns in Spring Boots Application </title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;I&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;n a Spring Boot web project, design patterns are essential to create a maintainable, scalable, and testable application. 
 Below are some common design patterns and how you can implement them in a Spring Boot project:
&lt;br /&gt;
&lt;b&gt;Singleton Pattern&lt;/b&gt;The Singleton pattern ensures a class has only one instance and provides a global point of access to it. 
In Spring, beans are singleton by default.
&lt;br /&gt;
&lt;b&gt; For Example :&lt;/b&gt; &lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt;@Service
public class MyService {
    // Spring automatically makes this bean a singleton
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;Factory Pattern&lt;/b&gt;&lt;br /&gt;
The Factory pattern is used to create objects without specifying the exact class of object that will be created.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;For Example :&lt;/b&gt; &lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt;@Component
public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        }
        return null;
    }
}
&lt;/textarea&gt;
&lt;b&gt;Usage in a Controller&lt;/b&gt;&lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="15"&gt;@RestController
@RequestMapping("/shapes")
public class ShapeController {

    private final ShapeFactory shapeFactory;

    public ShapeController(ShapeFactory shapeFactory) {
        this.shapeFactory = shapeFactory;
    }

    @GetMapping("/{type}")
    public String getShape(@PathVariable String type) {
        Shape shape = shapeFactory.getShape(type);
        return shape != null ? shape.draw() : "Shape not found";
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;Prototype Pattern&lt;/b&gt;&lt;br /&gt;
The Prototype pattern is used to create a new instance of a class by copying or cloning an existing instance.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt; For Example :&lt;/b&gt; &lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt;@Component
@Scope("prototype")
public class MyPrototypeBean {
    // This bean will be a new instance each time it's requested
}
&lt;/textarea&gt;

&lt;textarea cols="90" name="converted_text" rows="10"&gt;@RestController
public class MyController {

    private final MyPrototypeBean prototypeBean;

    public MyController(MyPrototypeBean prototypeBean) {
        this.prototypeBean = prototypeBean;
    }

    @GetMapping("/prototype")
    public String usePrototype() {
        return prototypeBean.toString();
    }
}
&lt;/textarea&gt;
&lt;br /&gt;


&lt;b&gt;Adapter Pattern&lt;/b&gt;&lt;br /&gt;
The Adapter pattern allows incompatible interfaces to work together. In a Spring Boot project, it can be used to integrate third-party libraries.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt; For Example :&lt;/b&gt;Suppose you have an external logging service that doesn't fit directly into your logging system. &lt;br /&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt;public interface LogAdapter {
    void logMessage(String message);
}

public class ExternalLogServiceAdapter implements LogAdapter {
    private ExternalLogService externalLogService;

    public ExternalLogServiceAdapter(ExternalLogService externalLogService) {
        this.externalLogService = externalLogService;
    }

    @Override
    public void logMessage(String message) {
        externalLogService.log(message);
    }
}
&lt;/textarea&gt;

&lt;b&gt;Usage:&lt;/b&gt;
&lt;textarea cols="90" name="converted_text" rows="10"&gt;@Service
public class MyService {

    private final LogAdapter logAdapter;

    public MyService(LogAdapter logAdapter) {
        this.logAdapter = logAdapter;
    }

    public void performTask() {
        logAdapter.logMessage("Task performed");
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;Decorator Pattern&lt;/b&gt;&lt;br /&gt;
The Decorator pattern is used to add behavior to individual objects without affecting the behavior of other objects from the same class.&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;:&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;textarea cols="90" name="converted_text" rows="15"&gt;public interface Car {
    String assemble();
}

public class BasicCar implements Car {
    @Override
    public String assemble() {
        return "Basic Car.";
    }
}

public class CarDecorator implements Car {
    protected Car car;

    public CarDecorator(Car car) {
        this.car = car;
    }

    @Override
    public String assemble() {
        return this.car.assemble();
    }
}

public class SportsCar extends CarDecorator {
    public SportsCar(Car car) {
        super(car);
    }

    @Override
    public String assemble() {
        return super.assemble() + " Adding features of Sports Car.";
    }
}

&lt;/textarea&gt;

&lt;br /&gt;
&lt;b&gt;Observer Pattern&lt;/b&gt;&lt;br /&gt;
The Observer pattern allows an object to notify other objects when its state changes.&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;:&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;textarea cols="90" name="converted_text" rows="15"&gt;public interface Observer {
    void update(String message);
}

public class EmailNotificationObserver implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Email Notification: " + message);
    }
}

public class EventPublisher {
    private List&lt;Observer&gt; observers = new ArrayList&lt;&gt;();

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}
&lt;/textarea&gt;
&lt;b&gt;Usage in a Service:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt;@Service
public class NotificationService {

    private final EventPublisher eventPublisher;

    public NotificationService(EventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
        eventPublisher.addObserver(new EmailNotificationObserver());
    }

    public void notifyUsers(String message) {
        eventPublisher.notifyObservers(message);
    }
}
&lt;/textarea&gt;


&lt;br /&gt;
&lt;b&gt;Template Method Pattern&lt;/b&gt;&lt;br /&gt;
The Template Method pattern defines the skeleton of an al&amp;nbsp;algorithm in a method, deferring some steps to subclasses.&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;:&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;textarea cols="90" name="converted_text" rows="15"&gt;public abstract class OrderProcessor {

    public final void processOrder() {
        selectItem();
        payment();
        deliver();
    }

    protected abstract void selectItem();

    protected abstract void payment();

    protected void deliver() {
        System.out.println("Order delivered");
    }
}

public class OnlineOrder extends OrderProcessor {
    @Override
    protected void selectItem() {
        System.out.println("Item selected online");
    }

    @Override
    protected void payment() {
        System.out.println("Payment made online");
    }
}
&lt;/textarea&gt;
Usage:&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;textarea cols="90" name="converted_text" rows="5"&gt;@RestController
public class OrderController {

    @GetMapping("/order")
    public String processOrder() {
        OrderProcessor orderProcessor = new OnlineOrder();
        orderProcessor.processOrder();
        return "Order processed";
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;Conclusion:&lt;/b&gt;
Design patterns are critical in developing well-structured, maintainable, and flexible Spring Boot applications. They help in decoupling components, reusing code, and making the application easier to understand and extend. By leveraging these patterns 
in your Spring Boot project, you can achieve better code organization and more effective application design.










&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/08/how-to-implement-design-patterns-in.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-2877948812346607511</guid><pubDate>Mon, 05 Aug 2024 17:21:00 +0000</pubDate><atom:updated>2024-08-05T13:21:50.896-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Spring</category><title>@RestController and @Controller in Spring Framework</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;T&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;he primary difference between &lt;b&gt;@RestController&lt;/b&gt; and &lt;b&gt;@Controller&lt;/b&gt; in the Spring Framework lies in how they handle HTTP 
&lt;br /&gt;
&lt;b&gt;@Controller :&lt;/b&gt;&lt;br /&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;@Controller&lt;/b&gt; is used to define a controller class that can handle HTTP requests and return views.&lt;/li&gt;&lt;li&gt;&amp;nbsp;Typically used in web applications where the responses are HTML pages.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;You need to use &lt;b&gt;@ResponseBody&lt;/b&gt; on methods to indicate that the return value should be written directly to the HTTP response body.
&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
    @GetMapping("/view")

    public String view(Model model) {

        model.addAttribute("message", "Hello, World!");

        return "view"; // This returns the view name to be resolved by a ViewResolver.
    }

    @GetMapping("/api/data")
    @ResponseBody

    public String getData() {

        return "Hello, World!"; // This returns data directly in the response body.
    }
}
&lt;/textarea&gt;&lt;b&gt;@RestController:&lt;/b&gt;
	
	
	
	&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;@RestController&lt;/b&gt; is a specialized version of &lt;b&gt;@Controller&lt;/b&gt; that combines &lt;b&gt;@Controller&lt;/b&gt; and &lt;b&gt;@ResponseBody&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;Designed for RESTful web services where the responses are typically JSON or XML.&amp;nbsp;&lt;/li&gt;&lt;li&gt;All methods in a class annotated with &lt;b&gt;@RestController&lt;/b&gt; implicitly have &lt;b&gt;@ResponseBody&lt;/b&gt; applied, so the return values are written directly to the HTTP response body.
&lt;/li&gt;&lt;/ul&gt;
  &lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyRestController {
    @GetMapping("/data")
    public String getData() {
        return "Hello, World!"; // This returns data directly in the response body.
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Summary&lt;/b&gt;&lt;br /&gt;Use &lt;b&gt;@Controller&lt;/b&gt; when you need to return views (HTML pages).&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Use &lt;b&gt;@RestController&lt;/b&gt; when you need to create RESTful services and return data (like JSON or XML) directly in the response body.
	
&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/08/restcontroller-and-controller-in-spring.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-4827755747400083262</guid><pubDate>Sun, 04 Aug 2024 08:56:00 +0000</pubDate><atom:updated>2024-08-04T04:56:00.985-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">Key Features</category><category domain="http://www.blogger.com/atom/ns#">Lambda Lambda Expressions</category><title>Java 8 Introduced Key Features</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;J&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;ava 8 introduced several key features that significantly enhanced the language and its libraries. Here are the principal features:
&lt;br /&gt;
&lt;b&gt;Lambda Expressions:&lt;/b&gt;&lt;br /&gt;
Allow you to treat functionality as a method argument, or to create small function-like objects more concisely. &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Syntax:&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;(parameters) -&amp;gt; expression or (parameters) -&amp;gt; { statements; }&lt;/div&gt;&lt;/div&gt;
 &lt;b&gt;Functional Interfaces:&lt;/b&gt;&lt;br /&gt;
An interface with just one abstract method, used as the type for lambda expressions and method references. &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Example:&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; java.util.function.Predicate;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; java.util.function.Function;&lt;/div&gt;&lt;/div&gt;
 &lt;b&gt;Stream API:&lt;/b&gt;&lt;br /&gt;
Introduces a new abstraction for working with sequences of elements and performing operations like filter, map, and reduce on them. 
 &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Example:&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; List&lt;string&gt; myList = ...; myList.stream().filter(s -&amp;gt; s.startsWith("a")).forEach(System.out::println);&lt;/string&gt;&lt;/div&gt;&lt;/div&gt;
 &lt;b&gt;Default Methods:&lt;/b&gt;&lt;br /&gt;
Allow you to add new methods to interfaces without breaking the existing implementations.
 &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Example:&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; interface MyInterface {&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;default void newMethod() {&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; ............ // write Method body&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; } }&lt;/div&gt;&lt;/div&gt;

 
 &lt;b&gt;Optional:&lt;/b&gt;&lt;br /&gt;
 A container object which may or may not contain a non-null value, to avoid `NullPointerException`.
 &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Example:&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; Optional&lt;string&gt; opt = Optional.of("value");&amp;nbsp;&lt;/string&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;string&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; opt.ifPresent(System.out::println);&lt;/string&gt;&lt;/div&gt;&lt;/div&gt;
 
  &lt;b&gt;New Date and Time API:&lt;/b&gt;&lt;br /&gt;
 A comprehensive new date and time library under `java.time` package, which is more flexible and easier to use than the old &lt;b&gt;java.util.Date&lt;/b&gt; and &lt;b&gt;java.util.Calendar&lt;/b&gt; classes.
 &lt;br /&gt;
   &lt;b&gt;Nashorn JavaScript Engine:&lt;/b&gt;&lt;br /&gt;
Replaces the old Rhino JavaScript engine, allowing for the embedding of JavaScript code within Java applications.
 &lt;br /&gt;
 
  &lt;b&gt;Method References:&lt;/b&gt;&lt;br /&gt;
 Provide a way to refer to methods without invoking them, which can be used for constructing lambda expressions. 
 &lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Example: ClassName::methodName.
&lt;/div&gt;&lt;/div&gt;
 &lt;br /&gt;
 These features aim to make Java code more expressive, readable, and efficient.&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/08/java-8-introduced-key-features.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-102614768542456131</guid><pubDate>Sun, 04 Aug 2024 08:31:00 +0000</pubDate><atom:updated>2024-08-04T04:31:22.240-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">MAPPING</category><category domain="http://www.blogger.com/atom/ns#">Stream API</category><title>How to Mapping code logic using Stream API</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;S&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;tream API in Java provides a powerful way to work with collections and other data sources. 
Mapping is one of the key operations available in the Stream API, used to transform elements of a stream. Here's a step-by-step guide on how to use the &lt;b&gt;map&lt;/b&gt;
function with the Stream API:
&lt;br /&gt;
&lt;b&gt;Import Required Classes :&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
First, make sure to import the necessary classes:&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import java.util.Arrays;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import java.util.List;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import java.util.stream.Collectors;&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;import java.util.stream.Stream;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;
 
 &lt;b&gt;Create a Stream:&lt;/b&gt;&lt;br /&gt;
 You can create a stream from various sources, like collections, arrays, or generator functions. For example, creating a stream from a list:
 &lt;br /&gt;
  &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
List&lt;string&gt; names = Arrays.asList("a14mk", "manoj", "Jack");&amp;nbsp;&lt;/string&gt;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;&lt;string&gt;Stream&lt;string&gt; nameStream = names.stream();&lt;/string&gt;&lt;/string&gt;&lt;/div&gt;&lt;/div&gt;
&lt;b&gt;Apply the map Function:&lt;/b&gt;
&lt;br /&gt;
Use the &lt;b&gt;map&lt;/b&gt; function to transform each element of the stream. For instance, to convert each name to uppercase:&lt;br /&gt;

&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
Stream&lt;string&gt; upperCaseNames = nameStream.map(String::toUpperCase);
&lt;/string&gt;&lt;/div&gt;&lt;/div&gt;
 &lt;b&gt;Collect the Results:&lt;/b&gt;&lt;br /&gt;
 Finally, you can collect the transformed stream back into a list or another collection:&lt;br /&gt;
 &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
List&lt;string&gt; upperCaseNameList = upperCaseNames.collect(Collectors.toList());&lt;/string&gt;&lt;/div&gt;&lt;/div&gt;
&lt;b&gt;Complete Example:&lt;/b&gt;&lt;br /&gt;
Here’s a complete example demonstrating how to use the &lt;b&gt;map&lt;/b&gt; function with the Stream API:
&lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="16"&gt;import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamMapExample {
    public static void main(String[] args) {
        // Create a list of names
        List&lt;String&gt; names = Arrays.asList("a14mk", "manoj", "Jack");
        // Convert the list to a stream
        List&lt;String&gt; upperCaseNames = names.stream()
                // Apply the map function to transform each name to uppercase
                .map(String::toUpperCase)
                // Collect the results back into a list
                .collect(Collectors.toList());
        // Print the transformed list
        upperCaseNames.forEach(System.out::println);
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;Mapping with Complex Objects:&lt;/b&gt;&lt;br /&gt;
If you are working with a list of objects, you can use the &lt;b&gt;map&lt;/b&gt; function to transform specific fields or create new objects. For example:
&lt;br /&gt;

 &lt;textarea cols="90" name="converted_text" rows="30"&gt;import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}
public class StreamMapExample {
    public static void main(String[] args) {
        // Create a list of persons
        List&lt;Person&gt; people = Arrays.asList(
                new Person("a14mk", 25),
                new Person("manoj", 30),
                new Person("Jack", 35)
        );
        // Transform the list to get a list of names
        List&lt;String&gt; names = people.stream().map(Person::getName).collect(Collectors.toList());
        // Print the list of names
        names.forEach(System.out::println);
    }
}
&lt;/textarea&gt;
&lt;br /&gt;
In this example, the &lt;b&gt;map&lt;/b&gt; function is used to extract the names from a list of &lt;b&gt;Person&lt;/b&gt; objects.



 
 &lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/08/how-to-mapping-code-logic-using-stream.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-4255605370265700253</guid><pubDate>Sun, 04 Aug 2024 07:18:00 +0000</pubDate><atom:updated>2024-08-04T03:18:42.653-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">IOC</category><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">Spring Boot</category><title>Inversion of Control (IoC) in Spring Frameworks</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;I&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;o&lt;b&gt;C&lt;/b&gt; stands for "&lt;b&gt;Inversion of Control&lt;/b&gt;", 
a principle in software engineering where the control of objects or portions of a program is transferred to a framework or container.
 This concept is fundamental to achieving loose coupling in object-oriented design, which makes applications more modular, flexible, and easier to maintain.
&lt;br /&gt;
&lt;b&gt;Key Concepts of Inversion of Control :&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;Dependency Injection (DI)&lt;/b&gt;&lt;/li&gt;&lt;/ul&gt;&lt;ol style="text-align: left;"&gt;&lt;li style="text-align: justify;"&gt;The most common implementation of IoC.&amp;nbsp;&lt;/li&gt;&lt;li style="text-align: justify;"&gt;Dependencies (objects that a class requires to function) are injected into the class rather than the class creating them itself.&amp;nbsp;&lt;/li&gt;&lt;li style="text-align: justify;"&gt;&amp;nbsp;Can be implemented in three main ways: constructor injection, setter injection, and interface injection.
&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&lt;b&gt;	
Service Locator&lt;/b&gt;&lt;/li&gt;&lt;/ul&gt;&lt;ol style="text-align: left;"&gt;&lt;li&gt;&amp;nbsp;An alternative to dependency injection.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;A central registry (the service locator) provides dependencies upon request.&amp;nbsp;&lt;/li&gt;&lt;li&gt;&amp;nbsp;Can lead to less transparency in dependency management compared to DI.&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;How IoC Works:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&amp;nbsp; Without IoC.&lt;/li&gt;&lt;/ul&gt;
 &lt;textarea cols="90" name="converted_text" rows="5"&gt;public class Car {
      private Engine engine;
      public Car() {
          this.engine = new Engine(); // Car class is responsible for creating the Engine instance
      }
  }
&lt;/textarea&gt;
&lt;br /&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;&amp;nbsp;With IoC (Dependency Injection).&lt;/li&gt;&lt;/ul&gt;
 &lt;textarea cols="90" name="converted_text" rows="5"&gt;public class Car {
      private Engine engine;
      public Car(Engine engine) { // Engine instance is injected into Car class
          this.engine = engine;
      }
  }
&lt;/textarea&gt;
 &lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
In the example above, with IoC, the `Car` class does not create the `Engine` instance itself. Instead, 
it receives it from an external source (typically an IoC container).
&lt;br /&gt;

&lt;b&gt;Benefits of IoC:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;b&gt;Decoupling&lt;/b&gt;: Reduces the dependency between components, making the system more modular.
 &lt;b&gt;Testability&lt;/b&gt;: Easier to test components in isolation since dependencies can be easily mocked or stubbed.
 &lt;b&gt;Flexibility&lt;/b&gt;: Easier to swap out implementations of dependencies without modifying the dependent class.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;&lt;b&gt;Maintainability&lt;/b&gt;: Simplifies code management and maintenance by following the single responsibility principle.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;IoC Containers:&lt;/b&gt;
IoC containers are frameworks that manage the creation and injection of dependencies. Some popular IoC containers are:
&lt;br /&gt;
&lt;b&gt;Spring (Java)&lt;/b&gt;: Provides comprehensive support for dependency injection and IoC.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;PicoContainer (Java)&lt;/b&gt;: Lightweight and simple to use.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Unity (C#)&lt;/b&gt;: A dependency injection container from Microsoft.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Autofac (C#)&lt;/b&gt;: A popular IoC container for .NET applications.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;

&lt;b&gt;Example in Spring Framework:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
Spring Framework is a well-known example of an IoC container. Here’s how dependency injection is typically configured in a Spring application:&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&amp;nbsp;
&lt;br /&gt;
&lt;b&gt;XML Configuration:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="5"&gt; 
&lt;bean id="engine" class="com.example.Engine"/&gt;
  &lt;bean id="car" class="com.example.Car"&gt;
      &lt;constructor-arg ref="engine"/&gt;
  &lt;/bean&gt;
&lt;/textarea&gt;
&lt;br /&gt;

&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Java Configuration:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="5"&gt;@Configuration
  public class AppConfig {
      @Bean
      public Engine engine() {
          return new Engine();
      }
      
      @Bean
      public Car car() {
          return new Car(engine());
      }
  }
&lt;/textarea&gt;
 &lt;br /&gt;
 &lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Annotation-Based Configuration:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
 &lt;textarea cols="90" name="converted_text" rows="5"&gt;@Component
  public class Engine {
      // Engine properties and methods
  }
  @Component
  public class Car {
      private final Engine engine;

      @Autowired
      public Car(Engine engine) {
          this.engine = engine;
      }
  }
&lt;/textarea&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
In these examples, the Spring container manages the lifecycle and injection of the `Engine` dependency into the `Car` class.
In summary, IoC is a design principle that helps to create flexible, maintainable, and testable software systems by inverting the
control of dependency management. Dependency injection is the most common pattern used to implement IoC, 
and it is supported by various frameworks and containers across different programming languages.
 &lt;br /&gt;



&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/08/inversion-of-control-ioc-in-spring.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-6539083344183407065</guid><pubDate>Sat, 27 Apr 2024 12:34:00 +0000</pubDate><atom:updated>2024-04-27T08:34:32.956-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">Stream API</category><title>How to Develop code logic using Stream API Workflow</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;L&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;et's begin by defining the term stream as it applies to the stream API: &lt;br /&gt;
A stream operates on a data source, such as an array or a collection. A stream, itself, never provides storage on a data. It simply moves data, possibly 
filtering, sorting, or otherwise  operating on that data is the process. as a genral rule, however a stream operation by itself does not modyfy the data source.
For Example: sorting a stream does not change the order of the source.  Rather, sorting a stream results in the creation of a new stream that produces the 
sroted result.
&lt;br /&gt;
&lt;b&gt;A Simple Stream Example :&lt;/b&gt; Let's work through an example that uses streams.
The following program creates an ArrayList called myList that holds a collection of integers. Next, it obtains a stream that uses myList as a source.&lt;br /&gt;
&lt;br /&gt;	
 &lt;textarea cols="90" name="converted_text" rows="50"&gt; 
package streamclasses;
import java.util.ArrayList;
import java.util.Optional;
import java.util.stream.Stream;

/**
 *
 * @author manoj.vishwakarma
 */
public class StreamClassDemo {
    public static void main(String[] args) {
        //Create a list of integer Values
        ArrayList&lt;Integer&gt; myList=new ArrayList&lt;Integer&gt;();
        myList.add(7);
        myList.add(18);
        myList.add(10);
        myList.add(5);
        myList.add(24);
        myList.add(17);
        myList.add(5);
        System.out.println("Original Lise:" +myList);
        //Obtain a stream to the array list.
        Stream&lt;Integer&gt; myStream=myList.stream();
        //Obtain the minimum and maximum value by using of min(), max(), isPresent(), and get()
        Optional&lt;Integer&gt; minValu=myStream.min(Integer::compare);
        if(minValu.isPresent()){
            System.out.println("Minimum Value:"+minValu.get());
        }
        // Must obtain a new stream because previous call to min() is a terminal opration that consumed the stream
        //Max value
         myStream=myList.stream();
         Optional&lt;Integer&gt; maxValu=myStream.max(Integer::compare);
        if(maxValu.isPresent()){
            System.out.println("Max Value:"+maxValu.get());
        }
        
        //Sort the stream by use of sorted()
         Stream&lt;Integer&gt; sortStream=myList.stream().sorted();
         //Display the sorted stream by use of forEacg().
         System.out.println("Sorted stream");
         sortStream.forEach((n)-&gt;System.out.println(n+""));
         
         //Dispaly only the odd values by use of filter()
        
          Stream&lt;Integer&gt; oddValue=myList.stream().sorted().filter((n)-&gt;(n%2)==1);
         //Display the sorted stream by use of forEacg().
         System.out.println("Odd Values");
         oddValue.forEach((n)-&gt;System.out.println(n+""));
         
         //Display only the odd value that are greater than 5. Notice That two filter operations are pipelined
       oddValue=myList.stream().sorted().filter((n)-&gt;(n%2)==1)
                                        .filter((n)-&gt;n&gt;5);
         System.out.println("Odd Values grater  than 5:");
         oddValue.forEach((n)-&gt;System.out.println(n+""));              
    }  
}
&lt;/textarea&gt;
   &lt;br /&gt;&lt;b&gt;OUTPUT:&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHZiJQrgAAw1RXDW5eZitktADkdSdJqxeLeAvkTwvuHN2RwuMU0Wt0dgZvWkYqZZocOyb9K-pTByaMW43od2ks3ddXP0IQOHl8P9g7SAjNsAKYdFqmRNcWsyhulBWYRoJUZNWz_ReIfyfkTz-yVBT5kQicR7GaCgVYx3QPLhOhOmbkgx1eGjA1hPTNqBDW/s857/strimApiOutput.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="857" data-original-width="681" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHZiJQrgAAw1RXDW5eZitktADkdSdJqxeLeAvkTwvuHN2RwuMU0Wt0dgZvWkYqZZocOyb9K-pTByaMW43od2ks3ddXP0IQOHl8P9g7SAjNsAKYdFqmRNcWsyhulBWYRoJUZNWz_ReIfyfkTz-yVBT5kQicR7GaCgVYx3QPLhOhOmbkgx1eGjA1hPTNqBDW/s16000/strimApiOutput.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/04/how-to-develop-code-logic-using-stream.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHZiJQrgAAw1RXDW5eZitktADkdSdJqxeLeAvkTwvuHN2RwuMU0Wt0dgZvWkYqZZocOyb9K-pTByaMW43od2ks3ddXP0IQOHl8P9g7SAjNsAKYdFqmRNcWsyhulBWYRoJUZNWz_ReIfyfkTz-yVBT5kQicR7GaCgVYx3QPLhOhOmbkgx1eGjA1hPTNqBDW/s72-c/strimApiOutput.png" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-8737117966389288508</guid><pubDate>Sat, 27 Apr 2024 10:36:00 +0000</pubDate><atom:updated>2024-04-27T06:36:44.101-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SQL</category><category domain="http://www.blogger.com/atom/ns#">SQL TUTORIAL</category><title> How To Retrieve Data Using FLASHBACK  Command In Oracle.</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;T&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;his command undoes changes made by Oracle Database to the data files that exist when you run the command.
 &lt;b&gt;FLASHBACK&lt;/b&gt; can fix logical failures, but not physical failures
&lt;br /&gt;
&lt;b&gt;FLASHBACK DATABASE&lt;/b&gt; is usually much faster than a &lt;b&gt;RESTORE&lt;/b&gt; operation followed by point-in-time recovery because no data files are restored. The time needed to perform &lt;b&gt;FLASHBACK DATABASE&lt;/b&gt; depends on the number of changes made to the database since the desired flashback time. On the other hand, the time needed to 
do a traditional point-in-time recovery from restored backups depends on the size of the database.
&lt;br /&gt;

&lt;b&gt; For Example :&lt;/b&gt; &lt;br /&gt;

&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
	FLASHBACK TABLE TABLENAME to TIMESTAMP(SYSDATE-1); &amp;nbsp;&lt;/div&gt;
		&lt;/div&gt;
		&lt;br /&gt;
		&lt;b&gt;Note: If Flashback is not working on SQL Tools/Oracle DataTable you can First run the command given below and then run the flashback command.&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
	ALTER TABLE TABLENAME&amp;nbsp;ENABLE ROW MOVEMENT;&amp;nbsp;&lt;/div&gt;
		&lt;/div&gt;
 &lt;br /&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2024/04/how-to-retrieve-data-using-flashback.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-5265102815530270362</guid><pubDate>Thu, 28 Dec 2023 04:08:00 +0000</pubDate><atom:updated>2025-05-11T03:15:49.878-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">cron job scheduler</category><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">Microservices</category><category domain="http://www.blogger.com/atom/ns#">Multiples DATABASE Connection</category><category domain="http://www.blogger.com/atom/ns#">Rest API</category><category domain="http://www.blogger.com/atom/ns#">Spring Boot</category><title>Multiples DATABASE Connection and Data shifting  Using Spring Boots API </title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;M&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;ultiple DataBase Connection and Data shifting using Spring boot API configuration Example.
&lt;br /&gt; 


 &lt;div dir="ltr" trbidi="on"&gt;&lt;b&gt;S&lt;/b&gt;tep-by-step Write Java files.
 &lt;br /&gt;
1. application.properties  File for Add multiple DataBase Connection.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;2. DBConfigDBNAME.JAVA Files for multiple DataBase Connection.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;3. Job Scheduler.java file for Auto shift programm.&amp;nbsp;&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;4. Entity Beans, Repository, Services Implementations for Binding and shifting Data. 
&lt;/div&gt;
  &lt;div dir="ltr" trbidi="on"&gt;&lt;ol&gt;&lt;li&gt;&lt;b&gt;Create Spring Boot Java (Microservices)&lt;/b&gt;&lt;/li&gt;
  &lt;/ol&gt;&lt;/div&gt;&lt;/div&gt;
  
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; C&lt;/b&gt;reate Spring Boot Java (Microservices).
&lt;br /&gt;
&lt;div dir="ltr" trbidi="on"&gt;&lt;ol&gt;
  &lt;li&gt;&lt;b&gt;Project Name:&amp;nbsp;&lt;/b&gt;DataShiftingConfigSpringBoots&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Group:&amp;nbsp;&lt;/b&gt;DataShifting-a143mk&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Artifactid:&amp;nbsp;&lt;/b&gt;DataShifting-a143mk&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Description:&amp;nbsp;&lt;/b&gt;DataBase Connection and Data shifting using Spring boot API.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Package:&amp;nbsp;&lt;/b&gt;DataShiftinga143mk&lt;/li&gt;
  &lt;/ol&gt;&lt;/div&gt;
  
  &lt;/div&gt;

&lt;div&gt;Select the technologies and library(Maven Dependency ) to be.
&lt;div dir="ltr" trbidi="on"&gt;&lt;ol&gt;
  &lt;li&gt;&lt;b&gt;spring-boot-configuration-processor&lt;/b&gt;&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;ojdbc8&lt;/b&gt;&lt;/li&gt;
  &lt;/ol&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;br /&gt;
while creating the project&lt;b&gt;&amp;nbsp;pom.xml&lt;/b&gt; file and some maven dependency, main class is automatically created when web
 add any dependency like.&lt;br /&gt;

  &lt;textarea cols="90" name="converted_text" rows="8"&gt; 
  
 &lt;groupId&gt;DataShiftinga143mk&lt;/groupId&gt;
	&lt;artifactId&gt;DataShifting-a143mk&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;name&gt;DataShiftingConfigSpringBoots&lt;/name&gt;
	&lt;description&gt;DataBase Connection and Data shifting using Spring boot API&lt;/description&gt;
	&lt;properties&gt;
		&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
		&lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
		&lt;java.version&gt;1.8&lt;/java.version&gt;
	&lt;/properties&gt;
	
	
 &lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt; pom.xml&lt;/b&gt;
&lt;br /&gt;

 &lt;textarea cols="90" name="converted_text" rows="25"&gt; 
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

	&lt;groupId&gt;DataShiftinga143mk&lt;/groupId&gt;
	&lt;artifactId&gt;DataShifting-a143mk&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;packaging&gt;jar&lt;/packaging&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;name&gt;DataShiftingConfigSpringBoots&lt;/name&gt;
	&lt;description&gt;DataBase Connection and Data shifting using Spring boot API&lt;/description&gt;

	&lt;parent&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
		&lt;version&gt;1.5.3.RELEASE&lt;/version&gt;
		&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
	&lt;/parent&gt;

	&lt;properties&gt;
		&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
		&lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
		&lt;java.version&gt;1.8&lt;/java.version&gt;
	&lt;/properties&gt;



	&lt;!-- Spring Boot Starters --&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
		&lt;/dependency&gt;


	&lt;dependency&gt;
			&lt;groupId&gt;log4j&lt;/groupId&gt;
			&lt;artifactId&gt;log4j&lt;/artifactId&gt;
			&lt;version&gt;1.2.17&lt;/version&gt;
		&lt;/dependency&gt;

		 &lt;dependency&gt;
               &lt;groupId&gt;com.oracle.database.jdbc&lt;/groupId&gt;
               &lt;artifactId&gt;ojdbc8&lt;/artifactId&gt;
               &lt;version&gt;12.2.0.1&lt;/version&gt;
           &lt;/dependency&gt;

		
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt;
			&lt;optional&gt;true&lt;/optional&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;!-- Spring Boot Maven Plugin --&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
				&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
			&lt;/plugin&gt;

			
			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
				
				&lt;configuration&gt;
					&lt;useFile&gt;false&lt;/useFile&gt;
					&lt;includes&gt;
						&lt;include&gt;**/*Spec.java&lt;/include&gt;
					&lt;/includes&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;


&lt;/project&gt;



 &lt;/textarea&gt;
&lt;br /&gt;&lt;br /&gt;

  &lt;b&gt;1. Configure application.properties&lt;/b&gt;&lt;br /&gt;
   &lt;textarea cols="90" name="converted_text" rows="25"&gt;spring.jpa.database=default
spring.jpa.generate-ddl=true
server.port=9191

#  DB - "DATABASE1"
DATABASE1.datasource.driver-class-name=oracle.jdbc.OracleDriver
DATABASE1.datasource.url=jdbc:oracle:thin:@100.00.0.001:1521/serviceName(SID)
DATABASE1.datasource.username=db1UserName
DATABASE1.datasource.password=db1Password

#  DB - "DATABASE2"
DATABASE2.datasource.driver-class-name=oracle.jdbc.OracleDriver
DATABASE2.datasource.url=jdbc:oracle:thin:@100.00.1.002:1521/serviceName(SID)
DATABASE2.datasource.username=db2UserName
DATABASE2.datasource.password=db2Password

#  DB - "DATABASE3"
DATABASE3.datasource.driver-class-name=oracle.jdbc.OracleDriver
DATABASE3.datasource.url=jdbc:oracle:thin:@100.00.1.003:1521/serviceName(SID)
DATABASE3.datasource.username=db3UserName
DATABASE3.datasource.password=db3Password


#### LOGE FILE BLOCK#####
logging.level.org.springframework.web=INFO
logging.level.guru.springframework.controllers=DEBUG
logging.level.org.hibernate=ERROR
logging.file=logs/SHIPTING/masterShift.log
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

   &lt;/textarea&gt;&lt;br /&gt;
   
     &lt;br /&gt;
  &lt;b&gt;Create DataBase Configuration java Files : &lt;/b&gt;
  &lt;br /&gt;DBConfigDATABASE1.java&lt;br /&gt;
   &lt;textarea cols="90" name="converted_text" rows="25"&gt;package com.a143mk;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "DATABASE1EntityManagerFactory",
    transactionManagerRef = "DATABASE1TransactionManager", basePackages = {"com.a143mk.DATABASE1.CustomerRepo"})
public class DATABASE1DbConfig {

  @Bean(name = "DATABASE1DataSource")
  @ConfigurationProperties(prefix = "DATABASE1.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "DATABASE1EntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean DATABASE1EntityManagerFactory(
      EntityManagerFactoryBuilder builder, @Qualifier("DATABASE1DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.a143mk.DATABASE1.CustomerEntity").persistenceUnit("DATABASE1")
        .build();
  }

  @Bean(name = "DATABASE1TransactionManager")
  public PlatformTransactionManager DATABASE1TransactionManager(
      @Qualifier("DATABASE1EntityManagerFactory") EntityManagerFactory DATABASE1EntityManagerFactory) {
    return new JpaTransactionManager(DATABASE1EntityManagerFactory);
  }

}


   &lt;/textarea&gt;&lt;br /&gt;
   
    &lt;br /&gt;DBConfigDATABASE2.java&lt;br /&gt;
   &lt;textarea cols="90" name="converted_text" rows="25"&gt;package com.a143mk;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "DATABASE2EntityManagerFactory",
    transactionManagerRef = "DATABASE2TransactionManager", basePackages = {"com.a143mk.DATABASE2.CustomerRepo"})
public class DATABASE2DbConfig {

  @Bean(name = "DATABASE2DataSource")
  @ConfigurationProperties(prefix = "DATABASE2.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "DATABASE2EntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean DATABASE2EntityManagerFactory(
      EntityManagerFactoryBuilder builder, @Qualifier("DATABASE2DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.a143mk.DATABASE2.CustomerEntity").persistenceUnit("DATABASE2")
        .build();
  }

  @Bean(name = "DATABASE2TransactionManager")
  public PlatformTransactionManager DATABASE2TransactionManager(
      @Qualifier("DATABASE2EntityManagerFactory") EntityManagerFactory DATABASE2EntityManagerFactory) {
    return new JpaTransactionManager(DATABASE2EntityManagerFactory);
  }

}
   &lt;/textarea&gt;&lt;br /&gt;
   
   
   
      &lt;br /&gt;DBConfigDATABASE3.java&lt;br /&gt;
   &lt;textarea cols="90" name="converted_text" rows="25"&gt;package com.a143mk;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "DATABASE3EntityManagerFactory",
    transactionManagerRef = "DATABASE3TransactionManager", basePackages = {"com.a143mk.DATABASE3.CustomerRepo"})
public class DATABASE3DbConfig {

  @Bean(name = "DATABASE3DataSource")
  @ConfigurationProperties(prefix = "DATABASE3.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "DATABASE3EntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean DATABASE3EntityManagerFactory(
      EntityManagerFactoryBuilder builder, @Qualifier("DATABASE3DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.a143mk.DATABASE3.CustomerEntity").persistenceUnit("DATABASE3")
        .build();
  }

  @Bean(name = "DATABASE3TransactionManager")
  public PlatformTransactionManager DATABASE3TransactionManager(
      @Qualifier("DATABASE3EntityManagerFactory") EntityManagerFactory DATABASE3EntityManagerFactory) {
    return new JpaTransactionManager(DATABASE3EntityManagerFactory);
  }

}


   &lt;/textarea&gt;&lt;br /&gt;
   
   
    &lt;b&gt;Create Scheduler Class&lt;/b&gt;Create Scheduler for Auto run Program and import some Packages &lt;b&gt;Scheduler.java&lt;/b&gt; as below:&lt;br /&gt;
	&lt;textarea cols="90" name="converted_text" rows="30"&gt; 
	package com.a143mk.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import com.a143mk.DATABASE3.ServiceImpl.MastCustomerDATABASE3ServiceImpl;
import com.a143mk.DATABASE2.ServiceImpl.MastCustomerDATABASE2ServiceImpl;
import com.a143mk.DATABASE1.CustomerServicesImpl.CustomerMasterDATABASE1SericesImpl;
@EnableScheduling
@Configuration
public class Scheduler {
	
	
	@Autowired
	private CustomerMasterDATABASE1SericesImpl custDATABASE1ServiceImpl;
	
	@Autowired
	private MastCustomerDATABASE3ServiceImpl DATABASE3CustomerServiImpl;
	
	@Autowired
	private  MastCustomerDATABASE2ServiceImpl  DATABASE2CustServeImple;

	
	
	@Scheduled(cron = "0 */1 * ? * *")
	public void customerScheduletoDATABASE1() throws Exception {
		custDATABASE1ServiceImpl.customerinsertToDATABASE1();	
	}
	
	@Scheduled(cron = "0 */1 * ? * *")
	public void customerScheduletoDATABASE3() throws Exception {
	 DATABASE3CustomerServiImpl.customerinsertToDATABASE3();	
	}
	
	@Scheduled(cron = "0 */1 * ? * *")
	public void customerScheduletoDATABASE2() throws Exception {
	DATABASE2CustServeImple.customerinsertToDATABASE2();	
	}	

}

	&lt;/textarea&gt;&lt;br /&gt;
	&lt;b&gt;Have you seen the previous post? You all know how to learn and create Entity Bean, Repository,
	Service Implementation in the project.	If you don't know about it then go to the previous post and learn it.&lt;/b&gt;&lt;br /&gt;




</description><link>https://a143mk.blogspot.com/2023/12/multiples-database-connection-and-data.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-3072192993596469429</guid><pubDate>Sat, 07 Oct 2023 06:17:00 +0000</pubDate><atom:updated>2023-10-07T02:21:31.187-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">External Jar</category><category domain="http://www.blogger.com/atom/ns#">Maven</category><title>How to add External Jar file in Pom.xml file</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;A&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;dd Externals Jar file in Pom.xml&lt;br /&gt; 
There are many ways to configure external jar file but we are telling you an easy way, for this you should have whatever jar 
file you want to add, after that you know the .m2/repository folder.
&lt;br /&gt; 
Add dependencies in pom.xml and after saving the file, a folder 
is auto created inside the .m2/repository which is named after the groupId in dependency, such a groupId name is a143mkJar.
&lt;br /&gt;
&lt;b&gt; For Example :&lt;/b&gt; I have two Jar file one is &lt;a href="https://drive.google.com/file/d/1MouXylXH_pDMnFJADeebwVhka7Ngp8wI/view?usp=sharing" target="_blank"&gt;EncryptDecryptA143mk-2.7.7.jar &lt;/a&gt;and &lt;a href="https://drive.google.com/file/d/1CrR5qtz5hxUWWEHJPDKVgt8SiVehhYZg/view?usp=sharing"&gt;Ldap-a143mkJar-2.7.7.jar&lt;/a&gt;&lt;br /&gt;
&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
        groupId is a143mkJar&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
		artifactId is EncryptDecryptA143mk&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
		version is 2.7.7&amp;nbsp;&lt;/div&gt;
		&lt;/div&gt;
		&lt;br /&gt;
		&lt;b&gt;Add dependences in pom.xml:&lt;/b&gt;&lt;br /&gt;
 &lt;textarea cols="90" name="converted_text" rows="10"&gt;&lt;dependency&gt;
 &lt;groupId&gt;a143mkJar&lt;/groupId&gt;
 &lt;artifactId&gt;EncryptDecryptA143mk&lt;/artifactId&gt;
 &lt;version&gt;2.7.7&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
 &lt;groupId&gt;a143mkJar&lt;/groupId&gt;
 &lt;artifactId&gt;Ldap-a143mkJar&lt;/artifactId&gt;
  &lt;version&gt;2.7.7&lt;/version&gt;
&lt;/dependency&gt;
 &lt;/textarea&gt;
 &lt;br /&gt;
&lt;b&gt;Put the Jar file in maven repository Directory like this.&lt;/b&gt;
&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
        .m2/repository/a143mkJar/EncryptDecryptA143mk/2.7.7/EncryptDecryptA143mk-2.7.7.jar&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;.m2/repository/a143mkJar/Ldap-a143mkJar/2.7.7/Ldap-a143mkJar-2.7.7.jar&lt;/div&gt;&lt;/div&gt;

		





&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2023/10/how-to-add-external-jar-file-in-pomxml.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-7847863868599657841</guid><pubDate>Tue, 19 Sep 2023 09:56:00 +0000</pubDate><atom:updated>2023-09-19T06:01:06.661-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">Spring Boot</category><title>How to  PACKAGE Spring Boot application to JAR and WAR </title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;M&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;aven is a popular build tool, that takes your project’s Java source code, 
compiles it, tests it and converts it into an executable Java program: either a .jar or a .war file.
 &amp;nbsp;&lt;/div&gt;
 &lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Package Spring Boot application to JAR OR WAR file:&lt;/b&gt;
 &lt;br /&gt;
 The default packaging type of a Spring Boot project is jar if the &lt;packaging&gt; attribute is not present in the pom.xml file.
 It’s better to check your project’s pom.xml file to make sure that the packaging type is jar or War:
 &lt;/packaging&gt;&lt;/div&gt;
  &lt;textarea cols="90" name="converted_text" rows="3"&gt; &lt;packaging&gt;jar&lt;/packaging&gt;
	OR 
	&lt;packaging&gt;WAR&lt;/packaging&gt;
 &lt;/textarea&gt;  
 &lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div dir="ltr" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;&lt;b&gt;I&lt;/b&gt;f you use an IDE such as Eclipse or Spring Tool Suite, 
  right-click on the project, then select Run As &amp;gt; Maven Configuration Like:&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;&lt;ul style="text-align: left;"&gt;&lt;li&gt;CLEAN&lt;/li&gt;&lt;li&gt;BUILD&lt;/li&gt;&lt;li&gt;INSTALL&lt;/li&gt;&lt;li&gt;PACKAGE.................etc.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;
   &lt;!--IMAGE BOLCK--&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrNd3daKiZnoCFtzG-urocLTYUAsYXh7aTUkmcOo-Y1-Wq9kvja_d_AuuZC0pipfVnhqRLlN6gordhPs7RtZ_mya3MyngTf-vFypMEABo24tHppWwFnXjlV-FvIzp2yDqD2JMIRBevtute4N_1gYxXZYSvk0U6shdeH6jES5vdJbwchleDskYdvV1YpZkJ/s871/package.png" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="702" data-original-width="871" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrNd3daKiZnoCFtzG-urocLTYUAsYXh7aTUkmcOo-Y1-Wq9kvja_d_AuuZC0pipfVnhqRLlN6gordhPs7RtZ_mya3MyngTf-vFypMEABo24tHppWwFnXjlV-FvIzp2yDqD2JMIRBevtute4N_1gYxXZYSvk0U6shdeH6jES5vdJbwchleDskYdvV1YpZkJ/s16000/package.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2023/09/how-to-package-spring-boot-application.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrNd3daKiZnoCFtzG-urocLTYUAsYXh7aTUkmcOo-Y1-Wq9kvja_d_AuuZC0pipfVnhqRLlN6gordhPs7RtZ_mya3MyngTf-vFypMEABo24tHppWwFnXjlV-FvIzp2yDqD2JMIRBevtute4N_1gYxXZYSvk0U6shdeH6jES5vdJbwchleDskYdvV1YpZkJ/s72-c/package.png" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4382912182462653256.post-290286225450481906</guid><pubDate>Wed, 05 Jul 2023 12:19:00 +0000</pubDate><atom:updated>2023-07-21T07:13:27.454-04:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">java 8</category><category domain="http://www.blogger.com/atom/ns#">LDAP</category><title>Simple LDAP sign-on  Authentication Using Ldap-a143mkJar</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;b&gt;&lt;span style="font-family: Georgia,&amp;quot;Times New Roman&amp;quot;,serif;"&gt;
&lt;span style="font-size: large;"&gt;L&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;DAP sign-on is an authentication scheme that allows a user to log in with a single ID to any of 
several related, independent, software systems or web applications. In this post user will login through Outlook Mail.

&lt;a href="https://drive.google.com/file/d/1bNoICiusj0vp1-5BnZPgtCz1oybjemlc/view?usp=sharing" target="_blank"&gt;Ldap-a143mkJar.jar&lt;/a&gt; 
&lt;div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;Process of Ldap sign-On (LSO) Authentication:&lt;/b&gt;&lt;/div&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiN9cMgL4u3Go-k4kDIW9eQzQxgh-FDZ1MrRlMcDpAGEJgnsg0-JLtVLmg8-pHnLDGtTb6myvr-Q3DRK2mHPrZkLqKYkOpaaYEclr3g3jFy-pY7Q3IoDPAzpTG3eZ5kmNJH-zi5P6MXliLoAdqhSRQm2F06uEz9OYJVDuZaPE7ZHWvy-96apCD6BqRLZw17/s687/ldap-view.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="487" data-original-width="687" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiN9cMgL4u3Go-k4kDIW9eQzQxgh-FDZ1MrRlMcDpAGEJgnsg0-JLtVLmg8-pHnLDGtTb6myvr-Q3DRK2mHPrZkLqKYkOpaaYEclr3g3jFy-pY7Q3IoDPAzpTG3eZ5kmNJH-zi5P6MXliLoAdqhSRQm2F06uEz9OYJVDuZaPE7ZHWvy-96apCD6BqRLZw17/s16000/ldap-view.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
 &lt;div dir="ltr" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;
 &lt;div dir="ltr" trbidi="on"&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div dir="ltr" trbidi="on"&gt;&lt;b&gt;D&lt;/b&gt;ownload the jar file and implement some methods / functions have been used, the names of the methods 
 are as follows:&lt;/div&gt;
  &lt;br /&gt;
   &lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
  Call Class object LdapClient ldapClientClass=new LdapClient();&lt;/div&gt;&lt;/div&gt;
 &lt;div dir="ltr" trbidi="on"&gt;
 &lt;ol&gt;
 &lt;li&gt;&lt;b&gt;A143mkLdapConnection(ldapUrl, ldapDnConn, userEmailId, password);&lt;/b&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;b&gt;T&lt;/b&gt;here are some parameters in  methods, 
which we initialize by creating configuration object like this.&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;/div&gt;

&lt;div style="background: rgb(241, 241, 241); border: 1pt solid rgb(214, 214, 214); mso-border-alt: solid #D6D6D6 .75pt; mso-element: para-border-div; padding: 4pt 0cm 4pt 4pt;"&gt;
&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
         String ldapUrl= "ldap://172.0.0.0:389/";&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
		 String lDapDnConn="dc=domainName,dc=com";&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
		 String userEmailId="EmailMail@mailDomen.com";&amp;nbsp;&lt;/div&gt;&lt;div class="MsoNormal" style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: none; line-height: normal; margin-bottom: 0.0001pt; padding: 0cm;"&gt;
		 String password="mailPassword";&amp;nbsp;&lt;/div&gt;&lt;/div&gt;
&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;How to create a project/main class/other class to follow us. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKjXGuNgt5QawcjSt-khZP-G48voe03LahxIW8LRixwgQIIL3uJu9aJKt0lCiE2VLxeeyQl5WzKb8AgVYx1WBDpAptxCLIvzYCJ9KewFEfXI7Ln5l_jW85LYPNeCd39lKbg3vFCJ2mBs2x-FlZvnTBT3_d5j1aDjOzsaKrm_2ESznm6tfXWf4IYUGRoDP0/s1916/runProject.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="934" data-original-width="1916" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKjXGuNgt5QawcjSt-khZP-G48voe03LahxIW8LRixwgQIIL3uJu9aJKt0lCiE2VLxeeyQl5WzKb8AgVYx1WBDpAptxCLIvzYCJ9KewFEfXI7Ln5l_jW85LYPNeCd39lKbg3vFCJ2mBs2x-FlZvnTBT3_d5j1aDjOzsaKrm_2ESznm6tfXWf4IYUGRoDP0/s16000/runProject.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;/div&gt;
while creating the controller/main class&lt;b&gt;&amp;nbsp;Ldapconn.java&lt;/b&gt;.&lt;br /&gt;

  &lt;textarea cols="90" name="converted_text" rows="15"&gt; 

package ldapconn;
import ldap.a143mkjar.LdapClient;
import ldap.a143mkjar.LdapConnUser;
/**
 *
 * @author manoj.vishwakarma
 */
public class Ldapconn { 
     public static void main(String[] args) {
         //ldap-server configuration
        String ldapUrl= "ldap://172.0.0.0:389/";
        String lDapDnConn="dc=domainName,dc=com";
        String userEmailId="EmailMail@mailDomen.com";
        String password="mailPassword";
        
       LdapClient ldapClientClass=  new LdapClient();
       LdapConnUser get=ldapClientClass.A143mkLdapConnection(ldapUrl, lDapDnConn, userEmailId, password);
       if(get.getErrorLdapConn()==null){
          System.out.println(" DNParaMeter: "+get.getLdapDNParaMeter()+
                             "\n UserFirstName: "+get.getLdapUserFirstName()+
                             "\n UserSN: "+get.getLdapUserSN()+
                             "\n UserMailID: "+get.getLdapUserMailID()+
                              "\n accPassExpires: "+get.getAccPassExpires()+
                               "\n department: "+get.getDepartment()+
                                "\n description: "+get.getDescription()+
                                 "\n st: "+get.getSt()+
                                   "\n streetAddress: "+get.getStreetAddress());
          
  } else{
         System.out.println(get.getErrorLdapConn());
       }
     }
    
    
}

 &lt;/textarea&gt;
&lt;br /&gt;
&lt;b&gt;&lt;br /&gt; &lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Output :&lt;/b&gt;
&lt;br /&gt;

  



&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtZI24dAm8Vewm-5LPSSocAix2rz3iJQHTkLowiQBzIS7gzf9ySaPvzFjZULcKGGSXUKyDgmZOTsu5Ftnl5AgiKnb83BXXbtzFq6nqlCLOESG4Hd1E2l-KjVWik_gBVIjkI8xmZ-u2WkuoA5CclnQUPvNzP1GRPv9wiZkMUIEP_lnRhrd0GjnG_-OghMnn/s1471/output.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" data-original-height="547" data-original-width="1471" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtZI24dAm8Vewm-5LPSSocAix2rz3iJQHTkLowiQBzIS7gzf9ySaPvzFjZULcKGGSXUKyDgmZOTsu5Ftnl5AgiKnb83BXXbtzFq6nqlCLOESG4Hd1E2l-KjVWik_gBVIjkI8xmZ-u2WkuoA5CclnQUPvNzP1GRPv9wiZkMUIEP_lnRhrd0GjnG_-OghMnn/s16000/output.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;/div&gt;</description><link>https://a143mk.blogspot.com/2023/07/simple-ldap-sign-on-authentication.html</link><author>noreply@blogger.com (A143MK PROGRAMMING)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiN9cMgL4u3Go-k4kDIW9eQzQxgh-FDZ1MrRlMcDpAGEJgnsg0-JLtVLmg8-pHnLDGtTb6myvr-Q3DRK2mHPrZkLqKYkOpaaYEclr3g3jFy-pY7Q3IoDPAzpTG3eZ5kmNJH-zi5P6MXliLoAdqhSRQm2F06uEz9OYJVDuZaPE7ZHWvy-96apCD6BqRLZw17/s72-c/ldap-view.png" width="72"/><thr:total>1</thr:total></item></channel></rss>