Fresco Play Hands-on Latest Solutions

Fresco Play Tech Track: Your Java Hands-On Solution Hub

Welcome to the Fresco Play Tech Track, your one-stop destination for hands-on solutions in Java. Whether you're tackling Spring Boot, T4 Ecommerce, or any other Java-related course, we've got you covered.Our blog is dedicated to helping you conquer Java challenges and build your skills. we provide clear answers and guidance to ensure your success.

T4 Ecommerce Spring Boot fresco
play,wings-t4-rest web api-spring boot fresco play,spring boot - handson - build your rest api fresco play Course 1527: Master 'Wings-T4-RESTWebAPI-Springboot' Challenge with Spring Boot Solutions. Our blog provides clear answers and guidance to help you succeed in this course. Learn Spring Boot for backend development and ace the challenge easily.Spring Boot is a Java-Based Framework for building Microservices.

The Course Id is 1527. T4 ecommerce spring boot fresco play It is not difficult to clear the final Assignment. But of the members difficult to feel to clear the hands-on Questions. These Answers are very helpful who are stuck to clear those questions.

Here in this blog we discuss some Fresco play Hands-on Problems If you  you need any Any solution feel free to ping me on Instagram   : codingsolution75 .

Disclaimer: Our mission is to assist individuals overcoming challenges in course completion, be it technical issues or a lack of expertise. The content on this website is devoted to promoting knowledge and education, serving as a resource to support and empower learners throughout their educational journey


Problem Statement : Wings-T4-RESTWebAPI-Springboot

McDiffyStore is a vendor who sell various products ranging across different categories.They hired you to develop a distributed e-commerce platform to move their business online. As an initial MVP you are required to develop a restful API back-end application in spring boot.
Here is the requirement for the application.Database models are already created and initialized as below:

 

DB initialism with following default data: 

 

If you have any questions, please send them to me via direct message on my Instagram account codingsolution75 I will respond as soon as possible.

Solution :

We have project Structure looks like below image
 Note  :Please Ignore JWTRequest.java and JWTResoonse.java

We need to write code Only com.fresco.ecommerce.model package and data.sql Script file 
Inside  Model Package we need to modified only below classes
1. Cart.java
2. CartProduct.java
3. Category.java
4. Product.java
5. Role.java
6. User.java

Once Complete above classes we need to write script inside data.sql
Now Complete each java class one by one




1.Cart.java

package com.fresco.ecommerce.models;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

@Entity
public class Cart {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Integer cartId;
	private Double totalAmount;
	@OneToOne(fetch = FetchType.EAGER)
	private User user;
	@OneToMany(fetch = FetchType.EAGER, mappedBy="cart")
	private List<CartProduct> cartProducts;

	public Cart() {
		super();
	}

	public Cart(Integer cartId, Double totalAmount, User user, List<CartProduct> cartProducts) {
		super();
		this.cartId = cartId;
		this.totalAmount = totalAmount;
		this.user = user;
		this.cartProducts = cartProducts;
	}

	public Integer getCartId() {
		return cartId;
	}

	public void setCartId(Integer cartId) {
		this.cartId = cartId;
	}

	public Double getTotalAmount() {
		return totalAmount;
	}

	public void setTotalAmount(Double totalAmount) {
		this.totalAmount = totalAmount;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<CartProduct> getCartProducts() {
		return cartProducts;
	}

	public void setCartProducts(List<CartProduct> cartProducts) {
		this.cartProducts = cartProducts;
	}

	@Override
	public String toString() {
		return "Cart [cartId=" + cartId + ", totalAmount=" + totalAmount + ", user=" + user.getUserId()
				+ ", cartProducts=" + cartProducts + "]";
	}
}

  

2. CartProduct.java

package com.fresco.ecommerce.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class CartProduct {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Integer cpId;
	
	@ManyToOne()
	@JoinColumn(name="cart_id", referencedColumnName = "cartId")
	private Cart cart;
	
	@ManyToOne()
	@JoinColumn(name="product_id", referencedColumnName = "productId")
	private Product product;
	private Integer quantity = 1;

	public CartProduct() {
		super();
	}

	public CartProduct(Cart cart, Product product, Integer quantity) {
		super();
		this.cart = cart;
		this.product = product;
		this.quantity = quantity;
	}

	public Integer getCpId() {
		return cpId;
	}

	public void setCpId(Integer cpId) {
		this.cpId = cpId;
	}

	public Cart getCart() {
		return cart;
	}

	public void setCart(Cart cart) {
		this.cart = cart;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public Integer getQuantity() {
		return quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	@Override
	public String toString() {
		return "CartProduct [cpId=" + cpId + ", cart=" + cart.getCartId() + ", product=" + product.getProductId()
				+ ", quantity=" + quantity + "]";
	}

}

  

3. Category.java

package com.fresco.ecommerce.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Category {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Integer categoryId;
	
	@Column(unique = true)
	private String categoryName;

	public Category() {
		super();
	}

	public Category(String categoryName) {
		super();
		this.categoryName = categoryName;
	}

	public Integer getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(Integer categoryId) {
		this.categoryId = categoryId;
	}

	public String getCategoryName() {
		return categoryName;
	}

	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}

	@Override
	public String toString() {
		return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
	}

}

  

4. Product.java

package com.fresco.ecommerce.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class Product {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Integer productId;
	private String productName;
	private Double price;
	@ManyToOne()
	@JoinColumn(name="seller_id",referencedColumnName = "userId")
	private User seller;
	
	@ManyToOne()
	@JoinColumn(name="category_id", referencedColumnName = "categoryId")
	private Category category;

	public Product() {
		super();
	}

	public Product(Integer productId, String productName, Double price, User seller, Category category) {
		super();
		this.productId = productId;
		this.productName = productName;
		this.price = price;
		this.seller = seller;
		this.category = category;
	}

	public Integer getProductId() {
		return productId;
	}

	public void setProductId(Integer productId) {
		this.productId = productId;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	public User getSeller() {
		return seller;
	}

	public void setSeller(User seller) {
		this.seller = seller;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	@Override
	public String toString() {
		return "Product [productId=" + 0 + ", productName=" + productName + ", price=" + price + ", seller="
				+ seller.getUserId() + ", category=" + category + "]";
	}

}

  

5.Role.java

package com.fresco.ecommerce.models;

//Implement User Roles
public enum Role{
	CONSUMER, SELLER
}

  

6. User.java

package com.fresco.ecommerce.models;

import java.util.Set;

import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;

@Entity
public class User {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Integer userId;
	private String username;
	private String password;

	// Implement Roles
	@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
	@CollectionTable(name="user_role", joinColumns = @JoinColumn(name="user_id"))
	@Enumerated(EnumType.STRING)
	private Set<Role> roles;

	public User() {
		super();
	}

	public User(String username, String password, Set<Role> roles) {
		super();
		this.username = username;
		this.password = password;
		this.roles = roles;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}

	@Override
	public String toString() {
		return "User [userId=" + userId + ", username=" + username + ", password=" + password + ", roles=" + roles
				+ "]";
	}

}
  

data.sql

INSERT INTO category("CATEGORY_NAME") VALUES('Fashion');
INSERT INTO category("CATEGORY_NAME") VALUES('Electronics');
INSERT INTO category("CATEGORY_NAME") VALUES('Books');
INSERT INTO category("CATEGORY_NAME") VALUES('Groceries');
INSERT INTO category("CATEGORY_NAME") VALUES('Medicines');

INSERT INTO user("USERNAME","PASSWORD") values('jack', 'pass_word');
INSERT INTO user("USERNAME","PASSWORD") values('bob', 'pass_word');
INSERT INTO user("USERNAME","PASSWORD") values('apple', 'pass_word');
INSERT INTO user("USERNAME","PASSWORD") values('glaxo', 'pass_word');

INSERT INTO cart("TOTAL_AMOUNT","USER_USER_ID") values(20, 1);
INSERT INTO cart("TOTAL_AMOUNT","USER_USER_ID") values(0, 2);

INSERT INTO USER_ROLE("USER_ID", "ROLES") VALUES(1,'CONSUMER');
INSERT INTO USER_ROLE("USER_ID", "ROLES") VALUES(2,'CONSUMER');
INSERT INTO USER_ROLE("USER_ID", "ROLES") VALUES(3,'SELLER');
INSERT INTO USER_ROLE("USER_ID", "ROLES") VALUES(4,'SELLER');


INSERT INTO PRODUCT("PRICE", "PRODUCT_NAME", "CATEGORY_ID", "SELLER_ID") VALUES(29190, 'Apple iPad 10.2 8th Gen WiFi iOS Tablet', 2, 3);
INSERT INTO PRODUCT("PRICE", "PRODUCT_NAME", "CATEGORY_ID", "SELLER_ID") VALUES(10, 'Crocin pain relief tablet', 5, 4);

INSERT INTO CART_PRODUCT("CART_ID", "PRODUCT_ID", "QUANTITY") VALUES (1,2,2);
  
Please Write carefully otherwise you are facing issue to passing test cases If you have any questions, please send them to me via direct message on my Instagram account codingsolution75 I will respond as soon as possible.
Need More Solution ping me on Instagram   :


Problem Statement : Microservice : Wings--T4 RESTWebAPI (79659)

In this challenge, you are part of a team that is building a warehouse platform. One requirement is for a REST API service to manage products using Spring boot. You will need to add functionality to add and show product information as well as list all the products in the system. The team has come up with a set of requirements, including the API format, response codes, and the structure for the queries you must implement. The definitions and detailed requirements list follow. You will be graded on whether your application performs data retrieval and manipulation based on given use cases exactly as described in the requirements.

We have project structure like that


Now We need to change only below files

  • ProductController.java
  • ProductService.java
  • ProductRepository.java
  • Application.properties






ProductController.java

package com.example.warehouse.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.warehouse.model.Product;
import com.example.warehouse.service.ProductService;

@RestController
public class ProductController {

    /*
  This controller would be responsible for the ProductController endpoints
  Add the required annotations and create the endpoints
   */

   @Autowired
    private ProductService productService;

    //to add the Product details using Product object
    @PostMapping("/product/add")
    private Object postProduct(@RequestBody Product product){
        return productService.postProduct(product);
    }

    //to get all the Product details
    @GetMapping("/product/get")
    private Object getProduct(){
        return productService.getProduct();
    }


    //to update the product with id as pathVariable and product as object in RequestBody
    @PutMapping("/product/{id}")
    public ResponseEntity<Object> updateProduct( @PathVariable int id, @RequestBody Product product){
        return productService.updateProduct(id, product);
    }

    // to delete the product by using id as PathVariable
    @DeleteMapping("/product/{id}")
    public ResponseEntity<Object> deleteProductById(@PathVariable int id){
        return productService.deleteProductById(id);
    }

    //to get the product items by vendor
    @GetMapping("/product/vendor")
    public ResponseEntity<Object> getSimilarVendor(@RequestParam("value") String value){
        return productService.getSimilarVendor(value);
    }
}
     

ProductService.java

     package com.example.warehouse.service;

import com.example.warehouse.model.Product;
import com.example.warehouse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {

	/*
	 * Implement the business logic for the ProductService operations in this class
	 * Make sure to add required annotations
	 */

	@Autowired
	private ProductRepository productRepository;

	// to post all the Product details
	// created->201
	// badRequest->400
	public Object postProduct(Product product) {
		try {
			productRepository.save(product);
			return new ResponseEntity<>(HttpStatus.CREATED);
		} catch (Exception e) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
	}

	// to get all the Product details
	// ok->200
	// badRequest->400
	public Object getProduct() {
		List<Product> response = null;
		try {
			response = productRepository.findAll();
			if (response.size() != 0)
				return ResponseEntity.status(200).body(response);
			else {
				return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
			}
		} catch (Exception e) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
	}

	// to get the product with the value(pathVariable)
	// ok()->200
	// badRequest()->400
	public ResponseEntity<Object> getSimilarVendor(String value) {
		List<Product> lProd = null;
		try {
			lProd = productRepository.findByVender(value);
			if (lProd.size() != 0) {
				return new ResponseEntity<>(lProd, HttpStatus.OK);
			} else {
				return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
			}
		} catch (Exception e) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
	}

	// to update the Product with id as pathVariable and Product as object in
	// RequestBody
	// ok->200
	// badRequest->400
	public ResponseEntity<Object> updateProduct(int id, Product product) {
		List<Product> prodList = null;

		Optional<Product> res;

		try {
			prodList = productRepository.findAll();

			for (Product p : prodList) {
				if (p.getId() == id) {
					if (product.getCurrency() != null) {
						p.setCurrency(product.getCurrency());
					}
					if (product.getDescription() != null) {
						p.setDescription(product.getDescription());
					}
					if (product.getImage_url() != null) {
						p.setImage_url(product.getImage_url());
					}
					if (product.getName() != null) {
						p.setName(product.getName());
					}
					if (product.getPrice() != 0) {
						p.setPrice(product.getPrice());
					}
					if (product.getSku() != null) {
						p.setSku(product.getSku());
					}
					if (product.getStock() != 0) {
						p.setStock(product.getStock());
					}
					productRepository.save(p);
					return new ResponseEntity<>(p, HttpStatus.OK);
				}
			}
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

		} catch (Exception e) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
	}

	// to delete the product by using id as PathVariable
	// ok->200
	// badRequest->400
	public ResponseEntity<Object> deleteProductById(int id) {
		List<Product> response;
		try {

			response = productRepository.findAll();
			boolean f = false;
			for (Product prd : response) {
				if (prd.getId() == id) {
					productRepository.deleteById(id);
					f = true;
					break;

				}
			}
			if (f) {
				return new ResponseEntity<>(HttpStatus.OK);

			} else {
				return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

			}
		} catch (Exception e) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

		}
	}
}

     

ProductRepository.java

     package com.example.warehouse.repository;


import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.example.warehouse.model.Product;

@Repository
public interface ProductRepository extends JpaRepository<Product,Integer> {

	@Query(nativeQuery=true, value="SELECT * FROM PRODUCT WHERE VENDOR=?1")
	List<Product> findByVender(String value);

}

     

Application.Properties

spring.jpa.defer-datasource-initialization=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.h2.console.enabled=true
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root123@
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
     

Result




Now we start Complete E2 Competency In Java

#Mini-Project - Java Programming Masterclass

Question 1 : Conditional Statement

ava IF (Condition Statement)
XYZ' school had conducted the annual examination for the 5th Standard class and they want to calculate the grade for the students who all attended In the annual examination. Each student has 5 subject marks. Let's help them to calculate the grade for the students.

Define a function called calculateGrade which takes a parameter. The first parameter is students marks as a 2D array. The function definition code stub is given in the editor. Calculate grade for all students given in the list, store into the list, and return it.

Steps to calculate the grade for students:

Iterate each student, calculate the average score, and find the grade based on the average of a student.
Store the grade for each student into an array, and return it.

Input Format Format for Custom Testing

ALL

In the first line m given, denotes m students

In the second line n given, denotes n subjects

A

Next mlines n column students marks given, denotes m students with their n subjects marks.
Explanation:

Each row to be considered as individual student marks, Each row to be considered as each subject.
Each student has only 5 subjects Calculate the avg score and grade for each student Best row of students marks[] = [66.61 88 26 13], avg = 50.6. grade = 'D' (Based on the grade

table given above)

second row of students marks[]=[52, 38, 7, 74 621 avg 46.6 grade = 'F (Based on the grade table given above 
If you have any questions, please send them to me via direct message on my Instagram account codingsolution75 I will respond as soon as possible.
     class Result {

    /*
     * Complete the 'calculateGrade' function below.
     *
     * The function is expected to return a STRING_ARRAY.
     * The function accepts 2D_INTEGER_ARRAY students_marks as parameter.
     */

    public static String[] calculateGrade(int[][] students_marks) {
          String[] result = new String[students_marks.length];
          for(int i=0; i<students_marks.length ;i++){
              int sum =0;
              for(int j=0; j<students_marks[i].length; j++){
                  sum+=students_marks[i][j];
              }
              sum/=students_marks[i].length;
              System.out.println(sum);
              if(sum >= 90){
                  result[i] = "A+";
              }else if(sum < 90 && sum >= 80){
                  result[i] = "A";
              }else if(sum < 80 && sum >= 70){
                  result[i] = "B";
              }else if(sum < 70 && sum >= 60){
                  result[i] = "C";
              }else if(sum < 60 && sum >= 50){
                  result[i] = "D";
              }else{
                  result[i] = "F";
              }
          }
          return result;
    }

}
  
If you have any questions, please send them to me via direct message on my Instagram account codingsolution75 I will respond as soon as possible.

2. Classes and objects - Billing

Create a cash register for a fruit store that enables to complete purchases (applying offers,

if any), etc.
Project Setup
Class:
Register: Singleton class
Maintains a list of items for sale and their prices. Initiates and completes a checkout by returning a total bill amount Methods:
Register getinstance() static method String getTotalBill Map<String,Integer itemDetails)

Function Description

1. Create the function getInstance in Register class. Return the singleton Instance of a register class using the register variable which was declared and initiated to null.

2. Complete the function ger ToralBill in the editor below. The function must state what must be returned. getTotalBill has the following parameter(s) itemDetalls a key/value pair of string key and Integer value

The register contains the list of items and their prices in this exercise the list of items and

their prices are :

Input & Output

 
  class Register {
    
    private static Register register = null;
    
    public static Register getInstance(){
        if(register == null){
            register = new Register();
        }
        return register;
    }
    
    /*
     * Complete the 'getTotalBill' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts MAP itemDetails as parameter.
     */
   
    public String getTotalBill(Map<String,Integer> itemDetails) {

        // Write your code here
        String res = null;
        Double[] price = {2.0,1.5,1.2,1.0};
        Double sum  = 0.0;
        for(Map.Entry<String, Integer> key : itemDetails.entrySet()){
             if(key.getKey().equalsIgnoreCase("apple")){
                sum += key.getValue() * price[0];
            }else if(key.getKey().equalsIgnoreCase("orange")){
                sum += key.getValue() * price[1];
            }else if(key.getKey().equalsIgnoreCase("mango")){
                sum += key.getValue() * price[2];
            }else if(key.getKey().equalsIgnoreCase("grape")){
                sum += key.getValue() * price[3];
            }
        }
        res = String.valueOf(sum);
        return res;

    }
    
}
  
If you have any questions, please send them to me via direct message on my Instagram account codingsolution75
 
Good Luck and Start Coding! If you have any questions, please send them to me via direct message on my Instagram account codingsolution75 I will respond as soon as possible.
Need More Solution ping me on Instagram   :
codingsolution75
 
 

Comments

More Related

For Any Help Related to coding exams follow me on Instagram : codingsolution75

Popular Posts

WIPRO Latest Coding Questions with Solutions : 2023

EPAM Latest Coding Questions with Solutions 2023

TCS Wings 1 All Prerequisite

MindTree Latest Coding Questions with Solutions

TCS Digital Exam | DCA | Direct Capability Assessment

Angular - Routes and Forms

Infosys | InfytTq | Infosys Certification Exam Latest Coding Questions with Solutions

RAKUTEN Latest Coding Questions with Solutions

Cognizant