Commit d269f698 authored by Bhargava Rellu's avatar Bhargava Rellu

Initial commit

parents
#Tue Jun 07 20:48:02 IST 2022
gradle.version=7.4
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="11" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.16'
}
test {
useJUnitPlatform()
}
\ No newline at end of file
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'OrderManagementForRetailStore'
SELECT * FROM gap.products;
select category from gap.products where gender='Women' group by category;
\ No newline at end of file
package com.retail_store.order_management.application;
import com.retail_store.order_management.service.RetailStore;
import com.retail_store.order_management.service.RetailStoreService;
import com.retail_store.order_management.utils.Validate;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Logger;
public class OrderManagement {
private final Scanner scanner;
private final Logger logger;
public OrderManagement() {
System.setProperty("java.util.logging.SimpleFormatter.format",
"%5$s %n");
this.scanner = new Scanner(System.in);
this.logger = Logger.getLogger(OrderManagement.class.getName());
}
public void menu() {
logger.info("Welcome to GAP Business Management");
RetailStore gap = new RetailStoreService(scanner, logger);
String menu = "\nMenu \n 1. add product to your stock \n 2. get products available for customers \n 3. get order details \n 4. exit";
boolean flag = true;
logger.info(menu);
int menuOption = 0;
while (flag) {
try {
menuOption = scanner.nextInt();
} catch (Exception e) {
scanner.reset();
menu();
}
switch (menuOption) {
case 1:
try {
gap.addProduct();
} catch (Exception e) {
e.printStackTrace();
menu();
}
logger.info("Please enter 5 for menu\n To exit please enter 4\n To Add more enter 1");
break;
case 2:
gap.placeOrder();
logger.info("Please enter 5 for menu\n To exit please enter 4");
break;
case 4:
flag = false;
break;
case 5:
logger.info(menu);
break;
default:
logger.warning("Please enter valid menu option");
logger.info(menu);
}
}
}
public static void main(String[] args) throws SQLException {
OrderManagement orderManagement = new OrderManagement();
orderManagement.menu();
// Statement statement = Database.getConnection().createStatement();
// ResultSet resultSet = statement.executeQuery("select * from gap.products where gender='Men' group by gender");
// ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
// while (resultSet.next()) {
// for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
// System.out.println(resultSet.getString(i) + "\t");
// }
// System.out.println();
// }
RetailStore gap = new RetailStoreService(new Scanner(System.in), Logger.getLogger(RetailStore.class.getName()));
// LinkedHashMap<Size, Integer> sizeIntegerLinkedHashMap = new LinkedHashMap<>();
// sizeIntegerLinkedHashMap.put(Size.S, 0);
// sizeIntegerLinkedHashMap.put(Size.M, 3);
// sizeIntegerLinkedHashMap.put(Size.L, 4);
// sizeIntegerLinkedHashMap.put(Size.XL, 3);
// sizeIntegerLinkedHashMap.put(Size.XXL, 0);
// Product shirt1 = new Product("abcd", "men regular fit shirt", Category.HOODIES, Color.BLUE, 500.00, Gender.MEN, sizeIntegerLinkedHashMap);
// System.out.println( gap.addProductToCart(new ArrayList<Product>(), shirt1, Database.getConnection()));
// System.out.println(gap.addProductToCart(shirt1));
// gap.searchProduct();
// gap.getCategoriesByGender(Gender.FEMALE);
// gap.getProductsByGenderAndCategory(Gender.WOMEN, Category.SHIRTS);
// gap.getColorsByGenderAndCategory(Gender.MEN, Category.DRESS);
// System.out.println(UUID.randomUUID());
Validate validate = new Validate();
}
}
package com.retail_store.order_management.constants;
public enum Category {
SHIRTS(1), PANTS(2), JEANS(3), SHORTS(4), T_SHIRTS(5), POLOS(6), HOODIES(7), KURTA(8), SWEATSHIRTS(9), DRESS(10), TOPS(11);
int option;
public int getOption() {
return option;
}
Category(int option) {
this.option = option;
}
}
package com.retail_store.order_management.constants;
public enum Color {
RED(1), GREEN(2), BLUE(3), BROWN(4), GREY(5), WHITE(6), PINK(7), YELLOW(8), BLACK(9), PURPLE(10), ORANGE(11), SKY_BLUE(12);
int option;
public int getOption() {
return option;
}
Color(int option) {
this.option = option;
}
}
package com.retail_store.order_management.constants;
public enum Gender {
MEN(1, "Men"), WOMEN(2, "Women");
int option;
String gender;
public int getOption() {
return option;
}
public String getGender() {
return gender;
}
Gender(int option, String gender) {
this.option = option;
this.gender = gender;
}
}
package com.retail_store.order_management.constants;
public enum Size {
S(1, "size_s"), M(2, "size_m"), L(3, "size_l"), XL(4, "size_xl"), XXL(5, "size_xxl");
int option;
String name;
public int getOption() {
return option;
}
public String getName() {
return name;
}
Size(int option, String name) {
this.option = option;
this.name = name;
}
}
package com.retail_store.order_management.model;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class Order {
private String orderId;
private LocalDate orderDate;
private LocalTime localTime;
private String customerName;
private String phoneNumber;
List<OrderedProduct> productsList;
public Order(String orderId, LocalDate orderDate, LocalTime localTime, String customerName, String phoneNumber, List<OrderedProduct> productsList) {
this.orderId = orderId;
this.orderDate = orderDate;
this.localTime = localTime;
this.customerName = customerName;
this.phoneNumber = phoneNumber;
this.productsList = productsList;
}
public String orderIdGenerator() {
return Arrays.stream(UUID.randomUUID().toString().split("-")).findFirst().get() + "#" + Order.class.getSimpleName();
}
}
package com.retail_store.order_management.model;
import com.retail_store.order_management.constants.Category;
import com.retail_store.order_management.constants.Color;
import com.retail_store.order_management.constants.Gender;
import com.retail_store.order_management.constants.Size;
public class OrderedProduct {
private String id;
private String name;
private Category category;
private Color color;
private double price;
private Gender idealFor;
private Size size;
private int quantity;
public String getId() {
return id;
}
public String getName() {
return name;
}
public Category getCategory() {
return category;
}
public Color getColor() {
return color;
}
public double getPrice() {
return price;
}
public Gender getIdealFor() {
return idealFor;
}
public Size getSize() {
return size;
}
public int getQuantity() {
return quantity;
}
public OrderedProduct(String id, String name, Category category, Color color, double price, Gender idealFor, Size size, int quantity) {
this.id = id;
this.name = name;
this.category = category;
this.color = color;
this.price = price;
this.idealFor = idealFor;
this.size = size;
this.quantity = quantity;
}
@Override
public String toString() {
return "OrderedProduct{" +
"id='" + id + '\t' +
", name='" + name + '\n' +
", category=" + category + '\t' +
", color=" + color + '\n' +
", price=" + price + '\t' +
", idealFor=" + idealFor + '\n' +
", size=" + size + '\t' +
", quantity=" + quantity +
'}';
}
}
package com.retail_store.order_management.model;
import com.retail_store.order_management.constants.Category;
import com.retail_store.order_management.constants.Color;
import com.retail_store.order_management.constants.Gender;
import com.retail_store.order_management.constants.Size;
import java.util.Map;
public class Product {
private String id;
private String name;
private Category category;
private Color color;
private double price;
private Gender idealFor;
private Map<Size, Integer> size;
public Product(String id, String name, Category category, Color color, double price, Gender idealFor, Map<Size, Integer> size) {
this.id = id;
this.name = name;
this.category = category;
this.color = color;
this.price = price;
this.idealFor = idealFor;
this.size = size;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public Category getCategory() {
return category;
}
public Color getColor() {
return color;
}
public double getPrice() {
return price;
}
public Gender getIdealFor() {
return idealFor;
}
public Map<Size, Integer> getSize() {
return size;
}
public String getProductSizeAvailability() {
return size.entrySet().stream().map(entry -> entry.getKey() + " - " + entry.getValue()).reduce("", (sizes, size) -> sizes + "\n" + size.toString());
}
public boolean outOfStock() {
return size.entrySet().stream().allMatch(entry -> entry.getValue() <= 0);
}
public String showSizes() {
return outOfStock() ? "* Out of Stock *" : size.entrySet().stream().map(size -> size.getKey() + "-" + size.getValue()).reduce((sizes, size) -> sizes + ", " + size).get();
}
public String productShowcaseInMenu() {
return getName() + "\t" + getPrice() + "\n " + getColor() + "\t" + showSizes();
}
@Override
public String toString() {
return "Product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", category=" + category +
", color=" + color +
", price=" + price +
", idealFor=" + idealFor +
", size=" + getProductSizeAvailability() +
'}';
}
}
\ No newline at end of file
package com.retail_store.order_management.service;
import com.retail_store.order_management.constants.Category;
import com.retail_store.order_management.constants.Color;
import com.retail_store.order_management.constants.Gender;
import com.retail_store.order_management.model.Product;
import java.util.Collection;
import java.util.Map;
public interface ProductFilter {
// public List<T> getListFromMap(Map<K, V> products);
public Map<Integer, Category> getCategoriesByGender(Gender gender);
public Map<Integer, Color> getColorsByGenderAndCategory(Gender gender, Category category);
public Map<Integer, Product> getProductsByGenderAndCategory(Gender gender, Category category);
public Map<Integer, Product> getProductsByGenderAndColor(Collection<Product> productList, Color color);
// public Map<K, V> getProductsByCategory(List<T> products, Category category);
//
// public Map<K, V> getProductsByColor(List<T> products, Color color);
//
// public Map<K, V> getProductsBySize(List<T> products, Size size);
}
package com.retail_store.order_management.service;
import com.retail_store.order_management.model.OrderedProduct;
import com.retail_store.order_management.model.Product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;
public interface RetailStore {
public boolean addProduct();
public Collection<OrderedProduct> createOrder(Connection connection);
public boolean placeOrder();
public boolean addProductToCart(Collection<OrderedProduct> cart, Product product, Connection connection);
public boolean addProductToCart(Collection<OrderedProduct> cart, Product product, PreparedStatement preparedStatement);
}
package com.retail_store.order_management.service;
import com.retail_store.order_management.constants.Category;
import com.retail_store.order_management.constants.Color;
import com.retail_store.order_management.constants.Gender;
import com.retail_store.order_management.constants.Size;
import com.retail_store.order_management.model.OrderedProduct;
import com.retail_store.order_management.model.Product;
import com.retail_store.order_management.utils.Validate;
import java.sql.Date;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import static com.retail_store.order_management.utils.Database.getConnection;
public class RetailStoreService extends Validate implements RetailStore, ProductFilter {
// private Connection connection;
public List<Product> products;
public RetailStoreService(Scanner scanner, Logger logger) {
this.products = new ArrayList<>();
this.scanner = scanner;
this.logger = logger;
}
public boolean addProduct() {
boolean productAdded = false;
String id = productIdGenerator();
scanner = new Scanner(System.in);
logger.info("Enter Product details \n Enter Product Name");
String name = scanner.next();
name += scanner.nextLine();
Category category = getCategory(true, "Enter Product Category");
Color color = getColor(true, "Select color of the product");
double price = getPrice(true);
Gender gender = getGender(true, "Product is ideal for");
Map<Size, Integer> size = getProductSizes();
Connection connection = getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into products values(?,?,?,?,?,?,?,?,?,?,?)");
preparedStatement.setString(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, category.toString());
preparedStatement.setString(4, color.toString());
preparedStatement.setDouble(5, price);
preparedStatement.setString(6, gender.getGender());
preparedStatement.setInt(7, size.get(Size.S));
preparedStatement.setInt(8, size.get(Size.M));
preparedStatement.setInt(9, size.get(Size.L));
preparedStatement.setInt(10, size.get(Size.XL));
preparedStatement.setInt(11, size.get(Size.XXL));
productAdded = preparedStatement.executeUpdate() > 0;
if (productAdded) {
logger.info("Your product with name : " + name + " is added successfully");
} else {
logger.info("Your product is not added successfully");
productAdded = addProduct();
}
} catch (SQLException e) {
// e.printStackTrace();
logger.warning(e.getMessage());
logger.info("Your product is not added successfully");
productAdded = addProduct();
}
return productAdded;
}
public boolean placeOrder() {
Connection connection = getConnection();
try {
connection.setAutoCommit(false);
List<OrderedProduct> orderedProductList = new ArrayList<>(createOrder(connection));
if (orderedProductList.isEmpty()) {
logger.info("Since your order list is empty, unable to place order\n To make an order please enter 1\n Press any key to exit");
try {
int option = scanner.nextInt();
if (option == 1) {
return placeOrder();
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
String orderId = orderIdGenerator();
logger.info("Please enter Customer name");
String name = scanner.next();
name += scanner.nextLine();
logger.info("Please enter Phone number");
String phone = scanner.next();
Date date = Date.valueOf(LocalDate.now());
Time time = Time.valueOf(LocalTime.now());
connection = getConnection();
double bill = orderedProductList.stream().map(product -> product.getPrice() * product.getQuantity()).reduce(0.00, (totalBill, productBill) -> totalBill + productBill);
PreparedStatement preparedStatement = connection.prepareStatement("insert into orders values(?,?,?,?,?,?)");
preparedStatement.setString(1, orderId);
preparedStatement.setString(2, name);
preparedStatement.setString(3, phone);
preparedStatement.setDate(4, date);
preparedStatement.setTime(5, time);
preparedStatement.setDouble(6, bill);
if (preparedStatement.executeUpdate() > 0) {
preparedStatement = connection.prepareStatement("insert into ordered_products values (?,?,?,?,?,?,?,?,?)");
for (OrderedProduct product : orderedProductList) {
preparedStatement.setString(1, product.getId());
preparedStatement.setString(2, product.getName());
preparedStatement.setString(3, product.getCategory().toString());
preparedStatement.setString(4, product.getColor().toString());
preparedStatement.setDouble(5, product.getPrice());
preparedStatement.setString(6, product.getIdealFor().getGender());
preparedStatement.setString(7, product.getSize().toString());
preparedStatement.setInt(8, product.getQuantity());
preparedStatement.setString(9, orderId);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
}
connection.commit();
return true;
} catch (SQLException e) {
logger.warning(e.getMessage());
try {
connection.rollback();
} catch (SQLException ex) {
logger.warning(ex.getMessage());
}
return true;
}
}
@Override
public Collection<OrderedProduct> createOrder(Connection connection) {
List<OrderedProduct> cart = new ArrayList<>();
boolean orderBoolean = true;
while (orderBoolean) {
logger.info("********************GAP********************* " + "\n \t (1) Men \t \t \t \t (2) Women");
Gender gender = null;
gender = getGender(false, "Please select...");
boolean genderBoolean = true;
while (genderBoolean) {
Map<Integer, Category> categoryMenu = getCategoriesByGender(gender);
logger.info("Select the category\nTo change the gender please enter 0");
int categoryMenuNumber = scanner.nextInt();
Category category = categoryMenu.get(categoryMenuNumber);
if (category == null) {
break;
}
boolean categoryBoolean = true;
while (categoryBoolean) {
Map<Integer, Product> productsByGenderAndCategory = getProductsByGenderAndCategory(gender, category);
logger.info("Select the product\n To change the category please enter 0");
int productMenuNumber = scanner.nextInt();
Product product = productsByGenderAndCategory.get(productMenuNumber);
if (product == null) {
break;
}
if (!addProductToCart(cart, product, connection)) {
logger.info("Sorry to say this. Currently this product was out of stock.");
continue;
} else {
logger.info("Your product : " + product.getName() + " is added to your cart.");
}
boolean menuFlag = true;
logger.info("Please enter 1 - to continue the shopping \nPress 2 to place the order");
while (menuFlag) {
try {
int order = scanner.nextInt();
switch (order) {
case 1:
categoryBoolean = false;
genderBoolean = false;
menuFlag = false;
break;
case 2:
logger.info("Order Placed");
categoryBoolean = false;
genderBoolean = false;
menuFlag = false;
orderBoolean = false;
break;
default:
logger.info("Please enter valid option");
}
} catch (Exception e) {
logger.info("Please enter valid option");
}
}
}
}
}
return cart;
}
@Override
public synchronized boolean addProductToCart(Collection<OrderedProduct> cart, Product product, Connection connection) {
if (product.outOfStock()) {
return false;
}
logger.info(product.showSizes());
Size size = getSize(true, "Please Select Size");
logger.info("Please enter quantity required");
int quantity = getCount();
int availableQuantity = product.getSize().get(size);
if (quantity <= availableQuantity) {
int remaining = availableQuantity - quantity;
try {
PreparedStatement preparedStatement = connection.prepareStatement("update gap.products set " + size.getName() + "=? where id =?");
preparedStatement.setInt(1, remaining);
preparedStatement.setString(2, product.getId());
preparedStatement.executeUpdate();
} catch (SQLException e) {
logger.info(e.getMessage());
logger.warning("Unable to add product to cart");
return addProductToCart(cart, product, connection);
}
return cart.add(new OrderedProduct(product.getId(), product.getName(), product.getCategory(), product.getColor(), product.getPrice(), product.getIdealFor(), size, quantity));
} else {
logger.warning("your requirement is out of our quantity.\n please enter quantity less or equal to the stock available");
return addProductToCart(cart, product, connection);
}
}
@Override
public boolean addProductToCart(Collection<OrderedProduct> cart, Product product, PreparedStatement preparedStatement) {
return false;
}
@Override
public Map<Integer, Category> getCategoriesByGender(Gender gender) {
Map<Integer, Category> categoryMap = new LinkedHashMap<>();
AtomicInteger number = new AtomicInteger(0);
Connection connection = getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("select category from gap.products where gender=? group by category");
preparedStatement.setString(1, gender.getGender());
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
categoryMap.put(number.incrementAndGet(), Category.valueOf(resultSet.getString(1)));
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.info("got error while fetching the gender. please try again");
return getCategoriesByGender(gender);
}
if (categoryMap.isEmpty()) {
logger.info("Categories not found in " + gender);
} else {
String menu = categoryMap.entrySet().stream().map(entry -> entry.getKey() + ". " + entry.getValue()).reduce("", (categories, category) -> categories + "\n" + category);
logger.info(menu);
}
return categoryMap;
}
@Override
public Map<Integer, Color> getColorsByGenderAndCategory(Gender gender, Category category) {
Map<Integer, Color> colorMap = new LinkedHashMap<>();
AtomicInteger number = new AtomicInteger(0);
Connection connection = getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("select color from gap.products where gender=? and category=? group by color");
preparedStatement.setString(1, gender.getGender());
preparedStatement.setString(2, category.toString());
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
colorMap.put(number.incrementAndGet(), Color.valueOf(resultSet.getString(1)));
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.info("got error while fetching the gender. please try again");
return getColorsByGenderAndCategory(gender, category);
}
if (colorMap.isEmpty()) {
logger.info("Colors not found in " + category + " for " + gender);
} else {
String menu = colorMap.entrySet().stream().map(entry -> entry.getKey() + ". " + entry.getValue()).reduce("", (colors, color) -> colors + "\n" + color);
logger.info(menu);
}
return colorMap;
}
@Override
public Map<Integer, Product> getProductsByGenderAndCategory(Gender gender, Category category) {
Map<Integer, Product> productMap = new LinkedHashMap<>();
AtomicInteger number = new AtomicInteger(0);
Connection connection = getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("select * from gap.products where gender=? and category =?");
preparedStatement.setString(1, gender.getGender());
preparedStatement.setString(2, category.toString());
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
while (resultSet.next()) {
Product product = new Product(resultSet.getString(1), resultSet.getString(2), Category.valueOf(resultSet.getString(3)), Color.valueOf(resultSet.getString(4)), resultSet.getDouble(5), Gender.valueOf(resultSet.getString(6).toUpperCase()), getProductSizes(resultSet.getInt(7), resultSet.getInt(8), resultSet.getInt(9), resultSet.getInt(10), resultSet.getInt(11)));
productMap.put(number.incrementAndGet(), product);
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.info("got error while fetching the gender. please try again");
return getProductsByGenderAndCategory(gender, category);
}
if (productMap.isEmpty()) {
logger.info("Products not found in " + category);
} else {
String menu = productMap.entrySet().stream().map(entry -> entry.getKey() + ". " + entry.getValue().productShowcaseInMenu()).reduce("", (products, product) -> products + "\n" + product);
logger.info(menu);
}
return productMap;
}
@Override
public Map<Integer, Product> getProductsByGenderAndColor(Collection<Product> productList, Color color) {
return null;
}
}
package com.retail_store.order_management.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
private static Connection connection;
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/gap";
String userName = "root";
String password = "123mysql143";
if (connection == null) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
}
package com.retail_store.order_management.utils;
import com.retail_store.order_management.constants.Category;
import com.retail_store.order_management.constants.Color;
import com.retail_store.order_management.constants.Gender;
import com.retail_store.order_management.constants.Size;
import com.retail_store.order_management.model.Order;
import com.retail_store.order_management.service.RetailStore;
import java.util.*;
import java.util.logging.Logger;
public class Validate {
protected Logger logger;
protected Scanner scanner;
public Category getCategory(boolean check, String message) {
String categoryOptions = Arrays.stream(Category.values()).map(category -> category + "(" + category.getOption() + ")").reduce((categories, category) -> categories + " " + category).get();
if (check) {
logger.info(message + "\n" + categoryOptions);
}
try {
int option = scanner.nextInt();
return Arrays.stream(Category.values()).filter(category -> category.getOption() == option).findFirst().orElseGet(() -> {
logger.info("Please enter valid category\n" + categoryOptions);
return getCategory(false, message);
});
} catch (InputMismatchException e) {
logger.info("Please enter valid category\n" + categoryOptions);
scanner.reset();
return getCategory(false, message);
} catch (Exception e) {
logger.info(e.getMessage());
scanner.reset();
return getCategory(false, message);
}
}
public Size getSize(boolean check, String message) {
String categoryOptions = Arrays.stream(Size.values()).map(size -> size + "(" + size.getOption() + ")").reduce((sizes, size) -> sizes + " " + size).get();
if (check) {
logger.info(message + "\n" + categoryOptions);
}
try {
int option = scanner.nextInt();
return Arrays.stream(Size.values()).filter(size -> size.getOption() == option).findFirst().orElseGet(() -> {
logger.info("Please enter valid category\n" + categoryOptions);
return getSize(false, message);
});
} catch (InputMismatchException e) {
logger.info("Please enter valid category\n" + categoryOptions);
scanner.reset();
return getSize(false, message);
} catch (Exception e) {
logger.info(e.getMessage());
scanner.reset();
return getSize(false, message);
}
}
public Gender getGender(boolean check, String message) {
String genderOptions = Arrays.stream(Gender.values()).map(category -> category + "(" + category.getOption() + ")").reduce((categories, category) -> categories + " " + category).get();
if (check) {
logger.info(message + "\n" + genderOptions);
}
try {
int option = scanner.nextInt();
return Arrays.stream(Gender.values()).filter(gender -> gender.getOption() == option).findFirst().orElseGet(() -> {
logger.info("Please enter valid gender\n" + genderOptions);
return getGender(false, message);
});
} catch (InputMismatchException e) {
logger.info("Please enter valid gender\n" + genderOptions);
scanner.reset();
return getGender(false, message);
} catch (Exception e) {
logger.warning(e.getMessage());
scanner.reset();
return getGender(false, message);
}
}
public Color getColor(boolean check, String message) {
String colorOptions = Arrays.stream(Color.values()).map(category -> category + "(" + category.getOption() + ")").reduce((categories, category) -> categories + " " + category).get();
if (check) {
logger.info(message + "\n" + colorOptions);
}
try {
int option = scanner.nextInt();
return Arrays.stream(Color.values()).filter(color -> color.getOption() == option).findFirst().orElseGet(() -> {
logger.info("Please enter valid color\n" + colorOptions);
return getColor(false, message);
});
} catch (InputMismatchException e) {
logger.info("Please enter valid color\n" + colorOptions);
scanner.reset();
return getColor(false, message);
} catch (Exception e) {
logger.info(e.getMessage());
scanner.reset();
return getColor(false, message);
}
}
public double getPrice(boolean flag) {
if (flag) {
logger.info("Enter price for the product");
}
try {
return scanner.nextDouble();
} catch (InputMismatchException e) {
logger.warning("Please enter valid price");
scanner.reset();
return getPrice(false);
}
}
public int getCount() {
int count;
try {
count = scanner.nextInt();
if (count < 0) {
throw new RuntimeException();
}
return count;
} catch (Exception e) {
logger.warning("Please enter valid number");
scanner.reset();
return getCount();
}
}
public LinkedHashMap<Size, Integer> getProductSizes() {
LinkedHashMap<Size, Integer> productSizes = new LinkedHashMap<>();
logger.info("Please enter the available stock for particular sizes \n Number of products with size S");
productSizes.put(Size.S, getCount());
logger.info("Number of products with size M");
productSizes.put(Size.M, getCount());
logger.info("Number of products with size L");
productSizes.put(Size.L, getCount());
logger.info("Number of products with size XL");
productSizes.put(Size.XL, getCount());
logger.info("Number of products with size XXL");
productSizes.put(Size.XXL, getCount());
return productSizes;
}
public Map<Size, Integer> getProductSizes(int s, int m, int l, int xl, int xxl) {
LinkedHashMap<Size, Integer> productSizes = new LinkedHashMap<>();
productSizes.put(Size.S, s);
productSizes.put(Size.M, m);
productSizes.put(Size.L, l);
productSizes.put(Size.XL, xl);
productSizes.put(Size.XXL, xxl);
return productSizes;
}
public String productIdGenerator() {
return Arrays.stream(UUID.randomUUID().toString().split("-")).skip(1).findFirst().get() + "#" + RetailStore.class.getSimpleName();
}
public String orderIdGenerator() {
return Arrays.stream(UUID.randomUUID().toString().split("-")).findFirst().get() + "#" + Order.class.getSimpleName();
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment