├── .gitattributes ├── chat-bot-react ├── jsconfig.json ├── src │ └── app │ │ ├── favicon.ico │ │ ├── globals.css │ │ ├── layout.js │ │ └── page.js ├── next.config.mjs ├── postcss.config.mjs ├── public │ ├── vercel.svg │ ├── window.svg │ ├── file.svg │ ├── globe.svg │ └── next.svg ├── eslint.config.mjs ├── package.json ├── .gitignore └── README.md ├── src ├── main │ ├── java │ │ └── com │ │ │ └── engripaye │ │ │ └── ai_chatbot_system │ │ │ ├── repository │ │ │ ├── UserRepository.java │ │ │ ├── MessageRepository.java │ │ │ └── ChatRepository.java │ │ │ ├── model │ │ │ ├── User.java │ │ │ ├── Chat.java │ │ │ └── Message.java │ │ │ ├── AiChatbotSystemApplication.java │ │ │ ├── config │ │ │ └── SocketIOConfig.java │ │ │ ├── controller │ │ │ └── ChatController.java │ │ │ ├── webSocket │ │ │ └── ChatWebSocketHandler.java │ │ │ └── service │ │ │ └── ChatService.java │ └── resources │ │ └── application.properties └── test │ └── java │ └── com │ └── engripaye │ └── ai_chatbot_system │ └── AiChatbotSystemApplicationTests.java ├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── README.md ├── pom.xml ├── mvnw.cmd └── mvnw /.gitattributes: -------------------------------------------------------------------------------- 1 | /mvnw text eol=lf 2 | *.cmd text eol=crlf 3 | -------------------------------------------------------------------------------- /chat-bot-react/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "paths": { 4 | "@/*": ["./src/*"] 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /chat-bot-react/src/app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/engripaye/ai-chatbot-system/HEAD/chat-bot-react/src/app/favicon.ico -------------------------------------------------------------------------------- /chat-bot-react/next.config.mjs: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = {}; 3 | 4 | export default nextConfig; 5 | -------------------------------------------------------------------------------- /chat-bot-react/postcss.config.mjs: -------------------------------------------------------------------------------- 1 | const config = { 2 | plugins: ["@tailwindcss/postcss"], 3 | }; 4 | 5 | export default config; 6 | -------------------------------------------------------------------------------- /chat-bot-react/public/vercel.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.repository; 2 | 3 | import com.engripaye.ai_chatbot_system.model.User; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | public interface UserRepository extends MongoRepository { 7 | 8 | User findByUsername(String username); 9 | } 10 | -------------------------------------------------------------------------------- /chat-bot-react/public/window.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chat-bot-react/public/file.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/test/java/com/engripaye/ai_chatbot_system/AiChatbotSystemApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 7 | class AiChatbotSystemApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/model/User.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.mongodb.core.mapping.Document; 6 | 7 | @Data 8 | @Document(collection = "users") 9 | public class User { 10 | 11 | @Id 12 | private String id; 13 | private String username; 14 | private String role; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/repository/MessageRepository.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.repository; 2 | 3 | import com.engripaye.ai_chatbot_system.model.Message; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | import java.util.List; 7 | 8 | public interface MessageRepository extends MongoRepository { 9 | 10 | List findByChatId(String chatId); 11 | } 12 | -------------------------------------------------------------------------------- /chat-bot-react/eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import { dirname } from "path"; 2 | import { fileURLToPath } from "url"; 3 | import { FlatCompat } from "@eslint/eslintrc"; 4 | 5 | const __filename = fileURLToPath(import.meta.url); 6 | const __dirname = dirname(__filename); 7 | 8 | const compat = new FlatCompat({ 9 | baseDirectory: __dirname, 10 | }); 11 | 12 | const eslintConfig = [...compat.extends("next/core-web-vitals")]; 13 | 14 | export default eslintConfig; 15 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=ai-chatbot-system 2 | 3 | # OpenRouter AI Configuration 4 | spring.ai.openai.api-base-url=https://openrouter.ai/api/v1 5 | spring.ai.openai.chat.options.model=meta-llama/llama-3.2-8b-instruct 6 | spring.ai.openai.chat.options.temperature=0.7 7 | 8 | # MongoDB Configuration 9 | spring.data.mongodb.uri=mongodb://localhost:27017/chatbot 10 | spring.data.mongodb.database=chatbot 11 | 12 | # Server Port 13 | server.port=0 14 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/repository/ChatRepository.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.repository; 2 | 3 | import com.engripaye.ai_chatbot_system.model.Chat; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | import java.util.List; 7 | 8 | public interface ChatRepository extends MongoRepository { 9 | 10 | List findByCustomerId(String customerId); 11 | List findByAgentId(String agentId); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/model/Chat.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.mongodb.core.mapping.Document; 6 | 7 | import java.util.List; 8 | 9 | @Data 10 | @Document(collection = "chats") 11 | public class Chat { 12 | @Id 13 | private String id; 14 | private String customerId; 15 | private String agentId; 16 | private List messageIds; 17 | private boolean active; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /chat-bot-react/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chat-bot-react", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev --turbopack", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint" 10 | }, 11 | "dependencies": { 12 | "react": "19.1.0", 13 | "react-dom": "19.1.0", 14 | "next": "15.4.2" 15 | }, 16 | "devDependencies": { 17 | "@tailwindcss/postcss": "^4", 18 | "tailwindcss": "^4", 19 | "eslint": "^9", 20 | "eslint-config-next": "15.4.2", 21 | "@eslint/eslintrc": "^3" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/AiChatbotSystemApplication.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.PropertySource; 6 | 7 | @SpringBootApplication 8 | @PropertySource("classpath:application-secrets.properties") 9 | public class AiChatbotSystemApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(AiChatbotSystemApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | .mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | 35 | # Ignore secrets 36 | src/main/resources/application-secrets.properties 37 | -------------------------------------------------------------------------------- /chat-bot-react/src/app/globals.css: -------------------------------------------------------------------------------- 1 | @import "tailwindcss"; 2 | 3 | :root { 4 | --background: #ffffff; 5 | --foreground: #171717; 6 | } 7 | 8 | @theme inline { 9 | --color-background: var(--background); 10 | --color-foreground: var(--foreground); 11 | --font-sans: var(--font-geist-sans); 12 | --font-mono: var(--font-geist-mono); 13 | } 14 | 15 | @media (prefers-color-scheme: dark) { 16 | :root { 17 | --background: #0a0a0a; 18 | --foreground: #ededed; 19 | } 20 | } 21 | 22 | body { 23 | background: var(--background); 24 | color: var(--foreground); 25 | font-family: Arial, Helvetica, sans-serif; 26 | } 27 | -------------------------------------------------------------------------------- /chat-bot-react/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.* 7 | .yarn/* 8 | !.yarn/patches 9 | !.yarn/plugins 10 | !.yarn/releases 11 | !.yarn/versions 12 | 13 | # testing 14 | /coverage 15 | 16 | # next.js 17 | /.next/ 18 | /out/ 19 | 20 | # production 21 | /build 22 | 23 | # misc 24 | .DS_Store 25 | *.pem 26 | 27 | # debug 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | .pnpm-debug.log* 32 | 33 | # env files (can opt-in for committing if needed) 34 | .env* 35 | 36 | # vercel 37 | .vercel 38 | 39 | # typescript 40 | *.tsbuildinfo 41 | next-env.d.ts 42 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/config/SocketIOConfig.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.config; 2 | 3 | import com.corundumstudio.socketio.SocketIOServer; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class SocketIOConfig { 9 | 10 | @Bean 11 | public SocketIOServer socketIOServer(){ 12 | com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); 13 | 14 | config.setHostname("localhost"); 15 | config.setPort(8080); 16 | return new SocketIOServer(config); 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/model/Message.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.mongodb.core.mapping.Document; 6 | 7 | import java.time.LocalDateTime; 8 | 9 | @Data 10 | @Document(collection = "messages") 11 | public class Message { 12 | @Id 13 | private String id; 14 | private String chatId; 15 | private String senderId; 16 | private String senderRole; // CUSTOMER, AGENT, AI 17 | private String content; 18 | private LocalDateTime timeStamp; 19 | private Double confidence; // AI Confidence score 20 | private boolean requireHandOff; 21 | 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /chat-bot-react/src/app/layout.js: -------------------------------------------------------------------------------- 1 | import { Geist, Geist_Mono } from "next/font/google"; 2 | import "./globals.css"; 3 | 4 | const geistSans = Geist({ 5 | variable: "--font-geist-sans", 6 | subsets: ["latin"], 7 | }); 8 | 9 | const geistMono = Geist_Mono({ 10 | variable: "--font-geist-mono", 11 | subsets: ["latin"], 12 | }); 13 | 14 | export const metadata = { 15 | title: "Create Next App", 16 | description: "Generated by create next app", 17 | }; 18 | 19 | export default function RootLayout({ children }) { 20 | return ( 21 | 22 | 25 | {children} 26 | 27 | 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /chat-bot-react/public/globe.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | wrapperVersion=3.3.2 18 | distributionType=only-script 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.10/apache-maven-3.9.10-bin.zip 20 | -------------------------------------------------------------------------------- /chat-bot-react/public/next.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/controller/ChatController.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.controller; 2 | 3 | import com.engripaye.ai_chatbot_system.model.Chat; 4 | import com.engripaye.ai_chatbot_system.model.Message; 5 | import com.engripaye.ai_chatbot_system.model.User; 6 | import com.engripaye.ai_chatbot_system.service.ChatService; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import javax.print.attribute.standard.MediaSize; 10 | import java.util.List; 11 | 12 | @RestController 13 | @RequestMapping("/api") 14 | public class ChatController { 15 | 16 | private final ChatService chatService; 17 | 18 | public ChatController(ChatService chatService) { 19 | this.chatService = chatService; 20 | } 21 | 22 | @GetMapping("/chats") 23 | public List getAllChats(){ 24 | return chatService.getAllChats(); 25 | } 26 | 27 | @GetMapping("/chats/{chatId}/history") 28 | public List getChatHistory(@PathVariable String chatId){ 29 | return chatService.getChatHistory(chatId); 30 | } 31 | 32 | @GetMapping("/agent/{agentId}/chats") 33 | public List getAgentChats(@PathVariable String agentId){ 34 | return chatService.getAgentChats(agentId); 35 | } 36 | 37 | @PostMapping("/users") 38 | public User createUser(@RequestBody User user) { 39 | return chatService.saveUser(user); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /chat-bot-react/README.md: -------------------------------------------------------------------------------- 1 | This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). 2 | 3 | ## Getting Started 4 | 5 | First, run the development server: 6 | 7 | ```bash 8 | npm run dev 9 | # or 10 | yarn dev 11 | # or 12 | pnpm dev 13 | # or 14 | bun dev 15 | ``` 16 | 17 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. 18 | 19 | You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file. 20 | 21 | This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. 22 | 23 | ## Learn More 24 | 25 | To learn more about Next.js, take a look at the following resources: 26 | 27 | - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. 28 | - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. 29 | 30 | You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! 31 | 32 | ## Deploy on Vercel 33 | 34 | The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. 35 | 36 | Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. 37 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/webSocket/ChatWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.webSocket; 2 | 3 | import com.corundumstudio.socketio.SocketIOServer; 4 | import com.engripaye.ai_chatbot_system.model.Message; 5 | import com.engripaye.ai_chatbot_system.service.ChatService; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import jakarta.annotation.PostConstruct; 8 | import org.springframework.stereotype.Component; 9 | 10 | import java.util.Map; 11 | 12 | @Component 13 | public class ChatWebSocketHandler { 14 | 15 | private final SocketIOServer socketIOServer; 16 | private final ChatService chatService; 17 | private final ObjectMapper objectMapper; 18 | 19 | 20 | public ChatWebSocketHandler(SocketIOServer socketIOServer, ChatService chatService, ObjectMapper objectMapper) { 21 | this.socketIOServer = socketIOServer; 22 | this.chatService = chatService; 23 | this.objectMapper = objectMapper; 24 | } 25 | 26 | @PostConstruct 27 | public void start() { 28 | socketIOServer.addEventListener("message", Map.class, (client, data, askSender) -> { 29 | String userId = (String) data.get("userId"); 30 | String role = (String) data.get("role"); 31 | String content = (String) data.get("content"); 32 | String chatId = (String) data.get("chatId"); 33 | 34 | Message response; 35 | if ("CUSTOMER".equals(role)) { 36 | response = chatService.processCustomerMessage(userId, content); 37 | 38 | } else if ("AGENT".equals(role)) { 39 | response = chatService.processAgentMessage(chatId, userId, content); 40 | 41 | }else { 42 | return; 43 | } 44 | 45 | socketIOServer.getBroadcastOperations().sendEvent("message", objectMapper.writeValueAsString(response)); 46 | 47 | 48 | }); 49 | socketIOServer.start(); 50 | } 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Complete AI Customer Support Chatbot System using Spring Boot 2 | ## Spring AI with OpenRouter, 3 | WebSocket and REST, MongoDB, and a React/HTML frontend. The system will include smart auto-responses, human handoff for low-confidence AI responses, role-based support agents (customer, agent, admin), and an admin dashboard to monitor chats. I’ll use Java 21 and Spring Boot 3.3.2 (latest stable version as of July 21, 2025, as Spring Boot 3.5 is not widely confirmed), noting adjustments for 3.5 if applicable. This guide is detailed and beginner-friendly, with explanations for each step. 4 | 5 | Overview 6 | The system will: 7 | 1. Use Spring Boot for the backend, with Spring AI integrating OpenRouter’s API for AI-powered responses. 8 | 2. Implement WebSocket for real-time chat and REST for admin and user management. 9 | 3. Store chat data in MongoDB for persistence. 10 | 4. Provide a React frontend for customers, agents, and admins, with a dashboard to monitor chats. 11 | 5. Support smart auto-responses with confidence scoring, human handoff, and role-based access. 12 | 13 | Prerequisites 14 | 1. Java 21: Install OpenJDK 21 (e.g., via SDKMAN: sdk install java 21-open). 15 | 2. Maven: For dependency management. 16 | 3. OpenRouter API Key: Sign up at OpenRouter and generate an API key. 17 | 4. MongoDB: Install locally (MongoDB Community Server) or use MongoDB Atlas. 18 | 5. Node.js/NPM: For the React frontend (install from http://nodejs.org). 19 | 6. IDE: IntelliJ IDEA, Eclipse, or VS Code. 20 | 7. Postman or curl: For testing REST APIs. 21 | 22 | Step 1: Set Up OpenRouter 23 | OpenRouter provides access to various LLMs via a unified API, making it a flexible choice for AI responses. 24 | 1. Get an API Key: 25 | • Sign up at OpenRouter. 26 | • Navigate to the dashboard, click “Keys” in the sidebar, and create a new API key. 27 | • Save the key securely. 28 | 29 | 2. Test the API: 30 | • Use curl to verify: 31 | curl -X POST https://openrouter.ai/api/v1/chat/completions \ 32 | -H "Authorization: Bearer YOUR_API_KEY" \ 33 | -H "Content-Type: application/json" \ 34 | -d '{"model": "meta-llama/llama-3.2-8b-instruct", "messages": [{"role": "user", "content": "Hello, how can I assist you today?"}]}' 35 | • Expect a JSON response with the AI’s reply. 36 | 37 | Explanation: 38 | • OpenRouter supports models like meta-llama/llama-3.2-8b-instruct, which is suitable for customer support. 39 | • The API key and model will be configured in Spring AI. 40 | 41 | Step 2: Project Setup 42 | Create a Spring Boot project using Spring Initializr. 43 | 1. Create Project: 44 | • Go to http://start.spring.io. 45 | • Configure: 46 | • Project: Maven 47 | • Language: Java 48 | • Spring Boot: 3.3.2 (latest stable; adjust to 3.5.3 if confirmed available) 49 | • Java: 21 50 | • Group: com.example 51 | • Artifact: chatbot-system 52 | • Dependencies: 53 | • Spring Web 54 | • Spring WebFlux (for WebSocket) 55 | • Spring Data MongoDB 56 | • Lombok 57 | • Generate, download, unzip, and open in your IDE. 58 | 2. Add Spring AI Dependency: Since Spring AI does not have a specific OpenRouter starter, we’ll use the generic spring-ai-openai-spring-boot-starter (OpenRouter’s API is compatible with OpenAI’s format) 59 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.3.3 9 | 10 | 11 | com.engripaye 12 | ai-chatbot-system 13 | 0.0.1-SNAPSHOT 14 | ai-chatbot-system 15 | AI Customer Support Chatbot with SpringBoot and Hugging face 16 | 17 | 21 18 | 19 | 20 | 21 | 22 | 23 | org.springframework.ai 24 | spring-ai-bom 25 | 1.0.0-M2 26 | pom 27 | import 28 | 29 | 30 | 31 | 32 | 33 | 34 | spring-milestones 35 | Spring Milestones 36 | https://repo.spring.io/milestone 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.ai 43 | spring-ai-openai-spring-boot-starter 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-data-mongodb 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-web 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-websocket 56 | 57 | 58 | org.projectlombok 59 | lombok 60 | 1.18.32 61 | provided 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-starter-test 66 | test 67 | 68 | 69 | 70 | 71 | com.corundumstudio.socketio 72 | netty-socketio 73 | 2.0.3 74 | 75 | 76 | 77 | 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-compiler-plugin 82 | 83 | 84 | 85 | org.projectlombok 86 | lombok 87 | 88 | 89 | 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-maven-plugin 94 | 95 | 96 | 97 | org.projectlombok 98 | lombok 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /chat-bot-react/src/app/page.js: -------------------------------------------------------------------------------- 1 | import Image from "next/image"; 2 | 3 | export default function Home() { 4 | return ( 5 |
6 |
7 | Next.js logo 15 |
    16 |
  1. 17 | Get started by editing{" "} 18 | 19 | src/app/page.js 20 | 21 | . 22 |
  2. 23 |
  3. 24 | Save and see your changes instantly. 25 |
  4. 26 |
27 | 28 | 53 |
54 | 101 |
102 | ); 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/engripaye/ai_chatbot_system/service/ChatService.java: -------------------------------------------------------------------------------- 1 | package com.engripaye.ai_chatbot_system.service; 2 | 3 | import com.engripaye.ai_chatbot_system.model.Chat; 4 | import com.engripaye.ai_chatbot_system.model.Message; 5 | import com.engripaye.ai_chatbot_system.model.User; 6 | import com.engripaye.ai_chatbot_system.repository.ChatRepository; 7 | import com.engripaye.ai_chatbot_system.repository.MessageRepository; 8 | import com.engripaye.ai_chatbot_system.repository.UserRepository; 9 | import lombok.Getter; 10 | import org.springframework.ai.chat.client.ChatClient; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.time.LocalDateTime; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | import java.util.UUID; 17 | 18 | @Service 19 | public class ChatService { 20 | 21 | private final ChatClient chatClient; 22 | private final MessageRepository messageRepository; 23 | private final ChatRepository chatRepository; 24 | @Getter 25 | private final UserRepository userRepository; 26 | 27 | public ChatService(ChatClient.Builder chatClientBuilder, MessageRepository messageRepository, ChatRepository chatRepository, UserRepository userRepository) { 28 | this.chatClient = chatClientBuilder.build(); 29 | this.messageRepository = messageRepository; 30 | this.chatRepository = chatRepository; 31 | this.userRepository = userRepository; 32 | } 33 | 34 | public Message processCustomerMessage(String customerId, String question) { 35 | 36 | // find or create chat 37 | 38 | Chat chat = chatRepository.findByCustomerId(customerId).stream() 39 | .filter(Chat::isActive) 40 | .findFirst() 41 | .orElseGet(() -> { 42 | Chat newChat = new Chat(); 43 | newChat.setId(UUID.randomUUID().toString()); 44 | newChat.setCustomerId(customerId); 45 | newChat.setMessageIds(new ArrayList<>()); 46 | return chatRepository.save(newChat); 47 | }); 48 | 49 | // save customer message 50 | Message customerMessage = new Message(); 51 | customerMessage.setId(UUID.randomUUID().toString()); 52 | customerMessage.setChatId(chat.getId()); 53 | customerMessage.setSenderId(customerId); 54 | customerMessage.setSenderRole("CUSTOMER"); 55 | customerMessage.setContent(question); 56 | customerMessage.setTimeStamp(LocalDateTime.now()); 57 | messageRepository.save(customerMessage); 58 | chat.getMessageIds().add(customerMessage.getId()); 59 | chatRepository.save(chat); 60 | 61 | // Generate Ai Response 62 | String prompt = "You are a customer support chatbot. Provide a concise, helpful response to: " + question; 63 | String aiResponse = chatClient.prompt() 64 | .user(prompt) 65 | .call() 66 | .content(); 67 | double confidence = estimateConfidence(aiResponse); 68 | 69 | Message aiMessage = new Message(); 70 | aiMessage.setId(UUID.randomUUID().toString()); 71 | aiMessage.setChatId(chat.getId()); 72 | aiMessage.setSenderRole("AI"); 73 | aiMessage.setContent(aiResponse); 74 | aiMessage.setTimeStamp(LocalDateTime.now()); 75 | aiMessage.setConfidence(confidence); 76 | aiMessage.setRequireHandOff(confidence < 0.8); // Handoff if confidence <80% 77 | messageRepository.save(aiMessage); 78 | chatRepository.save(chat); 79 | 80 | return aiMessage; 81 | } 82 | 83 | public Message processAgentMessage(String chatId, String agentId, String content){ 84 | Message agentMessage = new Message(); 85 | agentMessage.setId(UUID.randomUUID().toString()); 86 | agentMessage.setChatId(chatId); 87 | agentMessage.setSenderId(agentId); 88 | agentMessage.setSenderRole("AGENT"); 89 | agentMessage.setContent(content); 90 | agentMessage.setTimeStamp(LocalDateTime.now()); 91 | messageRepository.save(agentMessage); 92 | 93 | Chat chat = chatRepository.findById(chatId).orElseThrow(); 94 | chat.setAgentId(agentId); 95 | chat.getMessageIds().add(agentMessage.getId()); 96 | chatRepository.save(chat); 97 | 98 | return agentMessage; 99 | } 100 | 101 | public List getChatHistory(String chatId) { 102 | return messageRepository.findByChatId(chatId); 103 | } 104 | 105 | public List getAgentChats(String agentId) { 106 | 107 | return chatRepository.findByAgentId(agentId); 108 | } 109 | 110 | public List getAllChats() { 111 | return chatRepository.findAll(); 112 | } 113 | 114 | private double estimateConfidence(String response){ 115 | 116 | return response.length() > 50 ? 0.9 : 0.7; 117 | } 118 | 119 | public User saveUser(User user){ 120 | return userRepository.save(user); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | <# : batch portion 2 | @REM ---------------------------------------------------------------------------- 3 | @REM Licensed to the Apache Software Foundation (ASF) under one 4 | @REM or more contributor license agreements. See the NOTICE file 5 | @REM distributed with this work for additional information 6 | @REM regarding copyright ownership. The ASF licenses this file 7 | @REM to you under the Apache License, Version 2.0 (the 8 | @REM "License"); you may not use this file except in compliance 9 | @REM with the License. You may obtain a copy of the License at 10 | @REM 11 | @REM http://www.apache.org/licenses/LICENSE-2.0 12 | @REM 13 | @REM Unless required by applicable law or agreed to in writing, 14 | @REM software distributed under the License is distributed on an 15 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | @REM KIND, either express or implied. See the License for the 17 | @REM specific language governing permissions and limitations 18 | @REM under the License. 19 | @REM ---------------------------------------------------------------------------- 20 | 21 | @REM ---------------------------------------------------------------------------- 22 | @REM Apache Maven Wrapper startup batch script, version 3.3.2 23 | @REM 24 | @REM Optional ENV vars 25 | @REM MVNW_REPOURL - repo url base for downloading maven distribution 26 | @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 27 | @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output 28 | @REM ---------------------------------------------------------------------------- 29 | 30 | @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) 31 | @SET __MVNW_CMD__= 32 | @SET __MVNW_ERROR__= 33 | @SET __MVNW_PSMODULEP_SAVE=%PSModulePath% 34 | @SET PSModulePath= 35 | @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( 36 | IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) 37 | ) 38 | @SET PSModulePath=%__MVNW_PSMODULEP_SAVE% 39 | @SET __MVNW_PSMODULEP_SAVE= 40 | @SET __MVNW_ARG0_NAME__= 41 | @SET MVNW_USERNAME= 42 | @SET MVNW_PASSWORD= 43 | @IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) 44 | @echo Cannot start maven from wrapper >&2 && exit /b 1 45 | @GOTO :EOF 46 | : end batch / begin powershell #> 47 | 48 | $ErrorActionPreference = "Stop" 49 | if ($env:MVNW_VERBOSE -eq "true") { 50 | $VerbosePreference = "Continue" 51 | } 52 | 53 | # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties 54 | $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl 55 | if (!$distributionUrl) { 56 | Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" 57 | } 58 | 59 | switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { 60 | "maven-mvnd-*" { 61 | $USE_MVND = $true 62 | $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" 63 | $MVN_CMD = "mvnd.cmd" 64 | break 65 | } 66 | default { 67 | $USE_MVND = $false 68 | $MVN_CMD = $script -replace '^mvnw','mvn' 69 | break 70 | } 71 | } 72 | 73 | # apply MVNW_REPOURL and calculate MAVEN_HOME 74 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 75 | if ($env:MVNW_REPOURL) { 76 | $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } 77 | $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" 78 | } 79 | $distributionUrlName = $distributionUrl -replace '^.*/','' 80 | $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' 81 | $MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" 82 | if ($env:MAVEN_USER_HOME) { 83 | $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" 84 | } 85 | $MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' 86 | $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" 87 | 88 | if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { 89 | Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" 90 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 91 | exit $? 92 | } 93 | 94 | if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { 95 | Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" 96 | } 97 | 98 | # prepare tmp dir 99 | $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile 100 | $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" 101 | $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null 102 | trap { 103 | if ($TMP_DOWNLOAD_DIR.Exists) { 104 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 105 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 106 | } 107 | } 108 | 109 | New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null 110 | 111 | # Download and Install Apache Maven 112 | Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 113 | Write-Verbose "Downloading from: $distributionUrl" 114 | Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 115 | 116 | $webclient = New-Object System.Net.WebClient 117 | if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { 118 | $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) 119 | } 120 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 121 | $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null 122 | 123 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 124 | $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum 125 | if ($distributionSha256Sum) { 126 | if ($USE_MVND) { 127 | Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." 128 | } 129 | Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash 130 | if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { 131 | Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." 132 | } 133 | } 134 | 135 | # unzip and move 136 | Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null 137 | Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null 138 | try { 139 | Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null 140 | } catch { 141 | if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { 142 | Write-Error "fail to move MAVEN_HOME" 143 | } 144 | } finally { 145 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 146 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 147 | } 148 | 149 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 150 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Optional ENV vars 25 | # ----------------- 26 | # JAVA_HOME - location of a JDK home dir, required when download maven via java source 27 | # MVNW_REPOURL - repo url base for downloading maven distribution 28 | # MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 29 | # MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output 30 | # ---------------------------------------------------------------------------- 31 | 32 | set -euf 33 | [ "${MVNW_VERBOSE-}" != debug ] || set -x 34 | 35 | # OS specific support. 36 | native_path() { printf %s\\n "$1"; } 37 | case "$(uname)" in 38 | CYGWIN* | MINGW*) 39 | [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" 40 | native_path() { cygpath --path --windows "$1"; } 41 | ;; 42 | esac 43 | 44 | # set JAVACMD and JAVACCMD 45 | set_java_home() { 46 | # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched 47 | if [ -n "${JAVA_HOME-}" ]; then 48 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 49 | # IBM's JDK on AIX uses strange locations for the executables 50 | JAVACMD="$JAVA_HOME/jre/sh/java" 51 | JAVACCMD="$JAVA_HOME/jre/sh/javac" 52 | else 53 | JAVACMD="$JAVA_HOME/bin/java" 54 | JAVACCMD="$JAVA_HOME/bin/javac" 55 | 56 | if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then 57 | echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 58 | echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 59 | return 1 60 | fi 61 | fi 62 | else 63 | JAVACMD="$( 64 | 'set' +e 65 | 'unset' -f command 2>/dev/null 66 | 'command' -v java 67 | )" || : 68 | JAVACCMD="$( 69 | 'set' +e 70 | 'unset' -f command 2>/dev/null 71 | 'command' -v javac 72 | )" || : 73 | 74 | if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then 75 | echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 76 | return 1 77 | fi 78 | fi 79 | } 80 | 81 | # hash string like Java String::hashCode 82 | hash_string() { 83 | str="${1:-}" h=0 84 | while [ -n "$str" ]; do 85 | char="${str%"${str#?}"}" 86 | h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) 87 | str="${str#?}" 88 | done 89 | printf %x\\n $h 90 | } 91 | 92 | verbose() { :; } 93 | [ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } 94 | 95 | die() { 96 | printf %s\\n "$1" >&2 97 | exit 1 98 | } 99 | 100 | trim() { 101 | # MWRAPPER-139: 102 | # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. 103 | # Needed for removing poorly interpreted newline sequences when running in more 104 | # exotic environments such as mingw bash on Windows. 105 | printf "%s" "${1}" | tr -d '[:space:]' 106 | } 107 | 108 | # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties 109 | while IFS="=" read -r key value; do 110 | case "${key-}" in 111 | distributionUrl) distributionUrl=$(trim "${value-}") ;; 112 | distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; 113 | esac 114 | done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" 115 | [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" 116 | 117 | case "${distributionUrl##*/}" in 118 | maven-mvnd-*bin.*) 119 | MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ 120 | case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in 121 | *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; 122 | :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; 123 | :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; 124 | :Linux*x86_64*) distributionPlatform=linux-amd64 ;; 125 | *) 126 | echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 127 | distributionPlatform=linux-amd64 128 | ;; 129 | esac 130 | distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" 131 | ;; 132 | maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; 133 | *) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; 134 | esac 135 | 136 | # apply MVNW_REPOURL and calculate MAVEN_HOME 137 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 138 | [ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" 139 | distributionUrlName="${distributionUrl##*/}" 140 | distributionUrlNameMain="${distributionUrlName%.*}" 141 | distributionUrlNameMain="${distributionUrlNameMain%-bin}" 142 | MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" 143 | MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" 144 | 145 | exec_maven() { 146 | unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : 147 | exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" 148 | } 149 | 150 | if [ -d "$MAVEN_HOME" ]; then 151 | verbose "found existing MAVEN_HOME at $MAVEN_HOME" 152 | exec_maven "$@" 153 | fi 154 | 155 | case "${distributionUrl-}" in 156 | *?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; 157 | *) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; 158 | esac 159 | 160 | # prepare tmp dir 161 | if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then 162 | clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } 163 | trap clean HUP INT TERM EXIT 164 | else 165 | die "cannot create temp dir" 166 | fi 167 | 168 | mkdir -p -- "${MAVEN_HOME%/*}" 169 | 170 | # Download and Install Apache Maven 171 | verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 172 | verbose "Downloading from: $distributionUrl" 173 | verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 174 | 175 | # select .zip or .tar.gz 176 | if ! command -v unzip >/dev/null; then 177 | distributionUrl="${distributionUrl%.zip}.tar.gz" 178 | distributionUrlName="${distributionUrl##*/}" 179 | fi 180 | 181 | # verbose opt 182 | __MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' 183 | [ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v 184 | 185 | # normalize http auth 186 | case "${MVNW_PASSWORD:+has-password}" in 187 | '') MVNW_USERNAME='' MVNW_PASSWORD='' ;; 188 | has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; 189 | esac 190 | 191 | if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then 192 | verbose "Found wget ... using wget" 193 | wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" 194 | elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then 195 | verbose "Found curl ... using curl" 196 | curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" 197 | elif set_java_home; then 198 | verbose "Falling back to use Java to download" 199 | javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" 200 | targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" 201 | cat >"$javaSource" <<-END 202 | public class Downloader extends java.net.Authenticator 203 | { 204 | protected java.net.PasswordAuthentication getPasswordAuthentication() 205 | { 206 | return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); 207 | } 208 | public static void main( String[] args ) throws Exception 209 | { 210 | setDefault( new Downloader() ); 211 | java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); 212 | } 213 | } 214 | END 215 | # For Cygwin/MinGW, switch paths to Windows format before running javac and java 216 | verbose " - Compiling Downloader.java ..." 217 | "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" 218 | verbose " - Running Downloader.java ..." 219 | "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" 220 | fi 221 | 222 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 223 | if [ -n "${distributionSha256Sum-}" ]; then 224 | distributionSha256Result=false 225 | if [ "$MVN_CMD" = mvnd.sh ]; then 226 | echo "Checksum validation is not supported for maven-mvnd." >&2 227 | echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 228 | exit 1 229 | elif command -v sha256sum >/dev/null; then 230 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then 231 | distributionSha256Result=true 232 | fi 233 | elif command -v shasum >/dev/null; then 234 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then 235 | distributionSha256Result=true 236 | fi 237 | else 238 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 239 | echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 240 | exit 1 241 | fi 242 | if [ $distributionSha256Result = false ]; then 243 | echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 244 | echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 245 | exit 1 246 | fi 247 | fi 248 | 249 | # unzip and move 250 | if command -v unzip >/dev/null; then 251 | unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" 252 | else 253 | tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" 254 | fi 255 | printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" 256 | mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" 257 | 258 | clean || : 259 | exec_maven "$@" 260 | --------------------------------------------------------------------------------