Capture Java Main Class Output in Spring Boot and Display in Angular

Discussão em 'Angular' iniciado por Omesha Pasan, Dezembro 4, 2024.

  1. Omesha Pasan

    Omesha Pasan Guest

    I have a Java Main class in a Spring Boot project that generates output when run. It needs to work both independently via the CLI and through a Spring Boot controller. When I input values via a form on the frontend, I want to run the Main class with those inputs, capture its output, and display it in real-time in a logs container on the Angular frontend.

    Here are the Angular component's HTML and TypeScript files, along with the Java Main class and the Spring Boot controller.

    Frontend(Angular)

    admin-dashboard.component.html

    <div class="dashboard-header"></div>

    <div class="dashboard">
    <div class="form-container">
    <h2>Enter Values</h2>
    <form (ngSubmit)="submitForm()">
    <label for="totalTickets">Total Tickets:</label>
    <input type="number" id="totalTickets" [(ngModel)]="totalTickets" name="totalTickets" required>

    <label for="ticketReleaseRate">Ticket Release Rate:</label>
    <input type="number" id="ticketReleaseRate" [(ngModel)]="ticketReleaseRate" name="ticketReleaseRate" required>

    <label for="customerRetrievalRate">Customer Retrieval Rate:</label>
    <input type="number" id="customerRetrievalRate" [(ngModel)]="customerRetrievalRate" name="customerRetrievalRate" required>

    <label for="maxTicketCapacity">Maximum Ticket Capacity:</label>
    <input type="number" id="maxTicketCapacity" [(ngModel)]="maxTicketCapacity" name="maxTicketCapacity" required>

    <button type="submit">Start</button>
    <button type="button" (click)="stop()">Stop</button>
    </form>
    </div>

    <div class="logs-container">
    <h2>Logs</h2>
    <div class="logs">
    <div *ngFor="let log of logs">{{ log }}</div>
    </div>
    </div>
    </div>


    admin-dashboard.component.ts

    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';

    @Component({
    selector: 'app-admin-dashboard',
    templateUrl: './admin-dashboard.component.html',
    styleUrls: ['./admin-dashboard.component.scss']
    })
    export class AdminDashboardComponent implements OnInit {
    totalTickets: number = 500;
    ticketReleaseRate: number = 123;
    customerRetrievalRate: number = 43;
    maxTicketCapacity: number = 2;

    // For storing logs
    logs: string[] = [];

    constructor(private http: HttpClient) { }

    ngOnInit(): void {
    this.http.get<any>('http://localhost:8080/api/ticketing/config')
    .subscribe(response => {
    this.totalTickets = response.totalTickets || 500;
    this.ticketReleaseRate = response.ticketReleaseRate || 123;
    this.customerRetrievalRate = response.customerRetrievalRate || 43;
    this.maxTicketCapacity = response.maxTicketCapacity || 2;
    });
    }

    // For submitting the form data to the backend
    submitForm(): void {
    const formData = {
    totalTickets: this.totalTickets,
    ticketReleaseRate: this.ticketReleaseRate,
    customerRetrievalRate: this.customerRetrievalRate,
    maxTicketCapacity: this.maxTicketCapacity
    };

    this.http.post('http://localhost:8080/api/ticketing/config', formData)
    .subscribe(response => {
    this.logs.push('Configuration updated successfully!');
    console.log('Form Submitted:', response);
    }, error => {
    this.logs.push('Error updating configuration');
    console.error('Error:', error);
    });
    }

    // For stopping the process
    stop(): void {
    console.log('Booking process stopped');
    this.logs.push('Booking process stopped');
    }
    }


    Java (needs to run separately in the CLI while also having its output displayed on the frontend)

    Main class

    package com.oop.Springboot.ticketingcli;

    public class Main {

    public static void runTicketingProcess(Configuration config) {
    int totalTickets = config.getTotalTickets();
    int ticketReleaseRate = config.getTicketReleaseRate();
    int customerRetrievalRate = config.getCustomerRetrievalRate();
    int maxCapacity = config.getMaxTicketCapacity();

    TicketPool ticketPool = new TicketPool(maxCapacity);

    // Create vendor threads to add tickets to the pool
    for (int i = 0; i < ticketReleaseRate; i++) {
    int vendorId = i + 1;
    Vendor vendor = new Vendor(vendorId, ticketPool, totalTickets, ticketReleaseRate);
    Thread vendorThread = new Thread(vendor);
    vendorThread.start();
    }

    // Create customer threads to book tickets from the pool
    for (int i = 0; i < customerRetrievalRate; i++) {
    int customerId = i + 1;
    Customer customer = new Customer(customerId, ticketPool, 1000);
    Thread customerThread = new Thread(customer);
    customerThread.start();
    }
    }

    // Main method for running the application as a standalone Java app
    public static void main(String[] args) {
    // Create a sample configuration for testing
    Configuration config = new Configuration();
    config.setTotalTickets(100);
    config.setTicketReleaseRate(10);
    config.setCustomerRetrievalRate(5);
    config.setMaxTicketCapacity(50);

    // Run the ticketing process with the sample configuration
    runTicketingProcess(config);
    }
    }



    Controller class

    package com.oop.Springboot.controller;

    import com.oop.Springboot.ticketingcli.Configuration;
    import com.oop.Springboot.ticketingcli.Main;
    import org.springframework.web.bind.annotation.*;

    @RestController
    @RequestMapping("/api/ticketing")
    @CrossOrigin(origins = "http://localhost:4200" , allowedHeaders = "*")
    public class TicketingController {

    private Configuration config;

    public TicketingController() {
    this.config = new Configuration();
    }

    @PostMapping("/config")
    public String updateConfig(@RequestBody Configuration newConfig) {
    this.config.setTotalTickets(newConfig.getTotalTickets());
    this.config.setTicketReleaseRate(newConfig.getTicketReleaseRate());
    this.config.setCustomerRetrievalRate(newConfig.getCustomerRetrievalRate());
    this.config.setMaxTicketCapacity(newConfig.getMaxTicketCapacity());

    Main.runTicketingProcess(config);
    return "Configuration updated successfully!";
    }

    @GetMapping("/config")
    public Configuration getConfig() {
    return this.config;
    }
    }


    What should I add to make this work?

    I tried integrating a Java Main class in a Spring Boot project to produce real-time output and send it to an Angular frontend. The goal was to input values through a form and display the output in a logs container in real-time.

    However, I am encountering the following issues:

    Error in Logs Container: When the "Start" button is clicked, the logs container displays the message:

    "Error updating configuration".


    Console Error: I’m getting the following error in the browser's console:

    {
    "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
    },
    "status": 403,
    "statusText": "OK",
    "url": "http://localhost:8080/api/ticketing/config",
    "ok": false,
    "name": "HttpErrorResponse",
    "message": "Http failure response for http://localhost:8080/api/ticketing/config: 403 OK",
    "error": null
    }


    do I need to use database?

    Continue reading...

Compartilhe esta Página