├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── README.md ├── exercises ├── week-1-e-1.md ├── week2 │ ├── fibbunacci-prompt.md │ ├── mini-project.md │ └── refactoring.md ├── week3 │ ├── Hands-on Exercise: AI Test Generation.md │ └── mini-project-2.md ├── week4 │ ├── diagrams.svg │ ├── hands-on-exercise.md │ ├── mini-project-part-2.md │ ├── mini-project.md │ └── user-profile-microservice.js └── week5 │ └── mini-project.md ├── faq └── faq.md ├── projects ├── final │ ├── docker-compose-example.md │ ├── ideas.md │ ├── requirements.md │ └── testing-requirements.md ├── product-catalog-api │ ├── .github │ │ └── workflows │ │ │ └── test.yml │ ├── .gitignore │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── app.js │ │ ├── data │ │ │ └── products.js │ │ ├── middleware │ │ │ └── auth-middleware.js │ │ ├── routes │ │ │ └── product-routes.js │ │ ├── server.js │ │ └── services │ │ │ └── product-service.js │ └── tests │ │ ├── integration │ │ └── product-routes.test.js │ │ └── unit │ │ └── product-service.test.js └── projects&assignments.md ├── resources ├── aditional.md ├── development-env-setup.md ├── github-reposotiry-setup.md └── week2 │ └── sample_data.csv ├── slides ├── 2.AI-Assisted Coding.pdf └── Week1.pdf └── syllabus.md /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # 📌 Code of Conduct 2 | 3 | To ensure a respectful and collaborative learning environment: 4 | - Be respectful to all peers. 5 | - Give constructive feedback during code reviews. 6 | - Do not plagiarize assignments or misuse AI tools. 7 | 8 | Failure to follow these guidelines may result in penalties or removal from the course discussions. 9 | 10 | --- -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # 📌 Contributing to Advanced Programming Repository 2 | 3 | We welcome contributions! You can contribute by: 4 | - Suggesting improvements in course materials. 5 | - Adding helpful resources. 6 | - Fixing typos or errors. 7 | 8 | ## 📍 How to Contribute 9 | 1. **Fork this repository** to your GitHub account. 10 | 2. **Make changes** to the relevant files. 11 | 3. **Create a Pull Request** with a description of your changes. 12 | 13 | --- -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📌 Advanced Programming - 2025 2 | 3 | Welcome to the **Advanced Programming (2025 Edition)** course repository! 🚀 This repository contains **syllabus, project specifications, coding exercises, and other course materials**. 4 | 5 | ## 📜 Course Overview 6 | This course focuses on **modern software engineering practices**, covering: 7 | - **AI-assisted software development** 8 | - **Microservices & API-first design** 9 | - **DevOps & CI/CD pipelines** 10 | - **Secure coding & DevSecOps principles** 11 | 12 | Students will work on **mini-projects** and a **final project**, integrating these concepts into real-world applications. 13 | 14 | ## 📂 Repository Structure 15 | ``` 16 | 📁 advanced-programming-2025 17 | │── 📜 README.md # Course introduction and repo guide 18 | │── 📜 syllabus.md # Full course syllabus 19 | │── 📁 slides/ # Weekly lecture slides (PDF/Markdown) 20 | │── 📁 projects/ # Project specifications & guidelines 21 | │── 📁 exercises/ # Hands-on coding exercises with solutions 22 | │── 📁 resources/ # Links to tools, guides, and reference materials 23 | │── 📁 faq/ # Frequently asked questions 24 | │── 📜 CONTRIBUTING.md # How students can suggest improvements 25 | │── 📜 CODE_OF_CONDUCT.md # Guidelines for respectful collaboration 26 | ``` 27 | 28 | ## 📘 Getting Started 29 | ### 1️⃣ **Clone the Repository** 30 | ```sh 31 | git clone https://github.com/agonb0/advanced-programming-2025.git 32 | cd advanced-programming-2025 33 | ``` 34 | 35 | ### 2️⃣ **Join the Course GitHub Organization** 36 | If required, students will be added as members to a private **GitHub classroom or organization** for submitting assignments. 37 | 38 | ### 3️⃣ **Setup Development Environment** 39 | Ensure you have the following installed: 40 | - [VS Code](https://code.visualstudio.com/) 41 | - [Git](https://git-scm.com/) 42 | - [Docker](https://www.docker.com/) 43 | - [Node.js](https://nodejs.org/) or [Python](https://www.python.org/) (as per project requirements) 44 | 45 | --- 46 | 47 | # 📜 Syllabus 48 | 49 | ## 📍 **Week 1 – Introduction & AI in Software Development** 50 | - Course structure, grading, and tools overview 51 | - AI-assisted coding demo (GitHub Copilot, ChatGPT) 52 | - 📌 **Hands-on:** Setup development environment & try AI-powered coding 53 | 54 | ## 📍 **Week 2 – AI-Assisted Coding** 55 | - AI pair programming & code generation 56 | - 📌 **Hands-on:** Implement and refactor code with AI 57 | 58 | *(Full syllabus available in `syllabus.md`)* 59 | 60 | --- 61 | 62 | # 🚀 Projects 63 | ## **Mini-Projects & Final Project** 64 | 📌 **Mini-Project 1** – AI-enhanced Code Refactoring 65 | 📌 **Mini-Project 2** – Microservice API Development 66 | 📌 **Mini-Project 3** – Secure DevOps Pipeline 67 | 📌 **Final Project** – Real-world application integrating AI, DevOps, and Security 68 | 69 | 🔹 Full project details are in `projects/` 70 | 71 | --- 72 | 73 | # 📌 Assignments & Submission 74 | - Assignments should be **submitted via GitHub** using **Pull Requests (PRs)**. 75 | - Each assignment has a dedicated folder inside `exercises/` with instructions. 76 | 77 | --- 78 | 79 | # 🔗 Resources 80 | - **[GitHub Copilot Docs](https://docs.github.com/en/copilot/)** 81 | - **[OWASP Security Guide](https://owasp.org/)** 82 | - **[Docker & CI/CD Tutorials](https://docs.docker.com/get-started/)** 83 | - *(More resources available in `resources/`)* 84 | 85 | --- 86 | 87 | # 📝 Code of Conduct 88 | This course follows **professional conduct guidelines** to maintain a respectful learning environment. Read `CODE_OF_CONDUCT.md` for details. 89 | 90 | --- 91 | 92 | # 🎤 Questions? 93 | - **Check `faq/` for common questions.** 94 | - **Ask in GitHub Discussions or Issues!** 🚀 95 | 96 | Happy coding! 🎯 97 | -------------------------------------------------------------------------------- /exercises/week-1-e-1.md: -------------------------------------------------------------------------------- 1 | # Week 1 Exercise: AI-Assisted "Hello World" 2 | 3 | ## Overview 4 | This introductory exercise will help you become familiar with using AI tools for coding assistance. You'll implement a simple program in a language of your choice, but with a twist - you'll use AI to help write parts of it. 5 | 6 | ## Objectives 7 | - Set up and test your development environment 8 | - Experience AI-assisted coding with GitHub Copilot or ChatGPT 9 | - Write a simple program with AI assistance 10 | - Document your experience with AI tools 11 | 12 | ## Exercise Instructions 13 | 14 | ### Part 1: Choose a Programming Language 15 | - Select a programming language you're comfortable with (Python, JavaScript, Java, etc.) 16 | - **Challenge option**: Choose a language you're not familiar with! 17 | 18 | ### Part 2: Create a New Project 19 | 1. Open VS Code 20 | 2. Create a new folder for this exercise 21 | 3. Initialize a Git repository in this folder: 22 | ```bash 23 | git init 24 | ``` 25 | 4. Create a new file for your program (e.g., `hello_world.py`, `hello_world.js`, etc.) 26 | 27 | ### Part 3: Use AI Assistance to Write Your Program 28 | You'll create a "Hello World" program with these requirements: 29 | - Print "Hello, World!" to the console 30 | - Ask for the user's name and store it 31 | - Greet the user by name 32 | - Print the current date and time 33 | - Have at least one function or method 34 | - Include proper error handling (e.g., for input) 35 | - Add appropriate comments 36 | 37 | **Using GitHub Copilot:** 38 | 1. Enable GitHub Copilot in VS Code 39 | 2. Start by writing comments describing what you want to do 40 | 3. Let Copilot suggest code implementations 41 | 4. Accept, modify, or reject suggestions as needed 42 | 43 | **Using ChatGPT (alternative):** 44 | 1. Go to chat.openai.com 45 | 2. Ask ChatGPT to help you write a program with the requirements listed above 46 | 3. Copy and refine the code in your file 47 | 48 | ### Part 4: Test Your Program 49 | 1. Run your program to ensure it works as expected 50 | 2. Fix any issues that arise 51 | 52 | ### Part 5: Document Your Experience 53 | Create a `README.md` file in your project folder and write about: 54 | 1. What language you chose and why 55 | 2. How you used the AI tool (what prompts or methods worked best) 56 | 3. What suggestions from the AI were helpful 57 | 4. What suggestions you had to modify or correct 58 | 5. What you learned about AI-assisted coding from this exercise 59 | 60 | Sample README template: 61 | ```markdown 62 | # AI-Assisted Hello World 63 | 64 | ## Language Choice 65 | I chose [language] because [reason]. 66 | 67 | ## AI Tool Used 68 | I used [GitHub Copilot/ChatGPT] to assist with coding. 69 | 70 | ## The AI Experience 71 | Here's how I used the AI tool and what I discovered: 72 | 73 | - **What worked well:** 74 | - [Example 1] 75 | - [Example 2] 76 | 77 | - **What didn't work well:** 78 | - [Example 1] 79 | - [Example 2] 80 | 81 | - **Modifications I made:** 82 | - [Example 1] 83 | - [Example 2] 84 | 85 | ## What I Learned 86 | [2-3 paragraphs about your experience and what you learned] 87 | 88 | ## Screenshot 89 | [Include a screenshot of your code and program output] 90 | ``` 91 | 92 | ### Part 6: Commit Your Work 93 | 1. Add your files to Git: 94 | ```bash 95 | git add . 96 | ``` 97 | 2. Commit your changes: 98 | ```bash 99 | git commit -m "Complete Week 1 AI-assisted Hello World exercise" 100 | ``` 101 | 3. If we've set up a class repository, push your work following the instructor's directions 102 | 103 | ## Submission 104 | - Upload your code file and README.md to the course submission system 105 | - Be prepared to share your experience briefly in the next class -------------------------------------------------------------------------------- /exercises/week2/fibbunacci-prompt.md: -------------------------------------------------------------------------------- 1 | # Function to calculate the nth Fibonacci number 2 | # # The Fibonacci sequence starts with 0 and 1 3 | # # Each subsequent number is the sum of the two preceding ones 4 | # # Example: 0, 1, 1, 2, 3, 5, 8, 13, ... 5 | # # Parameter: n (int) - the position in the sequence (0-indexed) 6 | # # Returns: the nth Fibonacci number 7 | 8 | -------------------------------------------------------------------------------- /exercises/week2/mini-project.md: -------------------------------------------------------------------------------- 1 | # AI-Assisted Data Analysis Tool Mini-Project 2 | 3 | ## Objective 4 | Create a command-line tool that analyzes CSV data using AI assistance throughout the development process. 5 | 6 | ## Requirements 7 | Your tool should: 8 | 1. Read CSV files with numeric data 9 | 2. Calculate basic statistics (mean, median, mode, standard deviation) 10 | 3. Generate a simple text-based histogram 11 | 4. Find correlations between columns 12 | 5. Identify outliers 13 | 14 | ## Implementation Details 15 | - Use Python for this project 16 | - Include proper error handling for invalid files or data 17 | - The tool should be usable from the command line 18 | - Document your code thoroughly 19 | 20 | ## Sample Data 21 | Use the provided `sample_data.csv` file for testing, which contains: 22 | - id: Record identifier 23 | - temperature: Temperature readings 24 | - humidity: Humidity percentage 25 | - pressure: Atmospheric pressure 26 | - wind_speed: Wind speed measurements 27 | 28 | ## Deliverables 29 | 1. Source code files 30 | 2. Brief documentation of: 31 | - How to use the tool 32 | - Which parts were AI-assisted 33 | - Challenges encountered and how you solved them 34 | 35 | ## Example Usage 36 | Your tool should support commands like: 37 | - `python data_analysis.py sample_data.csv stats temperature` 38 | - `python data_analysis.py sample_data.csv histogram humidity 10` 39 | - `python data_analysis.py sample_data.csv correlation temperature humidity` 40 | - `python data_analysis.py sample_data.csv outliers wind_speed 2.0` 41 | 42 | ## Development Process 43 | 1. Start by planning your approach with your partner 44 | 2. Use comments to guide GitHub Copilot in generating code 45 | 3. Critically evaluate and modify AI suggestions 46 | 4. Test your implementation with the provided sample data 47 | 5. Document which parts were AI-assisted and which parts you modified 48 | 49 | ## Time Allocation (40 minutes total) 50 | - 5 minutes: Planning and design 51 | - 25 minutes: Implementation with AI assistance 52 | - 10 minutes: Testing and documenting 53 | 54 | ## Grading Criteria 55 | - Functionality (working implementation of required features) 56 | - Code quality (readability, organization, error handling) 57 | - Effective use of AI assistance 58 | - Documentation quality -------------------------------------------------------------------------------- /exercises/week2/refactoring.md: -------------------------------------------------------------------------------- 1 | def f(l, t): 2 | r = [] 3 | for i in range(len(l)): 4 | if l[i]["t"] == t: 5 | r.append(l[i]) 6 | return r 7 | 8 | # Usage example: 9 | items = [ 10 | {"id": 1, "t": "book", "price": 20}, 11 | {"id": 2, "t": "food", "price": 10}, 12 | {"id": 3, "t": "book", "price": 15}, 13 | {"id": 4, "t": "food", "price": 5} 14 | ] 15 | books = f(items, "book") -------------------------------------------------------------------------------- /exercises/week3/Hands-on Exercise: AI Test Generation.md: -------------------------------------------------------------------------------- 1 | # Advanced Programming - Week 3 2 | ## Hands-on Exercise: AI Test Generation 3 | 4 | ### Overview 5 | In this exercise, you will use AI tools to generate and refine unit tests for a given function. This will help you understand how AI can assist in testing and how to ensure the quality of AI-generated tests. 6 | 7 | ### Learning Objectives 8 | - Generate unit tests using AI tools 9 | - Evaluate the quality and coverage of AI-generated tests 10 | - Refine and improve tests based on edge cases 11 | - Implement a complete test suite for a function 12 | 13 | ### Prerequisites 14 | - A GitHub account 15 | - Access to GitHub Copilot, ChatGPT, or another AI assistant 16 | - Basic knowledge of unit testing in JavaScript or Python 17 | 18 | ### Provided Code 19 | Below is a function called `validateUserData` that performs validation on user registration data. This function has multiple edge cases and conditions that need to be tested. 20 | 21 | #### JavaScript Version (Jest) 22 | ```javascript 23 | /** 24 | * Validates user registration data 25 | * @param {Object} userData - The user data to validate 26 | * @param {string} userData.username - The username (required, 3-20 chars, alphanumeric) 27 | * @param {string} userData.email - The email address (required, valid format) 28 | * @param {string} userData.password - The password (required, min 8 chars, at least 1 number and 1 special char) 29 | * @param {number} [userData.age] - The user's age (optional, must be 18+ if provided) 30 | * @param {string} [userData.referralCode] - Referral code (optional, must be exactly 8 chars if provided) 31 | * @returns {Object} - Object with isValid flag and any error messages 32 | */ 33 | function validateUserData(userData) { 34 | const result = { 35 | isValid: true, 36 | errors: {} 37 | }; 38 | 39 | // Check if userData exists and is an object 40 | if (!userData || typeof userData !== 'object') { 41 | result.isValid = false; 42 | result.errors.global = "Invalid user data format"; 43 | return result; 44 | } 45 | 46 | // Validate username 47 | if (!userData.username) { 48 | result.isValid = false; 49 | result.errors.username = "Username is required"; 50 | } else if (userData.username.length < 3 || userData.username.length > 20) { 51 | result.isValid = false; 52 | result.errors.username = "Username must be between 3 and 20 characters"; 53 | } else if (!/^[a-zA-Z0-9_]+$/.test(userData.username)) { 54 | result.isValid = false; 55 | result.errors.username = "Username can only contain letters, numbers, and underscores"; 56 | } 57 | 58 | // Validate email 59 | if (!userData.email) { 60 | result.isValid = false; 61 | result.errors.email = "Email is required"; 62 | } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userData.email)) { 63 | result.isValid = false; 64 | result.errors.email = "Invalid email format"; 65 | } 66 | 67 | // Validate password 68 | if (!userData.password) { 69 | result.isValid = false; 70 | result.errors.password = "Password is required"; 71 | } else if (userData.password.length < 8) { 72 | result.isValid = false; 73 | result.errors.password = "Password must be at least 8 characters long"; 74 | } else if (!/\d/.test(userData.password)) { 75 | result.isValid = false; 76 | result.errors.password = "Password must contain at least one number"; 77 | } else if (!/[!@#$%^&*(),.?":{}|<>]/.test(userData.password)) { 78 | result.isValid = false; 79 | result.errors.password = "Password must contain at least one special character"; 80 | } 81 | 82 | // Validate age (optional) 83 | if (userData.age !== undefined) { 84 | if (typeof userData.age !== 'number') { 85 | result.isValid = false; 86 | result.errors.age = "Age must be a number"; 87 | } else if (userData.age < 18) { 88 | result.isValid = false; 89 | result.errors.age = "User must be at least 18 years old"; 90 | } 91 | } 92 | 93 | // Validate referral code (optional) 94 | if (userData.referralCode !== undefined) { 95 | if (typeof userData.referralCode !== 'string') { 96 | result.isValid = false; 97 | result.errors.referralCode = "Referral code must be a string"; 98 | } else if (userData.referralCode.length !== 8) { 99 | result.isValid = false; 100 | result.errors.referralCode = "Referral code must be exactly 8 characters"; 101 | } 102 | } 103 | 104 | return result; 105 | } 106 | 107 | module.exports = validateUserData; 108 | ``` 109 | 110 | #### Python Version (pytest) 111 | ```python 112 | def validate_user_data(user_data): 113 | """ 114 | Validates user registration data 115 | 116 | Args: 117 | user_data (dict): The user data to validate with the following keys: 118 | - username (str): Required, 3-20 chars, alphanumeric 119 | - email (str): Required, valid format 120 | - password (str): Required, min 8 chars, at least 1 number and 1 special char 121 | - age (int, optional): The user's age, must be 18+ if provided 122 | - referral_code (str, optional): Must be exactly 8 chars if provided 123 | 124 | Returns: 125 | dict: Object with is_valid flag and any error messages 126 | """ 127 | import re 128 | 129 | result = { 130 | "is_valid": True, 131 | "errors": {} 132 | } 133 | 134 | # Check if user_data exists and is a dictionary 135 | if not user_data or not isinstance(user_data, dict): 136 | result["is_valid"] = False 137 | result["errors"]["global"] = "Invalid user data format" 138 | return result 139 | 140 | # Validate username 141 | if "username" not in user_data or not user_data["username"]: 142 | result["is_valid"] = False 143 | result["errors"]["username"] = "Username is required" 144 | elif len(user_data["username"]) < 3 or len(user_data["username"]) > 20: 145 | result["is_valid"] = False 146 | result["errors"]["username"] = "Username must be between 3 and 20 characters" 147 | elif not re.match(r'^[a-zA-Z0-9_]+$', user_data["username"]): 148 | result["is_valid"] = False 149 | result["errors"]["username"] = "Username can only contain letters, numbers, and underscores" 150 | 151 | # Validate email 152 | if "email" not in user_data or not user_data["email"]: 153 | result["is_valid"] = False 154 | result["errors"]["email"] = "Email is required" 155 | elif not re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', user_data["email"]): 156 | result["is_valid"] = False 157 | result["errors"]["email"] = "Invalid email format" 158 | 159 | # Validate password 160 | if "password" not in user_data or not user_data["password"]: 161 | result["is_valid"] = False 162 | result["errors"]["password"] = "Password is required" 163 | elif len(user_data["password"]) < 8: 164 | result["is_valid"] = False 165 | result["errors"]["password"] = "Password must be at least 8 characters long" 166 | elif not re.search(r'\d', user_data["password"]): 167 | result["is_valid"] = False 168 | result["errors"]["password"] = "Password must contain at least one number" 169 | elif not re.search(r'[!@#$%^&*(),.?":{}|<>]', user_data["password"]): 170 | result["is_valid"] = False 171 | result["errors"]["password"] = "Password must contain at least one special character" 172 | 173 | # Validate age (optional) 174 | if "age" in user_data: 175 | if not isinstance(user_data["age"], int): 176 | result["is_valid"] = False 177 | result["errors"]["age"] = "Age must be a number" 178 | elif user_data["age"] < 18: 179 | result["is_valid"] = False 180 | result["errors"]["age"] = "User must be at least 18 years old" 181 | 182 | # Validate referral code (optional) 183 | if "referral_code" in user_data: 184 | if not isinstance(user_data["referral_code"], str): 185 | result["is_valid"] = False 186 | result["errors"]["referral_code"] = "Referral code must be a string" 187 | elif len(user_data["referral_code"]) != 8: 188 | result["is_valid"] = False 189 | result["errors"]["referral_code"] = "Referral code must be exactly 8 characters" 190 | 191 | return result 192 | ``` 193 | 194 | ### Exercise Tasks 195 | 196 | #### Part 1: Initial Test Generation 197 | 1. Choose either the JavaScript or Python version of the function. 198 | 2. Use GitHub Copilot, ChatGPT, or another AI assistant to generate a complete set of unit tests for the function. 199 | 3. If using ChatGPT or similar, provide a prompt like: "Generate a comprehensive set of unit tests for the following function..." 200 | 4. Copy the AI-generated tests to a new file (`validateUserData.test.js` for JavaScript or `test_validate_user_data.py` for Python). 201 | 202 | #### Part 2: Test Evaluation 203 | Analyze the AI-generated tests and answer the following questions: 204 | 1. Does the test suite cover all parameters and conditions in the function? 205 | 2. Are there any edge cases that are not covered? 206 | 3. Are the tests well-structured and follow best practices? 207 | 4. How readable and maintainable are the tests? 208 | 5. Note any improvements that could be made to the tests. 209 | 210 | #### Part 3: Test Refinement 211 | 1. Refine the AI-generated tests to address any issues you identified in Part 2. 212 | 2. Add any missing test cases, especially for edge cases. 213 | 3. Improve the structure and readability of the tests as needed. 214 | 4. Ensure each test has a clear purpose and descriptive name. 215 | 216 | #### Part 4: Running the Tests 217 | 1. Set up a testing environment for your chosen language (Jest for JavaScript or pytest for Python). 218 | 2. Run your refined tests against the provided function. 219 | 3. Fix any issues that arise when running the tests. 220 | 4. Record the test results and any insights gained. 221 | 222 | #### Part 5: Reflection 223 | Write a brief reflection (200-300 words) addressing the following points: 224 | 1. How effective was the AI at generating tests? What did it do well and what did it miss? 225 | 2. What strategies did you use to improve the AI-generated tests? 226 | 3. How would you use AI-assisted testing in real-world development? 227 | 4. What are the limitations and potential risks of relying on AI for test generation? 228 | 229 | ### Submission Requirements 230 | Submit a ZIP file containing: 231 | 1. Your refined test file (`validateUserData.test.js` or `test_validate_user_data.py`) 232 | 2. A text file with your answers to the evaluation questions (Part 2) 233 | 3. Your reflection document (Part 5) 234 | 4. A screenshot showing your test results 235 | 236 | ### Evaluation Criteria 237 | - Comprehensive test coverage (40%) 238 | - Quality and clarity of tests (25%) 239 | - Identification of weaknesses in AI-generated tests (15%) 240 | - Thoughtfulness of reflection (15%) 241 | - Successfully running tests (5%) 242 | 243 | ### Resources 244 | - [Jest Documentation](https://jestjs.io/docs/getting-started) 245 | - [Pytest Documentation](https://docs.pytest.org/en/stable/) 246 | - [Best Practices for Unit Testing](https://github.com/mawrkus/js-unit-testing-guide) 247 | - [How to Write Good Test Cases](https://martinfowler.com/articles/practical-test-pyramid.html) -------------------------------------------------------------------------------- /exercises/week3/mini-project-2.md: -------------------------------------------------------------------------------- 1 | # Week 3 Assignment: AI-Assisted Testing 2 | 3 | ## Overview 4 | 5 | In this assignment, you will practice using AI tools to help generate tests for a simple REST API. You'll be working with a lightweight Product Catalog API that doesn't require any external database setup. 6 | 7 | ## Learning Objectives 8 | 9 | - Use AI tools to generate comprehensive test suites 10 | - Understand the strengths and limitations of AI-assisted testing 11 | - Apply best practices for unit and integration testing 12 | - Implement GitHub Actions for continuous integration 13 | - Document testing strategies and AI prompting techniques 14 | 15 | ## Setup Instructions 16 | 17 | ### 1. Fork and Clone the Repository 18 | 19 | ```bash 20 | # Fork the repository first on GitHub, then clone your fork 21 | git clone https://github.com/YOUR-USERNAME/simple-product-api.git 22 | cd simple-product-api 23 | ``` 24 | 25 | ### 2. Install Dependencies 26 | 27 | ```bash 28 | npm install 29 | ``` 30 | 31 | ### 3. Start the Server 32 | 33 | ```bash 34 | npm start 35 | # or for development with auto-reload 36 | npm run dev 37 | ``` 38 | 39 | The server will run on http://localhost:3000. 40 | 41 | ### 4. Test the API 42 | 43 | You can test that the API is working correctly using these curl commands: 44 | 45 | **Health Check:** 46 | ```bash 47 | curl http://localhost:3000/health 48 | ``` 49 | 50 | **Get All Products:** 51 | ```bash 52 | curl -H "X-API-Key: test-api-key" http://localhost:3000/api/products 53 | ``` 54 | 55 | **Get Product by ID:** 56 | ```bash 57 | curl -H "X-API-Key: test-api-key" http://localhost:3000/api/products/1 58 | ``` 59 | 60 | **Filter Products:** 61 | ```bash 62 | curl -H "X-API-Key: test-api-key" "http://localhost:3000/api/products?category=electronics&inStock=true" 63 | ``` 64 | 65 | **Create a Product:** 66 | ```bash 67 | curl -X POST \ 68 | -H "Content-Type: application/json" \ 69 | -H "X-API-Key: test-api-key" \ 70 | -d '{"name":"Smart Watch","price":199.99,"category":"electronics","stockCount":15}' \ 71 | http://localhost:3000/api/products 72 | ``` 73 | 74 | **Update a Product:** 75 | ```bash 76 | curl -X PUT \ 77 | -H "Content-Type: application/json" \ 78 | -H "X-API-Key: test-api-key" \ 79 | -d '{"price":89.99,"stockCount":25}' \ 80 | http://localhost:3000/api/products/1 81 | ``` 82 | 83 | **Delete a Product:** 84 | ```bash 85 | curl -X DELETE \ 86 | -H "X-API-Key: test-api-key" \ 87 | http://localhost:3000/api/products/1 88 | ``` 89 | 90 | **Get All Categories:** 91 | ```bash 92 | curl -H "X-API-Key: test-api-key" http://localhost:3000/api/products/categories/all 93 | ``` 94 | 95 | ## Assignment Tasks 96 | 97 | 1. **Complete Unit Tests** (50%) 98 | - Examine the product service in `src/services/product-service.js` 99 | - Use AI tools (GitHub Copilot, ChatGPT) to help generate unit tests in `tests/unit/product-service.test.js` 100 | - Ensure you test all methods and important edge cases 101 | - Run tests with `npm run test:unit` 102 | 103 | 2. **Complete Integration Tests** (30%) 104 | - Create tests for all API endpoints in `tests/integration/product-routes.test.js` 105 | - Test successful responses and error cases 106 | - Test with various query parameters and filters 107 | - Run tests with `npm run test:integration` 108 | 109 | 3. **Set up GitHub Actions** (10%) 110 | - Review the existing GitHub Actions workflow in `.github/workflows/test.yml` 111 | - Make any necessary adjustments to ensure it runs your tests 112 | - Push your changes to GitHub and verify the workflow runs 113 | 114 | 4. **Documentation** (10%) 115 | - Create a file called `TESTING.md` documenting your approach: 116 | - What AI tools you used 117 | - Example prompts that worked well 118 | - Challenges you encountered 119 | - How you improved upon AI-generated tests 120 | - Screenshots of your test results 121 | 122 | ## Documentation Requirements 123 | 124 | Your `TESTING.md` file should include the following sections: 125 | 126 | ### 1. Testing Strategy 127 | Explain your overall approach to testing the API. 128 | 129 | ### 2. AI-Assisted Testing Process 130 | Describe how you used AI tools to generate tests. Include: 131 | - Which AI tools you used 132 | - Examples of effective prompts 133 | - Screenshots of AI-generated tests 134 | 135 | ### 3. Test Coverage Analysis 136 | Include information about your test coverage (run `npm run test:coverage`). 137 | 138 | ### 4. Challenges and Solutions 139 | Discuss any limitations you found with AI-generated tests and how you addressed them. 140 | 141 | ### 5. Learnings 142 | Reflect on what you learned about AI-assisted testing and best practices. 143 | 144 | ## Example AI Prompts to Try 145 | 146 | Here are some example prompts to get you started: 147 | 148 | - "Generate unit tests for the getAllProducts method in the ProductService class. Include tests for filtering by category, price range, and in-stock status." 149 | 150 | - "Write integration tests for the POST /api/products endpoint that creates a new product. Include tests for successful creation and various validation error cases." 151 | 152 | - "Help me improve test coverage for the updateProduct method. I need to test edge cases like updating a non-existent product and providing invalid updates." 153 | 154 | ## Evaluation Criteria 155 | 156 | Your assignment will be evaluated based on: 157 | 158 | - **Test Completeness** (30%): Coverage of functionality and edge cases 159 | - **Test Quality** (20%): Well-organized, readable, and maintainable tests 160 | - **AI Usage** (20%): Effective use of AI tools and prompt engineering 161 | - **Documentation** (15%): Clear explanation of your approach and AI usage 162 | - **Code Quality** (10%): Clean code following best practices 163 | - **CI Implementation** (5%): Working GitHub Actions workflow 164 | 165 | ## Submission Instructions 166 | 167 | 1. Push all your changes to your GitHub repository 168 | 2. Ensure your repository includes: 169 | - Completed unit tests 170 | - Completed integration tests 171 | - Documentation file (TESTING.md) 172 | - Working GitHub Actions workflow 173 | 174 | 3. Submit the URL of your GitHub repository via [SUBMISSION METHOD] 175 | 176 | ## Due Date 177 | 178 | This assignment is due by 24.03.2025 -------------------------------------------------------------------------------- /exercises/week4/diagrams.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | User Profile Microservice Implementation 31 | Architecture Overview 32 | 33 | 34 | 35 | Client Application 36 | (Browser/Mobile App) 37 | 38 | 39 | 40 | API Gateway 41 | (Future Component) 42 | 43 | 44 | 45 | User Profile 46 | Microservice 47 | 48 | 49 | 50 | Product Service 51 | (Future Component) 52 | 53 | 54 | Order Service 55 | (Future Component) 56 | 57 | 58 | 59 | User Database 60 | 61 | 62 | 63 | Microservice Internals 64 | 65 | 66 | Controllers 67 | 68 | 69 | Services 70 | 71 | 72 | Models 73 | 74 | 75 | Middleware 76 | 77 | 78 | 79 | API Endpoints 80 | 81 | 82 | POST /users 83 | 84 | 85 | GET /users/{id} 86 | 87 | 88 | PUT /users/{id} 89 | 90 | 91 | POST /auth/login 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /exercises/week4/hands-on-exercise.md: -------------------------------------------------------------------------------- 1 | # Week 6: Microservices Architecture 2 | ## Hands-on Exercise: Designing a Microservice System 3 | 4 | ### Overview 5 | In this hands-on exercise, you'll work in small groups to design a microservice architecture for an e-commerce application. The goal is to apply the principles of microservices design that we've discussed in the lecture. 6 | 7 | ### Time Allocation: 50 minutes 8 | - Group formation: 5 minutes 9 | - Design work: 30 minutes 10 | - Preparation for presentations: 5 minutes 11 | - Group presentations: 10 minutes (2-3 minutes per group) 12 | 13 | ### Exercise Details 14 | 15 | #### Scenario: E-Shop Application 16 | You are tasked with redesigning a monolithic e-commerce application into a microservices architecture. The current monolith includes: 17 | - User registration and authentication 18 | - Product catalog with search functionality 19 | - Shopping cart management 20 | - Order processing 21 | - Payment handling 22 | - Inventory management 23 | - Shipping/delivery tracking 24 | - Customer reviews and ratings 25 | - Email notifications 26 | 27 | #### Task 1: Service Identification (15 minutes) 28 | 1. Break down the monolith into logical microservices 29 | 2. For each service, define: 30 | - Its primary responsibility/business capability 31 | - The data it needs to own 32 | - Key operations it should perform 33 | 34 | #### Task 2: Service Interactions (15 minutes) 35 | 1. Identify how services will communicate with each other 36 | 2. Determine which communication patterns to use: 37 | - Synchronous (REST, gRPC) 38 | - Asynchronous (message queue, event bus) 39 | 3. Map the critical paths for key user journeys (e.g., placing an order) 40 | 4. Identify potential bottlenecks or failure points 41 | 42 | #### Task 3: Architecture Diagram (10 minutes) 43 | Create a simple diagram showing: 44 | - All microservices in your design 45 | - Communication paths between services 46 | - Databases or data stores 47 | - External integrations (payment gateways, shipping providers, etc.) 48 | 49 | You can use any diagramming method: 50 | - Draw on paper/whiteboard 51 | - Use a digital tool (draw.io, Lucidchart, etc.) 52 | - Create a text-based representation 53 | 54 | ### Deliverables 55 | Each group should prepare: 56 | 1. A list of identified microservices with brief descriptions 57 | 2. An architecture diagram showing service relationships 58 | 3. A brief explanation of key design decisions (2-3 minutes presentation) 59 | 60 | ### Evaluation Criteria 61 | - Appropriate service boundaries based on business capabilities 62 | - Clear ownership of data by each service 63 | - Sensible communication patterns 64 | - Consideration of failure scenarios 65 | - Overall feasibility of the design 66 | 67 | ### Example Services to Consider 68 | - User Service 69 | - Product Catalog Service 70 | - Inventory Service 71 | - Order Service 72 | - Payment Service 73 | - Shipping Service 74 | - Notification Service 75 | - Review/Rating Service 76 | - Search Service 77 | - Analytics Service 78 | 79 | ### Tips for Success 80 | - Focus on business capabilities when defining services 81 | - Keep services focused and cohesive (single responsibility) 82 | - Think about data ownership - which service should be the source of truth? 83 | - Consider how to handle transactions that span multiple services 84 | - Remember that microservices add distributed systems complexity 85 | 86 | ### After the Exercise 87 | We'll have a brief presentation from each group, followed by questions and discussions about the different approaches taken. We'll analyze the trade-offs in various designs and identify common patterns that emerged. -------------------------------------------------------------------------------- /exercises/week4/mini-project-part-2.md: -------------------------------------------------------------------------------- 1 | Hi everyone, 2 | 3 | Great work on completing the initial version of the **User Profile Microservice**! Now it’s time to **upgrade** your project by doing two important things: 4 | 5 | --- 6 | 7 | ## ✅ Part 1: Add Unit and Integration Tests 8 | 9 | ### 📌 Why? 10 | Testing is a core part of building reliable applications. You’ll add: 11 | - **Unit tests** → to test individual functions (e.g., user service functions) 12 | - **Integration tests** → to test entire API routes (e.g., `/users`, `/auth/login`) 13 | 14 | ### 🧪 What You Need To Do 15 | 16 | #### 1. **Install Testing Tools** 17 | If you're using **Node.js/Express**, install: 18 | ```bash 19 | npm install --save-dev jest supertest 20 | ``` 21 | 22 | Update `package.json`: 23 | ```json 24 | "scripts": { 25 | "test": "jest" 26 | } 27 | ``` 28 | 29 | #### 2. **Set Up Jest Config (Optional)** 30 | Create a `jest.config.js` file: 31 | ```js 32 | module.exports = { 33 | testEnvironment: 'node', 34 | }; 35 | ``` 36 | 37 | #### 3. **Write Unit Tests** (`tests/userService.test.js`) 38 | Test your service layer (e.g., user creation, password validation). 39 | Example: 40 | ```js 41 | const { createUser } = require('../src/services/userService'); 42 | 43 | describe('User Service', () => { 44 | it('should create a user with valid input', () => { 45 | const user = createUser({ email: 'a@a.com', name: 'Test' }); 46 | expect(user).toHaveProperty('id'); 47 | }); 48 | }); 49 | ``` 50 | 51 | #### 4. **Write Integration Tests** (`tests/routes.test.js`) 52 | Use **Supertest** to test API routes. 53 | Example: 54 | ```js 55 | const request = require('supertest'); 56 | const app = require('../server'); // or wherever your express app is 57 | 58 | describe('POST /users', () => { 59 | it('should register a new user', async () => { 60 | const res = await request(app) 61 | .post('/users') 62 | .send({ email: 'test@test.com', password: '123456', name: 'Test' }); 63 | expect(res.statusCode).toBe(201); 64 | expect(res.body).toHaveProperty('id'); 65 | }); 66 | }); 67 | ``` 68 | 69 | #### 5. **Run Tests** 70 | ```bash 71 | npm test 72 | ``` 73 | 74 | ✅ **You must have at least:** 75 | - 2 unit tests (service functions) 76 | - 2 integration tests (API endpoints) 77 | 78 | --- 79 | 80 | ## 🌐 Part 2: Connect the App to Supabase 81 | 82 | We’ll now **replace in-memory storage** with **Supabase**, a free hosted PostgreSQL backend with RESTful API and authentication. 83 | 84 | ### 🧭 Steps 85 | 86 | #### 1. **Create a Supabase Project** 87 | - Go to [https://supabase.com/](https://supabase.com/) 88 | - Create a free account and project 89 | 90 | #### 2. **Create a `users` Table** 91 | Use the SQL editor or Table view to create: 92 | ```sql 93 | CREATE TABLE users ( 94 | id uuid PRIMARY KEY DEFAULT gen_random_uuid(), 95 | email text UNIQUE NOT NULL, 96 | password text NOT NULL, 97 | name text, 98 | address jsonb, 99 | registration_date timestamp DEFAULT now(), 100 | last_login timestamp 101 | ); 102 | ``` 103 | 104 | #### 3. **Get Supabase URL & API Key** 105 | Go to Project Settings → API: 106 | - Save the **anon public API key** 107 | - Save the **project URL** 108 | 109 | #### 4. **Install Supabase Client** 110 | ```bash 111 | npm install @supabase/supabase-js 112 | ``` 113 | 114 | #### 5. **Initialize Supabase in Your Project** 115 | Create `src/utils/supabaseClient.js`: 116 | ```js 117 | const { createClient } = require('@supabase/supabase-js'); 118 | 119 | const supabaseUrl = 'https://your-project.supabase.co'; 120 | const supabaseKey = 'your-anon-key'; 121 | 122 | const supabase = createClient(supabaseUrl, supabaseKey); 123 | 124 | module.exports = supabase; 125 | ``` 126 | 127 | #### 6. **Update User Service to Use Supabase** 128 | 129 | Instead of pushing to an array, use: 130 | ```js 131 | const supabase = require('../utils/supabaseClient'); 132 | 133 | async function createUser(user) { 134 | const { data, error } = await supabase 135 | .from('users') 136 | .insert([user]) 137 | .select(); 138 | 139 | if (error) throw new Error(error.message); 140 | return data[0]; 141 | } 142 | ``` 143 | 144 | > 🔐 Hash the password before storing (use `bcrypt`) 145 | 146 | #### 7. **Use Supabase in All CRUD Operations** 147 | Update your `getUserById`, `updateUser`, and `loginUser` functions to interact with Supabase instead of in-memory storage. 148 | 149 | --- 150 | 151 | ## 💾 What To Submit 152 | 153 | In your GitHub folder, make sure you have: 154 | 1. ✅ Working code with Supabase integration 155 | 2. 🧪 Tests inside `/tests` folder 156 | 3. 📄 Updated README showing: 157 | - How to run tests 158 | - How to connect to Supabase 159 | - Any setup steps 160 | 161 | --- 162 | 163 | If you have questions or face any issues, post them in the forum or come during office hours. This is a crucial step towards making your service production-ready. 164 | 165 | Enjoy coding! -------------------------------------------------------------------------------- /exercises/week4/mini-project.md: -------------------------------------------------------------------------------- 1 | # User Profile Microservice Mini-Project 2 | ## Advanced Programming Course - Week 6 3 | 4 | ## Project Overview 5 | 6 | In this mini-project, you will design and implement a User Profile microservice for our e-commerce application. This microservice will be responsible for user registration, authentication, and profile management. It represents one component of a larger microservice architecture that we've been designing. 7 | 8 | This hands-on project will help you apply the microservice concepts we've discussed in class, focusing on proper service boundaries, RESTful API design, and stateless authentication. 9 | 10 | ## Learning Objectives 11 | 12 | After completing this mini-project, you will be able to: 13 | - Implement a standalone microservice with well-defined responsibilities 14 | - Design and build RESTful APIs following microservice best practices 15 | - Apply proper data isolation principles 16 | - Implement stateless authentication using JWT 17 | - Document an API for other services to consume 18 | 19 | ## Project Requirements 20 | 21 | ### Core Functionality 22 | 23 | Your User Profile microservice must implement: 24 | 25 | 1. **User Management** 26 | - User registration 27 | - Profile retrieval 28 | - Profile updates 29 | - Basic validation (email format, required fields) 30 | 31 | 2. **Authentication** 32 | - User login with JWT token generation 33 | - Protected routes requiring authentication 34 | - Validation of credentials 35 | 36 | 3. **API Design** 37 | - RESTful endpoints with appropriate HTTP methods 38 | - Consistent request/response formats 39 | - Proper HTTP status codes 40 | - Clear error messages 41 | 42 | ### Technical Requirements 43 | 44 | #### Required API Endpoints 45 | 46 | Your microservice must expose these RESTful endpoints: 47 | 48 | | Endpoint | Method | Description | Authentication Required | 49 | |----------|--------|-------------|------------------------| 50 | | `/health` | GET | Service health check | No | 51 | | `/users` | POST | Create a new user | No | 52 | | `/users/{id}` | GET | Get user by ID | Yes | 53 | | `/users/{id}` | PUT | Update user details | Yes | 54 | | `/users/me` | GET | Get current user profile | Yes | 55 | | `/auth/login` | POST | Authenticate user | No | 56 | 57 | #### User Data Model 58 | 59 | Your User Profile should include at least these fields: 60 | - `id`: Unique identifier 61 | - `email`: User email (unique) 62 | - `password`: Hashed password (never returned in responses) 63 | - `name`: User's full name 64 | - `address`: Shipping/billing address information 65 | - `registrationDate`: When the user registered 66 | - `lastLogin`: When the user last logged in 67 | 68 | #### API Request/Response Examples 69 | 70 | **Create User (POST /users)** 71 | ```json 72 | // Request 73 | { 74 | "email": "user@example.com", 75 | "password": "securepassword", 76 | "name": "John Doe", 77 | "address": { 78 | "street": "123 Main St", 79 | "city": "Anytown", 80 | "zipCode": "12345", 81 | "country": "Exampleland" 82 | } 83 | } 84 | 85 | // Response (201 Created) 86 | { 87 | "id": "abc123", 88 | "email": "user@example.com", 89 | "name": "John Doe", 90 | "address": { 91 | "street": "123 Main St", 92 | "city": "Anytown", 93 | "zipCode": "12345", 94 | "country": "Exampleland" 95 | }, 96 | "registrationDate": "2025-03-20T14:00:00Z" 97 | } 98 | ``` 99 | 100 | **Login (POST /auth/login)** 101 | ```json 102 | // Request 103 | { 104 | "email": "user@example.com", 105 | "password": "securepassword" 106 | } 107 | 108 | // Response (200 OK) 109 | { 110 | "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", 111 | "userId": "abc123" 112 | } 113 | ``` 114 | 115 | **Get User (GET /users/me)** 116 | ```json 117 | // Response (200 OK) 118 | { 119 | "id": "abc123", 120 | "email": "user@example.com", 121 | "name": "John Doe", 122 | "address": { 123 | "street": "123 Main St", 124 | "city": "Anytown", 125 | "zipCode": "12345", 126 | "country": "Exampleland" 127 | }, 128 | "registrationDate": "2025-03-20T14:00:00Z", 129 | "lastLogin": "2025-03-21T09:30:00Z" 130 | } 131 | ``` 132 | 133 | #### Technical Implementation Requirements 134 | 135 | 1. **Storage**: 136 | - For this mini-project, you may use an in-memory data store (array/map) 137 | - Your implementation should be structured so that switching to a real database would be straightforward 138 | 139 | 2. **Authentication**: 140 | - Use JWT (JSON Web Tokens) for stateless authentication 141 | - Tokens should expire after a reasonable period (e.g., 24 hours) 142 | - Secure password storage with hashing (bcrypt or similar) 143 | 144 | 3. **Error Handling**: 145 | - Appropriate HTTP status codes (400 for validation errors, 401 for authentication issues, etc.) 146 | - Clear error messages that don't expose sensitive information 147 | - Consistent error response format 148 | 149 | 4. **Validation**: 150 | - Email format validation 151 | - Password strength requirements (minimum length, etc.) 152 | - Required fields checks 153 | 154 | 5. **Documentation**: 155 | - README.md with setup and API documentation 156 | - Code comments explaining key functionality 157 | 158 | ## Implementation Guidelines 159 | 160 | ### Recommended Project Structure 161 | 162 | Here's a suggested structure for your microservice (adapt based on your chosen technology): 163 | 164 | ``` 165 | user-profile-service/ 166 | ├── README.md # Project documentation 167 | ├── package.json # Dependencies (Node.js) 168 | ├── server.js # Entry point 169 | ├── src/ 170 | │ ├── controllers/ # Request handlers 171 | │ │ ├── userController.js 172 | │ │ └── authController.js 173 | │ ├── middleware/ # Authentication middleware 174 | │ │ └── authMiddleware.js 175 | │ ├── models/ # Data models 176 | │ │ └── userModel.js 177 | │ ├── routes/ # API routes 178 | │ │ ├── userRoutes.js 179 | │ │ └── authRoutes.js 180 | │ ├── services/ # Business logic 181 | │ │ └── userService.js 182 | │ └── utils/ # Helper functions 183 | │ ├── validation.js 184 | │ └── passwordUtils.js 185 | └── tests/ # Tests (optional for this project) 186 | ``` 187 | 188 | ### Recommended Technology Stack Options 189 | 190 | You may choose one of these technology stacks: 191 | 192 | **Node.js/Express.js**: 193 | - Express for API routing 194 | - JSON Web Tokens (JWT) for authentication 195 | - bcrypt for password hashing 196 | - In-memory array for storage 197 | 198 | **Python/Flask**: 199 | - Flask for the web framework 200 | - PyJWT for token handling 201 | - Werkzeug security for password hashing 202 | - In-memory dictionary for storage 203 | 204 | **Java/Spring Boot**: 205 | - Spring Boot for the framework 206 | - Spring Security for authentication 207 | - JJWT for token handling 208 | - H2 in-memory database for storage 209 | 210 | If you wish to use a different stack, please check with me first. 211 | 212 | ### Step-by-Step Implementation Guide 213 | 214 | #### Step 1: Project Setup 215 | 1. Create a new project directory 216 | 2. Initialize with appropriate package manager (npm, pip, etc.) 217 | 3. Install required dependencies 218 | 4. Configure basic server/application 219 | 5. Implement a health check endpoint 220 | 221 | #### Step 2: User Model & Storage 222 | 1. Define your User data model 223 | 2. Implement in-memory storage functionality 224 | 3. Create service methods for CRUD operations 225 | 226 | #### Step 3: Authentication 227 | 1. Implement password hashing functionality 228 | 2. Create JWT token generation and validation 229 | 3. Build authentication middleware for protected routes 230 | 231 | #### Step 4: API Routes 232 | 1. Implement route handlers for each required endpoint 233 | 2. Add request validation 234 | 3. Connect routes to your service layer 235 | 4. Apply authentication middleware to protected routes 236 | 237 | #### Step 5: Testing 238 | 1. Test each endpoint manually (using Postman, cURL, etc.) 239 | 2. Verify that authentication and validation work correctly 240 | 3. Create a collection of sample requests for demonstration 241 | 242 | #### Step 6: Documentation 243 | 1. Write a clear README with setup instructions 244 | 2. Document each API endpoint with examples 245 | 3. Add comments to your code explaining key functionality 246 | 247 | ## Evaluation Criteria 248 | 249 | Your implementation will be evaluated based on: 250 | 251 | 1. **Functionality (30%)** 252 | - All required endpoints work correctly 253 | - Authentication functions properly 254 | - Data validation is implemented 255 | - Error handling is appropriate 256 | 257 | 2. **API Design (25%)** 258 | - RESTful principles are followed 259 | - Endpoints are logically named and structured 260 | - Request/response formats are consistent 261 | - HTTP methods and status codes are used correctly 262 | 263 | 3. **Code Quality (20%)** 264 | - Code is well-organized and follows best practices 265 | - Separation of concerns is maintained 266 | - Naming is clear and consistent 267 | - Comments explain complex logic 268 | 269 | 4. **Microservice Principles (15%)** 270 | - Service has clear boundaries and responsibilities 271 | - Does not take on functionality that belongs elsewhere 272 | - Data isolation is maintained 273 | - Designed to be independently deployable 274 | 275 | 5. **Documentation (10%)** 276 | - README provides clear setup instructions 277 | - API endpoints are well-documented 278 | - Examples are provided 279 | - Code is appropriately commented 280 | 281 | ## Bonus Challenges 282 | 283 | If you complete the core requirements and want to challenge yourself further, consider implementing: 284 | 285 | 1. **Password Reset Functionality** 286 | - Add endpoints for initiating and completing password reset 287 | 288 | 2. **Role-Based Access Control** 289 | - Implement basic roles (admin, customer) with different permissions 290 | 291 | 3. **Request Rate Limiting** 292 | - Prevent abuse by implementing basic rate limiting 293 | 294 | 4. **Logging** 295 | - Add structured logging for operations and errors 296 | 297 | 5. **Simple Frontend** 298 | - Create a basic HTML/CSS/JS frontend for registration and login 299 | 300 | ## Submission Guidelines 301 | 302 | - Push your code to the course GitHub repository in your assigned folder 303 | - Include a README.md with: 304 | - Project description 305 | - Setup instructions 306 | - API documentation 307 | - Any additional features implemented 308 | - Be prepared to demonstrate your microservice during the code review session 309 | 310 | ## Resources 311 | 312 | ### Documentation & Tutorials 313 | - [Express.js Documentation](https://expressjs.com/) 314 | - [Flask Documentation](https://flask.palletsprojects.com/) 315 | - [Spring Boot Documentation](https://spring.io/projects/spring-boot) 316 | - [JWT.io - JSON Web Tokens](https://jwt.io/) 317 | - [REST API Design Best Practices](https://restfulapi.net/) 318 | 319 | ### Example Code References 320 | - Check the course GitHub repository for starter code examples 321 | - Refer to the class demo for implementation patterns 322 | 323 | ### Tools 324 | - [Postman](https://www.postman.com/) - API testing 325 | - [JWT Debugger](https://jwt.io/#debugger) - Test JWT tokens 326 | - [bcrypt Calculator](https://www.bcrypt-generator.com/) - Understand password hashing 327 | 328 | ## Getting Help 329 | 330 | If you encounter difficulties during implementation: 331 | - Check the reference materials and examples 332 | - Discuss with classmates (collaboration is encouraged, but each student must submit their own work) 333 | - Post questions in the course forum 334 | - Attend office hours: Monday 10-11am 335 | - Email me at agon.bajgora@umib.net (for urgent issues) 336 | 337 | Good luck, and enjoy building your microservice! 338 | 339 | --- 340 | 341 | **Prof. Agon Bajgora** 342 | Advanced Programming Course -------------------------------------------------------------------------------- /exercises/week4/user-profile-microservice.js: -------------------------------------------------------------------------------- 1 | // user-profile-service/server.js 2 | // Entry point for the User Profile Microservice 3 | 4 | const express = require('express'); 5 | const bodyParser = require('body-parser'); 6 | const jwt = require('jsonwebtoken'); 7 | const bcrypt = require('bcrypt'); 8 | 9 | // Initialize Express 10 | const app = express(); 11 | const PORT = process.env.PORT || 3000; 12 | const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'; // Use env variable in production 13 | 14 | // Middleware 15 | app.use(bodyParser.json()); 16 | 17 | // In-memory user storage (replace with database in production) 18 | const users = []; 19 | 20 | // ===== HELPER FUNCTIONS ===== 21 | 22 | // Find user by ID 23 | const findUserById = (id) => { 24 | return users.find(user => user.id === id); 25 | }; 26 | 27 | // Find user by email 28 | const findUserByEmail = (email) => { 29 | return users.find(user => user.email === email); 30 | }; 31 | 32 | // Validate email format 33 | const isValidEmail = (email) => { 34 | const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; 35 | return emailRegex.test(email); 36 | }; 37 | 38 | // Validate password strength 39 | const isStrongPassword = (password) => { 40 | return password.length >= 8; // Add more rules as needed 41 | }; 42 | 43 | // Authentication middleware 44 | const authenticateToken = (req, res, next) => { 45 | const authHeader = req.headers['authorization']; 46 | const token = authHeader && authHeader.split(' ')[1]; 47 | 48 | if (!token) { 49 | return res.status(401).json({ error: 'Authentication token required' }); 50 | } 51 | 52 | jwt.verify(token, JWT_SECRET, (err, user) => { 53 | if (err) { 54 | return res.status(403).json({ error: 'Invalid or expired token' }); 55 | } 56 | 57 | req.user = user; 58 | next(); 59 | }); 60 | }; 61 | 62 | // ===== ROUTES ===== 63 | 64 | // Health check endpoint 65 | app.get('/health', (req, res) => { 66 | res.status(200).json({ status: 'UP', service: 'user-profile-service' }); 67 | }); 68 | 69 | // TODO: Implement the following endpoints: 70 | // 1. POST /users - Create a new user 71 | // 2. GET /users/:id - Get user by ID (protected) 72 | // 3. PUT /users/:id - Update user details (protected) 73 | // 4. GET /users/me - Get current user (protected) 74 | // 5. POST /auth/login - Authenticate user 75 | 76 | // Start the server 77 | app.listen(PORT, () => { 78 | console.log(`User Profile Service running on port ${PORT}`); 79 | }); -------------------------------------------------------------------------------- /exercises/week5/mini-project.md: -------------------------------------------------------------------------------- 1 | ### 🧪 **Assignment: Full Stack Mini App with Docker Compose** 2 | 3 | #### 🎯 **Objective:** 4 | Build and containerize a small full-stack web application using **Node.js**, a **database of your choice**, and a **minimal frontend**. Use **Docker Compose** to run the entire stack with one command. 5 | 6 | --- 7 | 8 | ### 📦 **Project Requirements:** 9 | 10 | #### 🔧 1. **Backend (Node.js):** 11 | - Use **Express.js** to build a simple REST API. 12 | - Create **one resource** (e.g., `tasks`, `notes`, `products`, etc.) with the following features: 13 | - **GET** all items 14 | - **POST** a new item 15 | - Optional: **DELETE** an item by ID 16 | 17 | #### 💾 2. **Database (Your choice):** 18 | Choose **one** from the following: 19 | - **PostgreSQL** 20 | - **MongoDB** 21 | - **MySQL** 22 | - **SQLite** (in a volume) 23 | 24 | Use it to store your resource data. The database must: 25 | - Be launched as a separate service in Docker Compose. 26 | - Be connected to your backend using environment variables. 27 | 28 | #### 🎨 3. **Frontend (Minimal):** 29 | - Use **HTML + JavaScript** (can be plain or use a small framework like Vue/React if you prefer). 30 | - Must show: 31 | - A list of the items (fetched from the backend). 32 | - A form to create a new item. 33 | 34 | No styling or design is required—focus on **functionality**. 35 | 36 | #### 🐳 4. **Docker & Docker Compose:** 37 | - Create a `Dockerfile` for the backend (and for the frontend if needed). 38 | - Define all services in `docker-compose.yml`: 39 | - Backend 40 | - Database 41 | - Frontend (can be served using nginx or Node.js) 42 | - Running `docker compose up` should launch the entire app. 43 | - Use volumes and environment variables as needed. 44 | 45 | --- 46 | 47 | ### 📝 **Deliverables:** 48 | - A GitHub repo with: 49 | - `backend/` folder with source code and Dockerfile 50 | - `frontend/` folder with HTML/JS and Dockerfile or config 51 | - `docker-compose.yml` at root 52 | - A `README.md` with: 53 | - Brief project description 54 | - How to run the app using Docker Compose 55 | - Screenshot of working app (optional but nice) 56 | 57 | --- 58 | 59 | ### ✅ **Evaluation Criteria:** 60 | | Criterion | Description | 61 | |----------|-------------| 62 | | ✅ Docker Compose setup | All services start with `docker compose up` | 63 | | ✅ Working backend | Can GET and POST resource items | 64 | | ✅ Connected database | Data is stored and retrieved properly | 65 | | ✅ Functional frontend | Can view and create items | 66 | | ✅ Code clarity | Clean, organized code and repo | 67 | | ✅ README | Clear instructions to run the app | 68 | 69 | --- 70 | -------------------------------------------------------------------------------- /faq/faq.md: -------------------------------------------------------------------------------- 1 | # 📌 Frequently Asked Questions 2 | 3 | **Q1: Where do I submit my assignments?** 4 | Assignments should be submitted via **GitHub Pull Requests**. 5 | 6 | **Q2: Can I use AI tools for coding?** 7 | Yes, but you must **understand what the AI-generated code does** and be able to explain it. 8 | 9 | **Q3: What happens if I miss a session?** 10 | Check the repository for recorded sessions and assignments. 11 | 12 | --- -------------------------------------------------------------------------------- /projects/final/docker-compose-example.md: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | # Frontend service 5 | frontend: 6 | build: 7 | context: ./frontend 8 | dockerfile: Dockerfile 9 | ports: 10 | - "3000:3000" 11 | depends_on: 12 | - api-gateway 13 | environment: 14 | - REACT_APP_API_URL=http://api-gateway:8000 15 | - NODE_ENV=development 16 | volumes: 17 | - ./frontend:/app 18 | - /app/node_modules 19 | 20 | # API Gateway 21 | api-gateway: 22 | build: 23 | context: ./api-gateway 24 | dockerfile: Dockerfile 25 | ports: 26 | - "8000:8000" 27 | depends_on: 28 | - auth-service 29 | - main-service 30 | environment: 31 | - AUTH_SERVICE_URL=http://auth-service:8001 32 | - MAIN_SERVICE_URL=http://main-service:8002 33 | - NODE_ENV=development 34 | volumes: 35 | - ./api-gateway:/app 36 | - /app/node_modules 37 | 38 | # Authentication Service 39 | auth-service: 40 | build: 41 | context: ./auth-service 42 | dockerfile: Dockerfile 43 | ports: 44 | - "8001:8001" 45 | depends_on: 46 | - auth-db 47 | environment: 48 | - DATABASE_URL=mongodb://auth-db:27017/auth 49 | - JWT_SECRET=your_jwt_secret_here 50 | - NODE_ENV=development 51 | volumes: 52 | - ./auth-service:/app 53 | - /app/node_modules 54 | 55 | # Main Business Logic Service 56 | main-service: 57 | build: 58 | context: ./main-service 59 | dockerfile: Dockerfile 60 | ports: 61 | - "8002:8002" 62 | depends_on: 63 | - main-db 64 | environment: 65 | - DATABASE_URL=mongodb://main-db:27017/main 66 | - NODE_ENV=development 67 | volumes: 68 | - ./main-service:/app 69 | - /app/node_modules 70 | 71 | # Auth Database 72 | auth-db: 73 | image: mongo:latest 74 | ports: 75 | - "27017:27017" 76 | volumes: 77 | - auth-data:/data/db 78 | 79 | # Main Database 80 | main-db: 81 | image: mongo:latest 82 | ports: 83 | - "27018:27017" 84 | volumes: 85 | - main-data:/data/db 86 | 87 | volumes: 88 | auth-data: 89 | main-data: -------------------------------------------------------------------------------- /projects/final/ideas.md: -------------------------------------------------------------------------------- 1 | # Microservices Final Project Ideas 2 | ## Advanced Programming - Prof. Agon Bajgora 3 | 4 | This document provides detailed project ideas for the final assignment. Each project includes the core concept, required microservices, optional extensions, and expected technology stack. Students should select one idea and make it their own with unique features and implementation. 5 | 6 | ## Basic Requirements for All Projects 7 | 8 | Every project must include: 9 | - Frontend application (React, Angular, Vue, etc.) 10 | - At least 2 backend microservices 11 | - At least 1 database (SQL or NoSQL) 12 | - Docker containerization with Docker Compose 13 | - Service-to-service communication via APIs 14 | - User authentication 15 | - GitHub repository with documentation 16 | - Working demo for final presentation 17 | 18 | --- 19 | 20 | ## 1. E-Commerce Platform 21 | 22 | **Core Concept:** A platform where users can browse products, add them to cart, and place orders. 23 | 24 | **Required Microservices:** 25 | - **User Service:** Authentication, user profiles, account management 26 | - **Product Service:** Product catalog, inventory management, product search 27 | - **Order Service:** Shopping cart, checkout, order management 28 | - **Frontend:** Product browsing, cart management, checkout flow 29 | 30 | **Database Needs:** 31 | - User DB (users, profiles) 32 | - Product DB (products, categories, inventory) 33 | - Order DB (orders, line items, transactions) 34 | 35 | **Variations & Extensions:** 36 | - **a)** Focus on fashion retail with size/color variations 37 | - **b)** Build a grocery delivery system with stock management 38 | - **c)** Create a marketplace with multiple vendors 39 | - **d)** Implement a digital products store (e-books, software) 40 | 41 | **Optional Advanced Features:** 42 | - Product recommendation engine 43 | - Inventory tracking and notifications 44 | - Reviews and ratings system 45 | - Payment processing integration (simulated) 46 | 47 | --- 48 | 49 | ## 2. Task Management System 50 | 51 | **Core Concept:** A project management tool for teams to track and organize tasks. 52 | 53 | **Required Microservices:** 54 | - **Auth Service:** User management, authentication, team memberships 55 | - **Task Service:** Task CRUD, assignment, status tracking 56 | - **Project Service:** Project organization, team management 57 | - **Frontend:** Kanban boards, task details, dashboards 58 | 59 | **Database Needs:** 60 | - User DB (users, teams) 61 | - Task DB (tasks, assignments, comments) 62 | - Project DB (projects, workspaces) 63 | 64 | **Variations & Extensions:** 65 | - **a)** Focus on software development (with sprints, user stories) 66 | - **b)** Create a student team collaboration platform 67 | - **c)** Build a personal productivity tool with time tracking 68 | - **d)** Design a service desk/ticketing system 69 | 70 | **Optional Advanced Features:** 71 | - Calendar integration 72 | - File attachments 73 | - Activity feeds and notifications 74 | - Time tracking and reporting 75 | 76 | --- 77 | 78 | ## 3. Social Media Platform 79 | 80 | **Core Concept:** A platform for users to connect, share content, and interact with each other. 81 | 82 | **Required Microservices:** 83 | - **User Service:** Profiles, authentication, connections 84 | - **Content Service:** Posts, comments, likes 85 | - **Feed Service:** Aggregating and delivering content 86 | - **Frontend:** Profile pages, feed, interaction UI 87 | 88 | **Database Needs:** 89 | - User DB (profiles, relationships) 90 | - Content DB (posts, comments, reactions) 91 | - Activity DB (events, notifications) 92 | 93 | **Variations & Extensions:** 94 | - **a)** Photo-sharing focused platform 95 | - **b)** Professional networking service 96 | - **c)** Interest-based community platform 97 | - **d)** Event discovery and planning network 98 | 99 | **Optional Advanced Features:** 100 | - Content moderation 101 | - Direct messaging 102 | - Hashtags and trending content 103 | - User recommendations 104 | 105 | --- 106 | 107 | ## 4. Blog Platform 108 | 109 | **Core Concept:** A multi-user blogging platform where users can publish and interact with content. 110 | 111 | **Required Microservices:** 112 | - **Auth Service:** User authentication, roles, permissions 113 | - **Content Service:** Articles, drafts, publishing 114 | - **Interaction Service:** Comments, likes, bookmarks 115 | - **Frontend:** Reading interface, content editor, user profiles 116 | 117 | **Database Needs:** 118 | - User DB (authors, readers) 119 | - Content DB (posts, categories, tags) 120 | - Interaction DB (comments, reactions) 121 | 122 | **Variations & Extensions:** 123 | - **a)** Technical tutorial platform with code snippets 124 | - **b)** Recipe sharing and cooking blog 125 | - **c)** Travel blog with location integration 126 | - **d)** Academic/research publication platform 127 | 128 | **Optional Advanced Features:** 129 | - Rich text editor 130 | - Content search and filtering 131 | - SEO optimization 132 | - Content analytics 133 | 134 | --- 135 | 136 | ## 5. Food Delivery System 137 | 138 | **Core Concept:** A platform connecting restaurants with customers for food ordering and delivery. 139 | 140 | **Required Microservices:** 141 | - **User Service:** Customer profiles, authentication 142 | - **Restaurant Service:** Restaurant listings, menus, hours 143 | - **Order Service:** Cart, checkout, order tracking 144 | - **Frontend:** Restaurant browsing, menu viewing, ordering UI 145 | 146 | **Database Needs:** 147 | - User DB (customers, addresses) 148 | - Restaurant DB (restaurants, menus, items) 149 | - Order DB (orders, line items, delivery info) 150 | 151 | **Variations & Extensions:** 152 | - **a)** Campus food delivery for students 153 | - **b)** Grocery delivery service 154 | - **c)** Meal prep and subscription service 155 | - **d)** Group ordering for offices 156 | 157 | **Optional Advanced Features:** 158 | - Real-time order tracking 159 | - Delivery scheduling 160 | - Rating and review system 161 | - Special offers and promotions 162 | 163 | --- 164 | 165 | ## 6. Learning Management System 166 | 167 | **Core Concept:** An educational platform for courses, assignments, and student progress tracking. 168 | 169 | **Required Microservices:** 170 | - **User Service:** Student/teacher accounts, profiles 171 | - **Course Service:** Course content, materials, modules 172 | - **Assignment Service:** Assignments, submissions, grades 173 | - **Frontend:** Course dashboard, content viewer, assignment submission 174 | 175 | **Database Needs:** 176 | - User DB (students, instructors) 177 | - Course DB (courses, materials, modules) 178 | - Assignment DB (assignments, submissions, grades) 179 | 180 | **Variations & Extensions:** 181 | - **a)** Technical skills platform with code exercises 182 | - **b)** Language learning application 183 | - **c)** Professional certification training 184 | - **d)** Interactive tutorial platform 185 | 186 | **Optional Advanced Features:** 187 | - Progress tracking and analytics 188 | - Peer review system 189 | - Discussion forums 190 | - Quiz and assessment engine 191 | 192 | --- 193 | 194 | ## 7. Event Management Platform 195 | 196 | **Core Concept:** A system for creating, discovering, and managing events with registration. 197 | 198 | **Required Microservices:** 199 | - **User Service:** Authentication, profiles 200 | - **Event Service:** Event listings, details, categories 201 | - **Registration Service:** Ticketing, attendance, check-ins 202 | - **Frontend:** Event discovery, registration, tickets management 203 | 204 | **Database Needs:** 205 | - User DB (attendees, organizers) 206 | - Event DB (events, venues, schedules) 207 | - Registration DB (tickets, check-ins) 208 | 209 | **Variations & Extensions:** 210 | - **a)** Conference management system 211 | - **b)** University event platform 212 | - **c)** Concert and entertainment ticketing 213 | - **d)** Community meetup organizer 214 | 215 | **Optional Advanced Features:** 216 | - Calendar integration 217 | - Venue maps and seating 218 | - Event recommendations 219 | - QR code ticket generation 220 | 221 | --- 222 | 223 | ## 8. Health & Fitness Tracker 224 | 225 | **Core Concept:** An application for users to track health metrics, workouts, and fitness goals. 226 | 227 | **Required Microservices:** 228 | - **User Service:** Authentication, health profiles 229 | - **Activity Service:** Workout tracking, activity logs 230 | - **Nutrition Service:** Diet tracking, meal logs 231 | - **Frontend:** Dashboard, activity entry, progress visualization 232 | 233 | **Database Needs:** 234 | - User DB (profiles, goals) 235 | - Activity DB (workouts, exercises) 236 | - Nutrition DB (meals, food items) 237 | 238 | **Variations & Extensions:** 239 | - **a)** Running and cardio tracking focus 240 | - **b)** Strength training and gym workout logger 241 | - **c)** Nutrition and diet planning emphasis 242 | - **d)** Mental wellness and meditation tracker 243 | 244 | **Optional Advanced Features:** 245 | - Goal setting and tracking 246 | - Progress analytics and reports 247 | - Social sharing and challenges 248 | - Integration with fitness APIs 249 | 250 | --- 251 | 252 | ## 9. Real Estate Listing Platform 253 | 254 | **Core Concept:** A platform for listing, searching, and managing real estate properties. 255 | 256 | **Required Microservices:** 257 | - **User Service:** User accounts (buyers, sellers, agents) 258 | - **Property Service:** Listings, details, search 259 | - **Inquiry Service:** Questions, viewing requests, offers 260 | - **Frontend:** Property search, listing details, agent contact 261 | 262 | **Database Needs:** 263 | - User DB (users, preferences) 264 | - Property DB (listings, features, images) 265 | - Transaction DB (inquiries, appointments) 266 | 267 | **Variations & Extensions:** 268 | - **a)** Rental property focus 269 | - **b)** Commercial real estate platform 270 | - **c)** Student housing marketplace 271 | - **d)** Vacation property booking system 272 | 273 | **Optional Advanced Features:** 274 | - Map-based property search 275 | - Virtual tour integration 276 | - Mortgage calculator 277 | - Favorite properties and alerts 278 | 279 | --- 280 | 281 | ## 10. Job Board & Application Tracker 282 | 283 | **Core Concept:** A platform connecting job seekers with employers and tracking applications. 284 | 285 | **Required Microservices:** 286 | - **User Service:** Candidate/employer profiles, authentication 287 | - **Job Service:** Job listings, search, categories 288 | - **Application Service:** Job applications, status tracking 289 | - **Frontend:** Job search, application management, profile editor 290 | 291 | **Database Needs:** 292 | - User DB (candidates, employers) 293 | - Job DB (listings, requirements) 294 | - Application DB (applications, statuses) 295 | 296 | **Variations & Extensions:** 297 | - **a)** Technical job board for developers 298 | - **b)** Freelance marketplace 299 | - **c)** Campus recruitment platform 300 | - **d)** Industry-specific job platform (healthcare, education) 301 | 302 | **Optional Advanced Features:** 303 | - Resume parsing 304 | - Skill matching algorithm 305 | - Interview scheduling 306 | - Application analytics 307 | 308 | --- 309 | 310 | ## 11. Music Streaming Service 311 | 312 | **Core Concept:** A platform for users to discover, stream, and organize music content. 313 | 314 | **Required Microservices:** 315 | - **Auth Service:** User authentication, subscription management 316 | - **Catalog Service:** Artists, albums, songs database 317 | - **Playlist Service:** User playlists, favorites 318 | - **Frontend:** Music player, browse interface, playlist management 319 | 320 | **Database Needs:** 321 | - User DB (users, preferences) 322 | - Media DB (songs, albums, artists) 323 | - Playlist DB (playlists, saved items) 324 | 325 | **Variations & Extensions:** 326 | - **a)** Podcast streaming platform 327 | - **b)** DJ mixing and playlist creation tool 328 | - **c)** Music for meditation and wellness 329 | - **d)** Educational music platform for students 330 | 331 | **Optional Advanced Features:** 332 | - Recommendation engine 333 | - Audio visualization 334 | - Offline playback simulation 335 | - Social sharing features 336 | 337 | --- 338 | 339 | ## 12. Budget Tracker & Financial Planner 340 | 341 | **Core Concept:** An application to help users track expenses, manage budgets, and set financial goals. 342 | 343 | **Required Microservices:** 344 | - **User Service:** Authentication, profile management 345 | - **Transaction Service:** Expense tracking, categorization 346 | - **Budget Service:** Budget setting, reports, forecasting 347 | - **Frontend:** Dashboard, transaction entry, budget visualization 348 | 349 | **Database Needs:** 350 | - User DB (users, preferences) 351 | - Transaction DB (expenses, income) 352 | - Budget DB (categories, limits, goals) 353 | 354 | **Variations & Extensions:** 355 | - **a)** Personal finance manager 356 | - **b)** Small business expense tracker 357 | - **c)** Student budget and loan management 358 | - **d)** Group expense splitting app 359 | 360 | **Optional Advanced Features:** 361 | - Data visualization and reports 362 | - Recurring transaction management 363 | - Financial goal tracking 364 | - Receipt scanning simulation 365 | 366 | --- 367 | 368 | ## 13. Content Management System (CMS) 369 | 370 | **Core Concept:** A system for creating, managing, and publishing digital content across various channels. 371 | 372 | **Required Microservices:** 373 | - **Auth Service:** User management, roles, permissions 374 | - **Content Service:** Content creation, versioning, publishing 375 | - **Media Service:** Image/file uploads, processing 376 | - **Frontend:** Content editor, admin dashboard, preview 377 | 378 | **Database Needs:** 379 | - User DB (editors, admins) 380 | - Content DB (pages, posts, structures) 381 | - Media DB (images, files, metadata) 382 | 383 | **Variations & Extensions:** 384 | - **a)** Website builder with templates 385 | - **b)** Digital asset management system 386 | - **c)** Knowledge base/documentation platform 387 | - **d)** Multi-channel content publisher 388 | 389 | **Optional Advanced Features:** 390 | - Version control and drafts 391 | - Workflow and approval process 392 | - SEO tools and suggestions 393 | - Content analytics 394 | 395 | --- 396 | 397 | ## 14. Inventory Management System 398 | 399 | **Core Concept:** A system for tracking inventory, managing stock levels, and processing inventory transactions. 400 | 401 | **Required Microservices:** 402 | - **Auth Service:** User authentication, role management 403 | - **Inventory Service:** Product catalog, stock levels 404 | - **Transaction Service:** Orders, restocking, adjustments 405 | - **Frontend:** Inventory dashboard, transaction entry, reports 406 | 407 | **Database Needs:** 408 | - User DB (staff, managers) 409 | - Product DB (items, categories) 410 | - Transaction DB (orders, adjustments) 411 | 412 | **Variations & Extensions:** 413 | - **a)** Retail store inventory system 414 | - **b)** Warehouse management application 415 | - **c)** Restaurant inventory and ordering 416 | - **d)** Library book management system 417 | 418 | **Optional Advanced Features:** 419 | - Barcode/QR code generation 420 | - Low stock alerts 421 | - Vendor management 422 | - Inventory analytics and forecasting 423 | 424 | --- 425 | 426 | ## 15. Appointment Scheduling System 427 | 428 | **Core Concept:** A platform for booking and managing appointments between service providers and clients. 429 | 430 | **Required Microservices:** 431 | - **User Service:** Provider/client accounts, authentication 432 | - **Schedule Service:** Availability management, booking 433 | - **Notification Service:** Reminders, updates 434 | - **Frontend:** Booking interface, calendar, provider dashboard 435 | 436 | **Database Needs:** 437 | - User DB (providers, clients) 438 | - Schedule DB (slots, bookings) 439 | - Notification DB (messages, preferences) 440 | 441 | **Variations & Extensions:** 442 | - **a)** Medical clinic appointment system 443 | - **b)** Beauty salon booking platform 444 | - **c)** Academic advising scheduler 445 | - **d)** Professional consultation booking 446 | 447 | **Optional Advanced Features:** 448 | - Calendar integration 449 | - Resource allocation (rooms, equipment) 450 | - Online payment processing 451 | - Recurring appointment scheduling 452 | 453 | --- 454 | 455 | ## Project Selection Process 456 | 457 | 1. Students form teams of 2-3 members 458 | 2. Each team selects a project idea (or proposes their own) 459 | 3. Teams must choose unique variations - no two teams should implement the exact same project 460 | 4. Register your selection with the instructor to confirm availability 461 | 462 | ## Getting Started 463 | 464 | 1. Create a GitHub repository for your project 465 | 2. Set up initial project structure 466 | 3. Create a README.md with: 467 | - Project overview 468 | - Team members 469 | - Architecture diagram 470 | - Technology stack 471 | - Setup instructions 472 | 4. Begin by implementing service skeletons and APIs -------------------------------------------------------------------------------- /projects/final/requirements.md: -------------------------------------------------------------------------------- 1 | # Final Project Requirements & Grading Guide 2 | ## Advanced Programming - Prof. Agon Bajgora 3 | 4 | This document outlines the detailed requirements, deliverables, and evaluation criteria for the final project, worth 40% of your total course grade. 5 | 6 | ## Core Requirements 7 | 8 | Every final project must include the following components: 9 | 10 | ### 1. Architecture & Services 11 | - **Microservices Architecture**: Implement at least 2 separate backend services plus a frontend 12 | - **Service Boundaries**: Each service should have clear responsibilities and API contracts 13 | - **Independent Deployment**: Services must be containerized separately 14 | 15 | ### 2. Technology Stack 16 | - **Frontend**: Single-page application using a modern framework (React, Angular, Vue.js) 17 | - **Backend Services**: RESTful APIs using appropriate frameworks (Node.js/Express, Spring Boot, Django, etc.) 18 | - **Database**: At least one database (SQL or NoSQL) with proper data modeling 19 | - **API Communication**: Well-defined interfaces between services 20 | - **Configuration**: Environment variables for configuration 21 | 22 | ### 3. Infrastructure & Deployment 23 | - **Docker**: Each service must have a Dockerfile 24 | - **Docker Compose**: Complete docker-compose.yml for local deployment 25 | - **Environment Isolation**: Proper separation of development and production concerns 26 | 27 | ### 4. Security Fundamentals 28 | - **Authentication**: User registration and login functionality 29 | - **Authorization**: Basic role-based access control 30 | - **Input Validation**: Sanitization of user inputs 31 | - **Secure Configurations**: No hardcoded credentials 32 | 33 | ### 5. Code Quality & Documentation 34 | - **README Documentation**: Setup instructions, architecture overview 35 | - **API Documentation**: Endpoints, parameters, response formats 36 | - **Code Organization**: Clean, readable, and well-structured code 37 | - **Git History**: Meaningful commits and proper use of Git 38 | 39 | ## Optional Advanced Features 40 | 41 | Teams can implement additional features for higher scores: 42 | 43 | - **API Gateway**: Centralized entry point for frontend-to-backend communication 44 | - **Service Discovery**: Dynamic service registration and discovery 45 | - **Message Queue**: Asynchronous communication between services 46 | - **Caching Layer**: Performance optimization with Redis or similar 47 | - **Comprehensive Testing**: Unit and integration tests 48 | - **CI/CD Pipeline**: Automated builds and tests 49 | - **Monitoring**: Basic health checks and logging 50 | - **Advanced Security**: JWT implementation, HTTPS, etc. 51 | 52 | ## Project Deliverables 53 | 54 | Your team must submit: 55 | 56 | 1. **GitHub Repository** containing: 57 | - Source code for all services 58 | - Dockerfiles and docker-compose.yml 59 | - Documentation (README.md, API docs) 60 | - Architecture diagram(s) 61 | 62 | 2. **Architecture Design Document** explaining: 63 | - Service boundaries and responsibilities 64 | - Database schema design 65 | - API contracts between services 66 | - Technology choices and justification 67 | 68 | 3. **Working Demo** during final presentation showing: 69 | - End-to-end functionality 70 | - Deployment with Docker Compose 71 | - Key features in action 72 | 73 | ## Project Timeline 74 | 75 | - **Week 13**: Architecture design and planning 76 | - Form teams 77 | - Choose project idea 78 | - Design microservices architecture 79 | - Define API contracts 80 | 81 | - **Week 14**: Development and peer reviews 82 | - Implement core functionality 83 | - Set up Docker and Docker Compose 84 | - Conduct peer code reviews 85 | - Address feedback and iterate 86 | 87 | - **Week 15**: Finalization and presentations 88 | - Complete all required functionality 89 | - Prepare demo 90 | - Final documentation 91 | - Present to class 92 | 93 | ## Evaluation Criteria 94 | 95 | The final project (40% of course grade) will be evaluated based on: 96 | 97 | ### 1. Architecture Design (20%) 98 | - Appropriate service boundaries 99 | - Well-designed API contracts 100 | - Proper database modeling 101 | - Clear separation of concerns 102 | 103 | ### 2. Implementation (30%) 104 | - Working functionality 105 | - Code quality and organization 106 | - Error handling 107 | - Feature completeness 108 | 109 | ### 3. Docker Integration (20%) 110 | - Correct containerization 111 | - Working Docker Compose setup 112 | - Environment configuration 113 | - Deployment clarity 114 | 115 | ### 4. Documentation (15%) 116 | - Clear README and setup instructions 117 | - API documentation 118 | - Architecture diagrams 119 | - Code comments 120 | 121 | ### 5. Presentation (15%) 122 | - Live demonstration 123 | - Clear explanation of architecture 124 | - Team member contributions 125 | - Handling of Q&A 126 | 127 | ## Grading Rubric 128 | 129 | | Grade | Description | 130 | |-------|-------------| 131 | | A (90-100%) | Excellent implementation with all requirements met; additional advanced features; exceptional design and documentation; flawless demo | 132 | | B (80-89%) | Strong implementation with all core requirements met; good design and documentation; successful demo with minor issues | 133 | | C (70-79%) | Satisfactory implementation with most core requirements met; basic documentation; partially successful demo | 134 | | D (60-69%) | Incomplete implementation with several core requirements missing; minimal documentation; problematic demo | 135 | | F (below 60%) | Major components missing or non-functional; severe architectural issues; failed demo | 136 | 137 | ## Team Evaluation 138 | 139 | Each team member will complete a peer evaluation form assessing their teammates' contributions. These evaluations may adjust individual grades from the team score. 140 | 141 | Areas of contribution include: 142 | - Code implementation 143 | - Architecture design 144 | - Documentation 145 | - Problem-solving 146 | - Team communication 147 | 148 | ## Getting Help 149 | 150 | If your team encounters challenges: 151 | - Attend office hours: Monday 10-11am 152 | - Email: agon.bajgora@umib.net 153 | - Post questions in the course forum 154 | - Schedule a team meeting with the instructor 155 | 156 | Remember: The goal is to apply course concepts in a practical, working application. Focus on implementing a solid microservices architecture rather than complex features. -------------------------------------------------------------------------------- /projects/final/testing-requirements.md: -------------------------------------------------------------------------------- 1 | # Testing Requirements for Final Project 2 | ## Advanced Programming - Prof. Agon Bajgora 3 | 4 | Testing is a critical component of modern software development and DevOps practices. This document outlines the testing requirements for your final project, which will account for a portion of your overall project evaluation. 5 | 6 | ## Testing Requirements Overview 7 | 8 | Each final project must include the following testing components: 9 | 10 | ### 1. Unit Tests 11 | 12 | - **Frontend**: Test individual components in isolation 13 | - Minimum 5 component tests 14 | - Test component rendering and behavior 15 | - Mock external dependencies and API calls 16 | 17 | - **Backend Services**: Test individual functions and modules 18 | - Minimum 60% code coverage for each service 19 | - Focus on business logic and utility functions 20 | - Test both success and error cases 21 | 22 | ### 2. Integration Tests 23 | 24 | - **API Tests**: Verify endpoint behavior 25 | - Test at least 3 key API endpoints per service 26 | - Verify correct response status codes 27 | - Test request validation and error handling 28 | - Verify payload structure 29 | 30 | - **Service Integration**: Test interaction between services 31 | - Create at least 2 tests that verify service-to-service communication 32 | - Test authentication flow across services 33 | 34 | ### 3. Database Tests 35 | 36 | - Test database operations 37 | - Verify CRUD operations work correctly 38 | - Test data validation rules 39 | - Use test databases (not production) 40 | 41 | ### 4. End-to-End Test 42 | 43 | - Create at least 1 end-to-end test that: 44 | - Simulates a complete user flow 45 | - Interacts with the frontend 46 | - Validates data through the entire system 47 | 48 | ## Testing Tools & Frameworks 49 | 50 | Recommended testing tools by component: 51 | 52 | ### Frontend Testing 53 | - **React**: Jest + React Testing Library / Enzyme 54 | - **Angular**: Jasmine + Karma 55 | - **Vue**: Vue Test Utils + Jest 56 | 57 | ### Backend Testing 58 | - **Node.js**: Jest / Mocha + Chai 59 | - **Python**: Pytest 60 | - **Java**: JUnit + Mockito 61 | 62 | ### API Testing 63 | - **Postman** collections (export and include in repo) 64 | - **Supertest** (Node.js) 65 | - **REST Assured** (Java) 66 | 67 | ### E2E Testing 68 | - **Cypress** 69 | - **Selenium** 70 | - **Playwright** 71 | 72 | ## Test Organization 73 | 74 | Organize your tests with the following structure: 75 | 76 | ``` 77 | /service-name 78 | /src 79 | /components 80 | /routes 81 | ... 82 | /tests 83 | /unit 84 | /integration 85 | /e2e 86 | /coverage 87 | ``` 88 | 89 | ## Testing Documentation 90 | 91 | Include in your project documentation: 92 | 93 | 1. **Testing Strategy**: Brief explanation of your testing approach 94 | 2. **Test Coverage Report**: Include or screenshot coverage reports 95 | 3. **Running Tests**: Instructions for running tests locally 96 | 4. **CI Integration**: If you set up CI, explain how tests run in the pipeline 97 | 98 | ## Test Quality Criteria 99 | 100 | Tests will be evaluated based on: 101 | 102 | 1. **Coverage**: Percentage of code covered by tests 103 | 2. **Relevance**: Tests should verify important business logic 104 | 3. **Readability**: Tests should be well-organized and documented 105 | 4. **Independence**: Tests should not depend on each other 106 | 5. **Reliability**: Tests should not be flaky or inconsistent 107 | 108 | ## Including Tests in CI/CD (Optional) 109 | 110 | For advanced implementations, integrate tests into your CI/CD pipeline: 111 | 112 | - Configure GitHub Actions to run tests on each push 113 | - Fail the build if tests don't pass 114 | - Generate and store test coverage reports 115 | 116 | ## Grading Impact 117 | 118 | Testing will account for 15% of your final project grade, distributed as follows: 119 | 120 | - **Unit Tests**: 6% 121 | - **Integration Tests**: 5% 122 | - **Database Tests**: 2% 123 | - **E2E Tests**: 2% 124 | 125 | ## Testing Workflow Recommendations 126 | 127 | 1. **Write Tests Early**: Start with test cases before or alongside implementation 128 | 2. **Test-Driven Development**: Consider TDD for complex functionality 129 | 3. **Continuous Testing**: Run tests frequently during development 130 | 4. **Regression Testing**: Ensure new features don't break existing functionality 131 | 132 | ## Sample Test Cases 133 | 134 | ### Example Unit Test (Jest + React) 135 | 136 | ```javascript 137 | import { render, screen } from '@testing-library/react'; 138 | import ProductCard from './ProductCard'; 139 | 140 | test('renders product information correctly', () => { 141 | const product = { 142 | id: 1, 143 | name: 'Test Product', 144 | price: 19.99, 145 | imageUrl: 'test-image.jpg' 146 | }; 147 | 148 | render(); 149 | 150 | expect(screen.getByText('Test Product')).toBeInTheDocument(); 151 | expect(screen.getByText('$19.99')).toBeInTheDocument(); 152 | expect(screen.getByRole('img')).toHaveAttribute('src', 'test-image.jpg'); 153 | }); 154 | ``` 155 | 156 | ### Example API Test (Supertest + Node.js) 157 | 158 | ```javascript 159 | const request = require('supertest'); 160 | const app = require('../app'); 161 | 162 | describe('Product API', () => { 163 | it('GET /api/products should return list of products', async () => { 164 | const res = await request(app) 165 | .get('/api/products') 166 | .expect('Content-Type', /json/) 167 | .expect(200); 168 | 169 | expect(Array.isArray(res.body)).toBeTruthy(); 170 | expect(res.body.length).toBeGreaterThan(0); 171 | }); 172 | 173 | it('GET /api/products/:id should return 404 for invalid id', async () => { 174 | await request(app) 175 | .get('/api/products/9999') 176 | .expect(404); 177 | }); 178 | }); 179 | ``` 180 | 181 | ## Getting Started with Testing 182 | 183 | To help you get started, here are some initial steps: 184 | 185 | 1. **Set up testing frameworks** when creating your project 186 | 2. **Create test files** alongside your implementation files 187 | 3. **Write simple tests first** to verify basic functionality 188 | 4. **Gradually add more complex tests** as your project evolves 189 | 5. **Run tests before committing** code to your repository 190 | 191 | ## Resources for Testing 192 | 193 | - [Jest Documentation](https://jestjs.io/docs/getting-started) 194 | - [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) 195 | - [Mocha Documentation](https://mochajs.org/) 196 | - [Pytest Documentation](https://docs.pytest.org/) 197 | - [Cypress Documentation](https://docs.cypress.io/) 198 | 199 | With these guidelines, you'll be able to implement comprehensive testing for your microservices project, ensuring quality and reliability of your application. -------------------------------------------------------------------------------- /projects/product-catalog-api/.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test Suite 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [16.x, 18.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | cache: 'npm' 25 | 26 | - name: Install dependencies 27 | run: npm ci 28 | 29 | - name: Run unit tests 30 | run: npm run test:unit 31 | 32 | - name: Run integration tests 33 | run: npm run test:integration 34 | 35 | - name: Generate coverage report 36 | run: npm run test:coverage 37 | 38 | - name: Upload coverage report 39 | uses: actions/upload-artifact@v3 40 | with: 41 | name: coverage-report 42 | path: coverage/ -------------------------------------------------------------------------------- /projects/product-catalog-api/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | .DS_Store 4 | .env -------------------------------------------------------------------------------- /projects/product-catalog-api/README.md: -------------------------------------------------------------------------------- 1 | # Simple Product API 2 | 3 | A lightweight REST API for a product catalog, designed for AI-assisted testing practice. 4 | 5 | ## Features 6 | 7 | - No database required (uses in-memory storage) 8 | - Simple API key authentication 9 | - Complete CRUD operations for products 10 | - Filtering and pagination 11 | 12 | ## API Endpoints 13 | 14 | | Method | Endpoint | Description | 15 | |--------|----------|-------------| 16 | | GET | /api/products | Get all products (with optional filtering) | 17 | | GET | /api/products/:id | Get a single product by ID | 18 | | POST | /api/products | Create a new product | 19 | | PUT | /api/products/:id | Update an existing product | 20 | | DELETE | /api/products/:id | Delete a product | 21 | | GET | /api/products/categories/all | Get all product categories | 22 | 23 | ## Query Parameters (for GET /api/products) 24 | 25 | - `category`: Filter by product category 26 | - `minPrice`: Minimum price filter 27 | - `maxPrice`: Maximum price filter 28 | - `inStock`: Set to "true" to show only in-stock items 29 | - `limit`: Maximum number of products to return (default: 20) 30 | - `offset`: Number of products to skip for pagination (default: 0) 31 | 32 | ## Setup Instructions 33 | 34 | ### Prerequisites 35 | 36 | - Node.js (v14 or later) 37 | - npm or yarn 38 | 39 | ### Installation 40 | 41 | 1. Clone this repository: 42 | ```bash 43 | git clone https://github.com/yourusername/simple-product-api.git 44 | cd simple-product-api -------------------------------------------------------------------------------- /projects/product-catalog-api/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "simple-product-api", 3 | "version": "1.0.0", 4 | "description": "Simple Product API for testing practice", 5 | "main": "src/server.js", 6 | "scripts": { 7 | "start": "node src/server.js", 8 | "dev": "nodemon src/server.js", 9 | "test": "jest", 10 | "test:unit": "jest --testPathPattern=tests/unit", 11 | "test:integration": "jest --testPathPattern=tests/integration", 12 | "test:coverage": "jest --coverage" 13 | }, 14 | "keywords": [ 15 | "api", 16 | "testing", 17 | "product" 18 | ], 19 | "author": "Agon Bajgora", 20 | "license": "MIT", 21 | "dependencies": { 22 | "express": "^4.18.2", 23 | "cors": "^2.8.5" 24 | }, 25 | "devDependencies": { 26 | "jest": "^29.5.0", 27 | "nodemon": "^2.0.22", 28 | "supertest": "^6.3.3" 29 | } 30 | } -------------------------------------------------------------------------------- /projects/product-catalog-api/src/app.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const cors = require('cors'); 3 | const productRoutes = require('./routes/product-routes'); 4 | const authMiddleware = require('./middleware/auth-middleware'); 5 | 6 | const app = express(); 7 | 8 | // Middleware 9 | app.use(express.json()); 10 | app.use(cors()); 11 | 12 | // Routes 13 | app.use('/api/products', authMiddleware, productRoutes); 14 | 15 | // Health check 16 | app.get('/health', (req, res) => { 17 | res.status(200).json({ status: 'ok' }); 18 | }); 19 | 20 | // Error handler 21 | app.use((err, req, res, next) => { 22 | console.error(err.stack); 23 | res.status(500).json({ 24 | error: true, 25 | message: 'Internal Server Error', 26 | details: process.env.NODE_ENV === 'development' ? err.message : undefined 27 | }); 28 | }); 29 | 30 | module.exports = app; -------------------------------------------------------------------------------- /projects/product-catalog-api/src/data/products.js: -------------------------------------------------------------------------------- 1 | // In-memory product database 2 | const products = [ 3 | { 4 | id: "1", 5 | name: "Wireless Headphones", 6 | description: "High-quality wireless headphones with noise cancellation", 7 | price: 99.99, 8 | category: "electronics", 9 | inStock: true, 10 | stockCount: 45 11 | }, 12 | { 13 | id: "2", 14 | name: "Smartphone", 15 | description: "Latest model with high-resolution camera", 16 | price: 699.99, 17 | category: "electronics", 18 | inStock: true, 19 | stockCount: 20 20 | }, 21 | { 22 | id: "3", 23 | name: "Running Shoes", 24 | description: "Comfortable shoes for long-distance running", 25 | price: 79.99, 26 | category: "sports", 27 | inStock: true, 28 | stockCount: 30 29 | }, 30 | { 31 | id: "4", 32 | name: "Coffee Maker", 33 | description: "Automatic coffee maker with timer", 34 | price: 49.99, 35 | category: "home", 36 | inStock: false, 37 | stockCount: 0 38 | }, 39 | { 40 | id: "5", 41 | name: "Novel - The Adventure", 42 | description: "Bestselling fiction novel", 43 | price: 19.99, 44 | category: "books", 45 | inStock: true, 46 | stockCount: 100 47 | } 48 | ]; 49 | 50 | module.exports = products; -------------------------------------------------------------------------------- /projects/product-catalog-api/src/middleware/auth-middleware.js: -------------------------------------------------------------------------------- 1 | // Simple API key authentication middleware 2 | const authMiddleware = (req, res, next) => { 3 | const apiKey = req.headers['x-api-key']; 4 | 5 | if (!apiKey || apiKey !== 'test-api-key') { 6 | return res.status(401).json({ 7 | error: true, 8 | message: 'Invalid API key', 9 | code: 'INVALID_API_KEY' 10 | }); 11 | } 12 | 13 | next(); 14 | }; 15 | 16 | module.exports = authMiddleware; -------------------------------------------------------------------------------- /projects/product-catalog-api/src/routes/product-routes.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router(); 3 | const productService = require('../services/product-service'); 4 | 5 | // Get all products 6 | router.get('/', (req, res) => { 7 | try { 8 | const result = productService.getAllProducts(req.query); 9 | res.json(result); 10 | } catch (error) { 11 | res.status(400).json({ error: true, message: error.message }); 12 | } 13 | }); 14 | 15 | // Get product by ID 16 | router.get('/:id', (req, res) => { 17 | try { 18 | const product = productService.getProductById(req.params.id); 19 | res.json(product); 20 | } catch (error) { 21 | res.status(404).json({ error: true, message: error.message }); 22 | } 23 | }); 24 | 25 | // Create a new product 26 | router.post('/', (req, res) => { 27 | try { 28 | const newProduct = productService.createProduct(req.body); 29 | res.status(201).json(newProduct); 30 | } catch (error) { 31 | res.status(400).json({ error: true, message: error.message }); 32 | } 33 | }); 34 | 35 | // Update a product 36 | router.put('/:id', (req, res) => { 37 | try { 38 | const product = productService.updateProduct(req.params.id, req.body); 39 | res.json(product); 40 | } catch (error) { 41 | res.status(404).json({ error: true, message: error.message }); 42 | } 43 | }); 44 | 45 | // Delete a product 46 | router.delete('/:id', (req, res) => { 47 | try { 48 | const result = productService.deleteProduct(req.params.id); 49 | res.json(result); 50 | } catch (error) { 51 | res.status(404).json({ error: true, message: error.message }); 52 | } 53 | }); 54 | 55 | // Get all categories 56 | router.get('/categories/all', (req, res) => { 57 | try { 58 | const categories = productService.getAllCategories(); 59 | res.json(categories); 60 | } catch (error) { 61 | res.status(500).json({ error: true, message: error.message }); 62 | } 63 | }); 64 | 65 | module.exports = router; -------------------------------------------------------------------------------- /projects/product-catalog-api/src/server.js: -------------------------------------------------------------------------------- 1 | const app = require('./app'); 2 | 3 | const PORT = process.env.PORT || 3000; 4 | 5 | const server = app.listen(PORT, () => { 6 | console.log('*************************************'); 7 | console.log(`🚀 Server running on port ${PORT}`); 8 | console.log('*************************************'); 9 | }); 10 | 11 | module.exports = server; -------------------------------------------------------------------------------- /projects/product-catalog-api/src/services/product-service.js: -------------------------------------------------------------------------------- 1 | const products = require('../data/products'); 2 | 3 | class ProductService { 4 | // Get all products with optional filtering 5 | getAllProducts(filters = {}) { 6 | let result = [...products]; 7 | 8 | // Apply category filter 9 | if (filters.category) { 10 | result = result.filter(product => product.category === filters.category); 11 | } 12 | 13 | // Apply price filters 14 | if (filters.minPrice) { 15 | result = result.filter(product => product.price >= parseFloat(filters.minPrice)); 16 | } 17 | 18 | if (filters.maxPrice) { 19 | result = result.filter(product => product.price <= parseFloat(filters.maxPrice)); 20 | } 21 | 22 | // Apply in-stock filter 23 | if (filters.inStock === 'true') { 24 | result = result.filter(product => product.inStock === true); 25 | } 26 | 27 | // Apply pagination 28 | const limit = filters.limit ? parseInt(filters.limit) : 20; 29 | const offset = filters.offset ? parseInt(filters.offset) : 0; 30 | 31 | return { 32 | total: result.length, 33 | limit, 34 | offset, 35 | products: result.slice(offset, offset + limit) 36 | }; 37 | } 38 | 39 | // Get product by ID 40 | getProductById(id) { 41 | const product = products.find(p => p.id === id); 42 | 43 | if (!product) { 44 | throw new Error('Product not found'); 45 | } 46 | 47 | return product; 48 | } 49 | 50 | // Create a new product 51 | createProduct(productData) { 52 | // Validate required fields 53 | if (!productData.name || !productData.price || !productData.category) { 54 | throw new Error('Product must have name, price, and category'); 55 | } 56 | 57 | // Generate a new ID (simple approach for demo) 58 | const newId = (Math.max(...products.map(p => parseInt(p.id))) + 1).toString(); 59 | 60 | const newProduct = { 61 | id: newId, 62 | ...productData, 63 | // Set defaults if not provided 64 | inStock: productData.inStock !== undefined ? productData.inStock : true, 65 | stockCount: productData.stockCount !== undefined ? productData.stockCount : 0, 66 | createdAt: new Date().toISOString(), 67 | updatedAt: new Date().toISOString() 68 | }; 69 | 70 | products.push(newProduct); 71 | return newProduct; 72 | } 73 | 74 | // Update an existing product 75 | updateProduct(id, updates) { 76 | const index = products.findIndex(p => p.id === id); 77 | 78 | if (index === -1) { 79 | throw new Error('Product not found'); 80 | } 81 | 82 | // Update the product 83 | const updatedProduct = { 84 | ...products[index], 85 | ...updates, 86 | updatedAt: new Date().toISOString() 87 | }; 88 | 89 | products[index] = updatedProduct; 90 | return updatedProduct; 91 | } 92 | 93 | // Delete a product 94 | deleteProduct(id) { 95 | const index = products.findIndex(p => p.id === id); 96 | 97 | if (index === -1) { 98 | throw new Error('Product not found'); 99 | } 100 | 101 | products.splice(index, 1); 102 | 103 | return { 104 | success: true, 105 | message: 'Product deleted successfully' 106 | }; 107 | } 108 | 109 | // Get all categories 110 | getAllCategories() { 111 | const categories = [...new Set(products.map(p => p.category))]; 112 | return { categories }; 113 | } 114 | } 115 | 116 | module.exports = new ProductService(); -------------------------------------------------------------------------------- /projects/product-catalog-api/tests/integration/product-routes.test.js: -------------------------------------------------------------------------------- 1 | // This is a starter file - students will complete this 2 | const request = require('supertest'); 3 | const app = require('../../src/app'); 4 | 5 | describe('Product API Routes', () => { 6 | // Valid API key for tests 7 | const validApiKey = 'test-api-key'; 8 | 9 | // Sample test to get started 10 | describe('GET /api/products', () => { 11 | it('should return 401 if no API key is provided', async () => { 12 | const res = await request(app).get('/api/products'); 13 | expect(res.statusCode).toEqual(401); 14 | }); 15 | 16 | it('should return a list of products with valid API key', async () => { 17 | const res = await request(app) 18 | .get('/api/products') 19 | .set('X-API-Key', validApiKey); 20 | 21 | expect(res.statusCode).toEqual(200); 22 | expect(res.body).toHaveProperty('products'); 23 | expect(Array.isArray(res.body.products)).toBe(true); 24 | }); 25 | 26 | // Students will add more tests here 27 | }); 28 | 29 | // More test suites to be added by students 30 | }); -------------------------------------------------------------------------------- /projects/product-catalog-api/tests/unit/product-service.test.js: -------------------------------------------------------------------------------- 1 | // This is a starter file - students will complete this 2 | const productService = require('../../src/services/product-service'); 3 | 4 | describe('ProductService', () => { 5 | // Sample test to get started 6 | describe('getAllProducts', () => { 7 | it('should return all products when no filters are applied', () => { 8 | const result = productService.getAllProducts(); 9 | expect(result.products.length).toBeGreaterThan(0); 10 | expect(result).toHaveProperty('total'); 11 | expect(result).toHaveProperty('limit'); 12 | expect(result).toHaveProperty('offset'); 13 | }); 14 | 15 | // Students will add more tests here 16 | }); 17 | 18 | // More test suites to be added by students 19 | }); -------------------------------------------------------------------------------- /projects/projects&assignments.md: -------------------------------------------------------------------------------- 1 | # 📌 Projects & Assignments 2 | 3 | ## **Mini-Project 1 – AI-Assisted Code Refactoring** 4 | 📌 Use AI (GitHub Copilot or ChatGPT) to refactor an existing project and improve code quality. 5 | 6 | ## **Mini-Project 2 – Microservices & API Development** 7 | 📌 Design and implement a microservice using API-first principles. 8 | 9 | ## **Final Project – AI-Powered Full-Stack App** 10 | 📌 Develop an application integrating AI-assisted development, DevOps, and security best practices. -------------------------------------------------------------------------------- /resources/aditional.md: -------------------------------------------------------------------------------- 1 | # 📌 Additional Resources 2 | 3 | - **[GitHub Copilot Docs](https://docs.github.com/en/copilot/)** 4 | - **[OWASP Security Guide](https://owasp.org/)** 5 | - **[Docker & CI/CD Tutorials](https://docs.docker.com/get-started/)** 6 | - *(More resources available in `resources/`)* -------------------------------------------------------------------------------- /resources/development-env-setup.md: -------------------------------------------------------------------------------- 1 | # Development Environment Setup Guide 2 | ## Advanced Programming Course 3 | 4 | This guide will help you set up all the necessary tools and accounts needed for the course. 5 | 6 | ## 1. GitHub Account Setup 7 | 8 | 1. **Create a GitHub account** (if you don't already have one) 9 | - Go to [GitHub.com](https://github.com/) 10 | - Click "Sign up" and follow the prompts 11 | - Choose a professional username that you won't mind sharing with future employers 12 | 13 | 2. **Install Git** 14 | - **Windows**: Download and install from [git-scm.com](https://git-scm.com/download/win) 15 | - **macOS**: 16 | - Option 1: Install using Homebrew: `brew install git` 17 | - Option 2: Download from [git-scm.com](https://git-scm.com/download/mac) 18 | - **Linux**: Use your distribution's package manager 19 | - Ubuntu/Debian: `sudo apt install git` 20 | - Fedora: `sudo dnf install git` 21 | 22 | 3. **Basic Git Configuration** 23 | ```bash 24 | git config --global user.name "Your Name" 25 | git config --global user.email "your-email@example.com" 26 | ``` 27 | 28 | 4. **Generate and Add SSH Key to GitHub** (Optional but recommended) 29 | - Follow the [official GitHub guide](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent) 30 | 31 | ## 2. Install Visual Studio Code 32 | 33 | 1. **Download and Install VS Code** 34 | - Go to [code.visualstudio.com](https://code.visualstudio.com/) 35 | - Download the appropriate version for your operating system 36 | - Follow the installation instructions 37 | 38 | 2. **Install Essential Extensions** 39 | - Open VS Code 40 | - Go to Extensions view (Ctrl+Shift+X or Cmd+Shift+X on Mac) 41 | - Install the following extensions: 42 | - **GitHub Pull Requests and Issues** by GitHub 43 | - **Docker** by Microsoft 44 | - **ESLint** or other linters depending on language preference 45 | - **Python** (if you'll be using Python) 46 | - **GitHub Copilot** (if available to you - we'll discuss access options in class) 47 | 48 | 3. **Configure VS Code Settings** 49 | - Open Settings (Ctrl+, or Cmd+, on Mac) 50 | - Enable auto-save (recommended) 51 | - Configure formatter on save (recommended) 52 | 53 | ## 3. Docker Installation 54 | 55 | 1. **Install Docker Desktop** 56 | - **Windows/Mac**: Download [Docker Desktop](https://www.docker.com/products/docker-desktop) 57 | - **Linux**: Follow the [official installation guide](https://docs.docker.com/engine/install/) 58 | 59 | 2. **Verify Installation** 60 | - Open a terminal/command prompt 61 | - Run: `docker --version` 62 | - Run: `docker run hello-world` to verify that Docker can pull and run images 63 | 64 | 3. **Docker Hub Account** (Optional) 65 | - Create a [Docker Hub](https://hub.docker.com/) account 66 | - This will be useful for pushing and sharing Docker images 67 | 68 | ## 4. Additional Tools & Accounts 69 | 70 | 1. **Postman** (for API Testing) 71 | - Download from [postman.com](https://www.postman.com/downloads/) 72 | - Create a free account when prompted 73 | 74 | 2. **Node.js and npm** (for JavaScript projects) 75 | - Download from [nodejs.org](https://nodejs.org/) 76 | - Verify installation: `node --version` and `npm --version` 77 | 78 | 3. **Python 3** (if needed for your projects) 79 | - Download from [python.org](https://www.python.org/downloads/) 80 | - Or use package managers (brew, apt, etc.) 81 | - Verify installation: `python --version` or `python3 --version` 82 | 83 | ## 5. Course GitHub Repository 84 | 85 | 1. **Join the Course Repository** 86 | - You'll receive an invitation to join our course GitHub Organization 87 | - Accept the invitation via email or through GitHub 88 | - Bookmark the repository URL for easy access 89 | 90 | 2. **Fork the Repository** (if instructed) 91 | - We'll go through this process together in class 92 | - This creates your own copy of the repository for your coursework 93 | 94 | 3. **Clone the Repository** 95 | ```bash 96 | git clone https://github.com/org-name/repo-name.git 97 | cd repo-name 98 | ``` 99 | 100 | ## Troubleshooting 101 | 102 | If you encounter any issues during setup: 103 | 1. Check our course forum for solutions 104 | 2. Google the error message (seriously, this works!) 105 | 3. Post your issue to our class discussion board 106 | 4. Come to office hours for help 107 | 108 | ## Next Steps 109 | 110 | Once you have everything installed: 111 | 1. Open the course repository in VS Code 112 | 2. Explore the project structure 113 | 3. Read the README.md file for project-specific instructions 114 | 4. Complete the first assignment (details in repository) 115 | 116 | We'll verify everyone's setup in the first lab session and troubleshoot any issues together. -------------------------------------------------------------------------------- /resources/github-reposotiry-setup.md: -------------------------------------------------------------------------------- 1 | Creating a repository and adding projects to it depends on the platform you are using. Here’s a step-by-step guide for **GitHub** (or any Git-based repository) and managing multiple projects within it. 2 | 3 | --- 4 | 5 | ### **1. Create a New Repository on GitHub** 6 | 1. **Go to GitHub**: [GitHub](https://github.com/) 7 | 2. **Click on "New Repository"**: 8 | - Click the **+** sign in the top right corner. 9 | - Select **"New repository"**. 10 | 3. **Set Up Your Repository**: 11 | - **Repository name**: Give it a name (e.g., `MyProjects`). 12 | - **Description** (optional): A short summary of your repo. 13 | - **Visibility**: Choose **Public** (open-source) or **Private**. 14 | - **Initialize with a README** (optional). 15 | - Click **Create repository**. 16 | 17 | --- 18 | 19 | ### **2. Clone the Repository to Your Local Machine** 20 | To work with the repository locally, clone it using **Git**. 21 | 22 | 1. Open **Terminal** (Mac/Linux) or **Command Prompt** (Windows). 23 | 2. Run the following command: 24 | ```sh 25 | git clone https://github.com/your-username/MyProjects.git 26 | ``` 27 | *(Replace `your-username` with your GitHub username and `MyProjects` with your repo name.)* 28 | 3. Navigate into the repo: 29 | ```sh 30 | cd MyProjects 31 | ``` 32 | 33 | --- 34 | 35 | ### **3. Create New Projects Inside the Repository** 36 | Since you want to store multiple projects inside one repository, you can organize them in **separate folders**. 37 | 38 | 1. Create a new folder for each project: 39 | ```sh 40 | mkdir Project1 41 | mkdir Project2 42 | ``` 43 | 2. Navigate into a project folder and initialize it: 44 | ```sh 45 | cd Project1 46 | ``` 47 | 48 | If it's a programming project: 49 | - For a **Node.js project**: 50 | ```sh 51 | npm init -y 52 | ``` 53 | - For a **Python project**: 54 | ```sh 55 | touch main.py 56 | ``` 57 | - For a **C# project**: 58 | ```sh 59 | dotnet new console -n Project1 60 | ``` 61 | 62 | Repeat for other projects. 63 | 64 | --- 65 | 66 | ### **4. Add and Commit Changes** 67 | Once you have added files to your projects, go back to the main repository folder: 68 | ```sh 69 | cd .. 70 | ``` 71 | Then run: 72 | ```sh 73 | git add . 74 | git commit -m "Added initial projects" 75 | git push origin main 76 | ``` 77 | 78 | --- 79 | 80 | ### **5. Managing Multiple Projects Within One Repo** 81 | - Keep each project in a **separate folder** (`Project1`, `Project2`, etc.). 82 | - Use a `.gitignore` file to ignore unnecessary files. 83 | - Create different **branches** if projects are independent: 84 | ```sh 85 | git checkout -b project1-feature 86 | ``` 87 | 88 | --- 89 | 90 | ### **Alternative Approach: Use a GitHub Organization** 91 | If these projects belong to different teams, consider creating **separate repositories** inside a **GitHub organization** instead of one monorepo. 92 | 93 | Would you like me to help set up an automated script for this process? 🚀 -------------------------------------------------------------------------------- /resources/week2/sample_data.csv: -------------------------------------------------------------------------------- 1 | id,temperature,humidity,pressure,wind_speed 2 | 1,25.2,65,1013,12 3 | 2,24.8,68,1012,10 4 | 3,26.1,62,1014,15 5 | 4,25.0,70,1013,8 6 | 5,23.9,75,1010,5 7 | 6,26.5,60,1015,18 8 | 7,24.5,65,1012,11 9 | 8,25.3,63,1014,13 10 | 9,24.7,69,1011,9 11 | 10,32.1,55,1012,22 -------------------------------------------------------------------------------- /slides/2.AI-Assisted Coding.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Agonb/advanced-programming-2025/d839fac47355efbf7fff3ecfb487a0ad476eec13/slides/2.AI-Assisted Coding.pdf -------------------------------------------------------------------------------- /slides/Week1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Agonb/advanced-programming-2025/d839fac47355efbf7fff3ecfb487a0ad476eec13/slides/Week1.pdf -------------------------------------------------------------------------------- /syllabus.md: -------------------------------------------------------------------------------- 1 | # 📌 Advanced Programming Syllabus - 2025 2 | 3 | ## 📍 **Course Description** 4 | This course introduces modern programming practices, including AI-powered development, microservices, DevOps, and secure software engineering principles. 5 | 6 | ## 📍 **Weekly Topics** 7 | | **Week** | **Topic** | 8 | |---|---| 9 | | 1 | Introduction & AI in Software Development | 10 | | 2 | AI-Assisted Coding | 11 | | 3 | AI in Testing & CI/CD | 12 | | 4 | AI-Driven Debugging & Code Analysis | 13 | | 5 | Ethics & Responsible AI Use | 14 | | 6 | Microservices Architecture | 15 | | 7 | API-First Development | 16 | | 8 | Cloud-Native Development & Infrastructure as Code | 17 | | 9 | Continuous Integration & Deployment (CI/CD) | 18 | | 10 | Secure Coding & OWASP Top 10 | 19 | | 11 | DevSecOps & CI/CD Security | 20 | | 12 | Cloud Security & Monitoring | 21 | | 13 | Project Design & Tooling | 22 | | 14 | Project Development & Peer Review | 23 | | 15 | Final Presentations & Wrap-up | 24 | 25 | --- --------------------------------------------------------------------------------