CACS354 Advance Java Programming

Advance Java ProgrammingUnit 911 min read

Project Work & Implementation in Java (Agile, MVC, Testing, Deployment)

Unit 9 of Advanced Java Programming teaches how to design, implement, test, and deploy Java-based projects using Agile methodologies, MVC architecture, unit testing, and cloud deployment, with real-world examples from Nepali apps like Daraz and eSewa.

TAKEAWAYS:

  • Learn Agile methodologies (Scrum, Kanban) to manage iterative project development with sprints, backlogs, and burndown charts.
  • Apply MVC architecture to separate business logic (Model), user interface (View), and control flow (Controller) in Java projects.
  • Use JUnit and Mockito for unit testing Java applications to ensure reliability and catch bugs early.
  • Deploy Java projects to cloud platforms (AWS, Google Cloud, Azure) and containerize them using Docker.
  • Understand version control (Git, GitHub) for collaborative development and CI/CD pipelines.
  • Compare traditional vs. Agile project management and choose the right approach for real-world scenarios.

1. Introduction to Project Work in Java

A project in software engineering is a structured effort to create a working software solution. In Java, projects range from small applications (e.g., a student grade calculator) to large-scale systems (e.g., eSewa’s transaction processing). This unit focuses on planning, implementing, testing, and deploying Java projects professionally.

Key Steps in Project Development

  1. Requirements Gathering: Define what the project should do (e.g., Daraz’s order management system).
  2. Design: Choose architecture (MVC), data structures, and algorithms.
  3. Implementation: Write Java code (Servlets, JSP, JDBC, RMI).
  4. Testing: Use JUnit to validate functionality.
  5. Deployment: Host the project on a server (AWS, Ncell’s cloud).
  6. Maintenance: Update and fix bugs post-launch.

2. Agile Methodologies in Java Projects

Agile is an iterative approach to project management where work is divided into small cycles called sprints (typically 2–4 weeks). Unlike traditional waterfall methods, Agile allows flexibility to adapt to changes.

Agile Frameworks

Framework Key Features Example Use Case
Scrum Fixed-length sprints, daily standups, backlog refinement Developing Pathao’s ride-matching app
Kanban Visual workflow (Kanban board), continuous delivery Managing eSewa’s transaction processing
Extreme Programming (XP) Pair programming, test-driven development (TDD) Building Ncell’s mobile app backend

Agile Roles in a Team

flowchart TD
    A["Product Owner"] -->|"Defines goals"| B["Scrum Master"]
    B -->|"Facilitates"| C["Development Team"]
    C -->|"Develops"| D["Sprint Backlog"]
    D -->|"Delivers"| E["Increment"]
    E -->|"Feedback"| A

Worked Example: Scrum in a Java Project

Scenario: Developing a student attendance system for a university.

  • Sprint 1 (2 weeks): Build login and user registration (Servlets + JSP).
  • Sprint 2 (2 weeks): Add attendance tracking (JDBC + database).
  • Sprint 3 (2 weeks): Implement reports (JSP + JUnit testing).

Burndown Chart (shows work remaining vs. time): Caption: Burndown chart for Sprint 1 of the attendance system.


3. MVC Architecture in Java Projects

MVC (Model-View-Controller) is a design pattern that separates a project into three components:

  1. Model: Handles data and business logic (e.g., JDBC queries).
  2. View: Displays data to the user (e.g., JSP pages).
  3. Controller: Processes user input and updates the Model (e.g., Servlets).

MVC in a Java Web App (e.g., Daraz’s Product Page)

classDiagram
    class Model {
        +getProductDetails()
        +updateInventory()
    }
    class View {
        +displayProductPage()
        +showCart()
    }
    class Controller {
        +handleRequest()
        +forwardToView()
    }
    Model --> Controller : "Sends data"
    Controller --> View : "Renders UI"
    View --> Controller : "Sends user input"

Worked Example: MVC in a Library Management System

Model: Java class Book with methods checkOut(), returnBook(). View: JSP page book.jsp displaying book details. Controller: Servlet BookServlet handling GET/POST requests.

Code Snippet: Model (Book.java)

public class Book {
    private String title;
    private String author;
    private boolean isCheckedOut;

    public void checkOut() {
        if (!isCheckedOut) {
            isCheckedOut = true;
            System.out.println(title + " checked out.");
        }
    }
}

Trace of checkOut() Method

Step Action isCheckedOut Output
1 Book object created false
2 checkOut() called false
3 Condition !isCheckedOut true false
4 isCheckedOut = true true "Book Title checked out."

4. Unit Testing with JUnit and Mockito

Unit testing ensures individual components (methods/classes) work correctly. JUnit is a testing framework for Java, and Mockito helps simulate dependencies (e.g., databases).

JUnit Test Example: Testing a Book Class

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class BookTest {
    @Test
    public void testCheckOut() {
        Book book = new Book("Java Programming", "Herbert Schildt");
        book.checkOut();
        assertTrue(book.isCheckedOut(), "Book should be checked out");
    }
}

Mockito Example: Mocking a Database Connection

import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.SQLException;

public class DatabaseTest {
    @Test
    public void testDatabaseConnection() throws SQLException {
        Connection mockConn = mock(Connection.class);
        when(mockConn.isClosed()).thenReturn(false);
        assertFalse(mockConn.isClosed());
    }
}

Advantages of Unit Testing

Advantage Description
Early Bug Detection Catches issues during development.
Improved Code Quality Encourages modular, maintainable code.
Regression Testing Ensures new changes don’t break existing functionality.

5. Version Control with Git and GitHub

Version control tracks changes in codebase. Git is a distributed version control system, and GitHub hosts repositories.

Git Commands for Project Work

flowchart TD
    A["git init"] --> B["Initialize local repository"]
    B --> C["git add ."]
    C --> D["Stage changes"]
    D --> E["git commit -m 'message'"]
    E --> F["Commit changes to local repo"]
    F --> G["git push origin main"]
    G --> H["Upload to remote GitHub repo"]

Worked Example: Collaborating on a Java Project

  1. Clone the repository:
    git clone https://github.com/team/java-project.git
    
  2. Branch for a new feature:
    git checkout -b feature/login
    
  3. Commit changes:
    git add src/
    git commit -m "Added login page"
    
  4. Push to GitHub:
    git push origin feature/login
    

6. Deployment: Docker and Cloud Platforms

Deployment makes a project accessible to users. Docker containerizes apps, and cloud platforms (AWS, Google Cloud) host them.

Dockerizing a Java Web App

  1. Create a Dockerfile:
    FROM openjdk:17-jdk-slim
    COPY target/myapp.war /app/
    WORKDIR /app
    ENTRYPOINT ["java", "-jar", "myapp.war"]
    
  2. Build and run:
    docker build -t myapp .
    docker run -p 8080:8080 myapp
    

Deploying to AWS (e.g., Ncell’s Backend)

  1. Upload Docker image to Amazon ECR.
  2. Deploy using AWS Elastic Beanstalk or EC2.
  3. Monitor with AWS CloudWatch.

7. Continuous Integration/Deployment (CI/CD)

CI/CD automates testing and deployment. Tools like Jenkins or GitHub Actions help.

CI/CD Pipeline Example

flowchart TD
    A["Code Commit"] --> B["GitHub Actions"]
    B --> C["Run JUnit Tests"]
    C -->|"Pass?"| D["Build Docker Image"]
    D --> E["Deploy to AWS"]
    C -->|"Fail"| F["Notify Team"]

In the Real World

  1. Daraz’s Order Processing System

    • Idea Used: MVC Architecture
    • How: Daraz’s frontend (View) interacts with backend services (Controller) to update inventory (Model) in real-time. JUnit tests ensure order processing logic is bug-free before deployment.
    • Real Example: When a user adds an item to cart, the OrderController validates input, updates the OrderModel, and refreshes the OrderView.
  2. eSewa’s Transaction Security

    • Idea Used: Unit Testing + Agile Sprints
    • How: eSewa uses JUnit to test payment validation logic in small sprints (Agile). Each sprint focuses on a feature (e.g., "Add UPI support"), with tests ensuring security and correctness.
    • Worked Example: A test case verifies that a transaction fails if the PIN is incorrect:
      @Test
      public void testInvalidPIN() {
          Transaction txn = new Transaction("123456", "invalidPIN");
          assertFalse(txn.verifyPIN(), "PIN should be rejected");
      }
      
  3. Pathao’s Ride-Matching Algorithm

    • Idea Used: Docker + Cloud Deployment
    • How: Pathao’s backend (written in Java) runs in Docker containers on AWS. Docker ensures consistency across development and production environments, while AWS scales the service during peak hours (e.g., evening rush).
    • Real Example: During the 2023 Dashain festival, Pathao’s team used Kubernetes (managed by AWS EKS) to automatically scale the ride-matching service to handle 50% more requests.

Exam Tips

  1. Understand Agile vs. Waterfall:

    • Agile is iterative (e.g., Scrum sprints), while Waterfall is sequential (e.g., one-phase development).
    • Exam Focus: Compare the two in a table (like the one above) and give a real-world example (e.g., Pathao uses Agile; a government project might use Waterfall).
  2. MVC Deep Dive:

    • Know how Servlets act as Controllers, JSP as Views, and JDBC as Models.
    • Exam Focus: Draw a UML diagram of MVC for a given scenario (e.g., a bank loan application system).
  3. JUnit Testing:

    • Practice writing test cases for simple Java methods (e.g., isPrime(), factorial()).
    • Exam Focus: Trace a test case step-by-step (like the checkOut() example) and explain assertions.
  4. Docker and Cloud:

    • Know the steps to containerize a Java app and deploy it to AWS/GCP.
    • Exam Focus: Describe how Docker ensures portability (runs the same on dev and production) and give an example (e.g., Ncell’s mobile app backend).
  5. Git Commands:

    • Memorize key commands (init, add, commit, push, pull, branch).
    • Exam Focus: Show a sequence diagram of a team collaborating on a GitHub repo (like the Mermaid diagram above).
  6. Project Workflow:

    • Structure your answer in 6 steps (requirements → design → implementation → testing → deployment → maintenance).
    • Exam Focus: For a given project (e.g., "Design a hospital patient management system"), map each step to real-world tools (e.g., Jira for Agile, Maven for builds, AWS for deployment).

Final Note: This unit is project-based, so expect practical questions (e.g., "Design a JUnit test for a bank account class") and scenario-based questions (e.g., "How would you deploy a Java app for Ncell’s customer support system?"). Use diagrams (MVC, Agile flowcharts) and code snippets to score full marks.

Based on the TU BCA syllabus for Advance Java Programming (CACS354), unit 9.

Discussion

Loading…