Search in sources :

Example 21 with Ingredient

use of BasicCommonClasses.Ingredient in project SmartCity-Market by TechnionYP5777.

the class SQLDatabaseConnection method addIngredient.

@Override
public String addIngredient(Integer sessionID, String ingredientName) throws CriticalError, ClientNotConnected {
    log.debug("SQL Public addIngredient: ingredient name: " + ingredientName + " (SESSION: " + sessionID + " )");
    validateSessionEstablished(sessionID);
    int $;
    // START transaction
    connectionStartTransaction();
    try {
        // WRITE part of transaction
        // get "fresh" id for the new ingredient
        $ = allocateIDToTable(IngredientsTable.table, IngredientsTable.ingredientIDCol);
        String insertQuery = new InsertQuery(IngredientsTable.table).addColumn(IngredientsTable.ingredientIDCol, PARAM_MARK).addColumn(IngredientsTable.ingredientNameCol, PARAM_MARK).validate() + "";
        insertQuery.hashCode();
        getParameterizedQuery(insertQuery, $, ingredientName).executeUpdate();
        // END transaction
        connectionCommitTransaction();
    } catch (CriticalError | SQLException e) {
        connectionRollbackTransaction();
        throw new CriticalError();
    } finally {
        connectionEndTransaction();
    }
    return Serialization.serialize(new Ingredient($, ingredientName));
}
Also used : InsertQuery(com.healthmarketscience.sqlbuilder.InsertQuery) SQLException(java.sql.SQLException) Ingredient(BasicCommonClasses.Ingredient)

Example 22 with Ingredient

use of BasicCommonClasses.Ingredient in project SmartCity-Market by TechnionYP5777.

the class CommandExecuter method addNewIngredient.

private void addNewIngredient(SQLDatabaseConnection c) {
    Ingredient ingredient = null;
    String ingredientResult = null;
    log.info("Add new ingredient from serderID " + inCommandWrapper.getSenderID() + " command called");
    try {
        ingredient = Serialization.deserialize(inCommandWrapper.getData(), Ingredient.class);
    } catch (java.lang.RuntimeException e) {
        log.fatal("Failed to parse data for Add New Ingredient command");
        outCommandWrapper = new CommandWrapper(ResultDescriptor.SM_ERR);
        return;
    }
    log.info("Trying to add new ingredient " + ingredient + " to system");
    try {
        ingredientResult = c.addIngredient(inCommandWrapper.getSenderID(), ingredient.getName());
        outCommandWrapper = new CommandWrapper(ResultDescriptor.SM_OK, ingredientResult);
    } catch (CriticalError e) {
        log.fatal("Add new ingredient command failed, critical error occured from SQL Database connection");
        outCommandWrapper = new CommandWrapper(ResultDescriptor.SM_ERR);
    } catch (ClientNotConnected e) {
        log.info("Add new ingredient customer command failed, client is not connected");
        outCommandWrapper = new CommandWrapper(ResultDescriptor.SM_SENDER_IS_NOT_CONNECTED);
    }
    log.info("Add new ingredient " + ingredient + " to system finished");
}
Also used : CriticalError(SQLDatabase.SQLDatabaseException.CriticalError) ClientNotConnected(SQLDatabase.SQLDatabaseException.ClientNotConnected) Ingredient(BasicCommonClasses.Ingredient) CommandWrapper(ClientServerApi.CommandWrapper)

Example 23 with Ingredient

use of BasicCommonClasses.Ingredient in project SmartCity-Market by TechnionYP5777.

the class SQLJsonGenerator method ProductToJson.

/**
	 * convert product from ResultSet to Json representation of product
	 * 
	 * @param product
	 *            - ResultSet of the product\s joined with manufactures table
	 *            (assuming the ResultSet ordered by product barcode) the
	 *            ResultSet need to point to the product to convert). this
	 *            object will point the next product after returning.
	 * @param productIngredients
	 *            - ResultSet of the product\s ingredients (assuming the
	 *            ResultSet ordered by product barcode) the ResultSet should
	 *            pointing the product to convert, if it has ingredients. if so,
	 *            this object will point the next product after returning.
	 * @param productLocations
	 *            - ResultSet of the product\s locations (assuming the ResultSet
	 *            ordered by product barcode) the ResultSet should pointing the
	 *            product to convert, if it has ingredients. if so, this object
	 *            will point the next product after returning.
	 * @return
	 * @throws CriticalError
	 */
static String ProductToJson(ResultSet product, ResultSet productIngredients, ResultSet productLocations) throws CriticalError {
    HashSet<Location> locations;
    HashSet<Ingredient> ingredients;
    try {
        long productBarcode = product.getLong(ProductsCatalogTable.barcodeCol.getColumnNameSQL());
        // adding all ingredients
        ingredients = createIngredientsListByBarcode(productBarcode, productIngredients);
        // adding all locations
        locations = createLocationsList(productBarcode, productLocations);
        // get product other details
        String productManufacturerName = getStringFromResultset(product, ManufacturerTable.manufacturerNameCol);
        int productManufacturerID = product.getInt(ManufacturerTable.manufacturerIDCol.getColumnNameSQL());
        String productDescription = getStringFromResultset(product, ProductsCatalogTable.productDescriptionCol), productName = getStringFromResultset(product, ProductsCatalogTable.productNameCol), productPicture = getStringFromResultset(product, ProductsCatalogTable.productPictureCol);
        double productPrice = product.getDouble(ProductsCatalogTable.productPriceCol.getColumnNameSQL());
        product.next();
        return Serialization.serialize(new CatalogProduct(productBarcode, productName, ingredients, new Manufacturer(productManufacturerID, productManufacturerName), productDescription, productPrice, productPicture, locations));
    } catch (SQLException e) {
        throw new SQLDatabaseException.CriticalError();
    }
}
Also used : SQLException(java.sql.SQLException) CriticalError(SQLDatabase.SQLDatabaseException.CriticalError) CatalogProduct(BasicCommonClasses.CatalogProduct) Ingredient(BasicCommonClasses.Ingredient) Manufacturer(BasicCommonClasses.Manufacturer) Location(BasicCommonClasses.Location)

Example 24 with Ingredient

use of BasicCommonClasses.Ingredient in project SmartCity-Market by TechnionYP5777.

the class SQLDatabaseConnection method setIngredientsForCustomer.

/**
	 * update the ingredients of the user to the ones in the hashset.
	 * 
	 * @param username The username of the customer to update.
	 * @param newSet The new set of ingredients to update to. cannot be null.
	 * @throws CriticalError
	 */
private void setIngredientsForCustomer(String username, HashSet<Ingredient> newSet) throws CriticalError {
    PreparedStatement statement = null;
    try {
        //remove the old list of ingredients
        String deleteIngredientsQuery = generateDeleteQuery(CustomersIngredientsTable.table, BinaryCondition.equalTo(CustomersIngredientsTable.customerUsernameCol, PARAM_MARK));
        statement = getParameterizedQuery(deleteIngredientsQuery, username);
        log.debug("updateIngredientsForCustomer: removing old ingredients of customer: " + username + "\nby running query: " + statement);
        statement.executeUpdate();
        closeResources(statement);
        for (Ingredient ingredient : newSet) {
            //add new ingredients 
            String insertIngredientQuery = new InsertQuery(CustomersIngredientsTable.table).addColumn(CustomersIngredientsTable.customerUsernameCol, PARAM_MARK).addColumn(CustomersIngredientsTable.ingredientIDCol, PARAM_MARK).validate() + "";
            statement = getParameterizedQuery(insertIngredientQuery, username, ingredient.getId());
            log.debug("updateIngredientsForCustomer: add igredient: " + ingredient + " to customer: " + username + "\nby running query: statement");
            statement.executeUpdate();
            closeResources(statement);
        }
    } catch (SQLException e) {
        throw new CriticalError();
    } finally {
        closeResources(statement);
    }
}
Also used : InsertQuery(com.healthmarketscience.sqlbuilder.InsertQuery) Ingredient(BasicCommonClasses.Ingredient) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement)

Example 25 with Ingredient

use of BasicCommonClasses.Ingredient in project SmartCity-Market by TechnionYP5777.

the class Customer method getAllIngredients.

@Override
public List<Ingredient> getAllIngredients() throws CriticalError {
    String serverResponse;
    log.info("Creating getAllIngredients command wrapper");
    establishCommunication(CustomerDefs.port, CustomerDefs.host, CustomerDefs.timeout);
    /* first: getting the product from the server */
    try {
        serverResponse = sendRequestWithRespondToServer(new CommandWrapper(id, CommandDescriptor.GET_ALL_INGREDIENTS).serialize());
    } catch (SocketTimeoutException e) {
        log.fatal("Critical bug: failed to get respond from server");
        throw new CriticalError();
    }
    terminateCommunication();
    CommandWrapper commandWrapper = getCommandWrapper(serverResponse);
    try {
        resultDescriptorHandler(commandWrapper.getResultDescriptor());
    } catch (InvalidCommandDescriptor | CriticalError | AmountBiggerThanAvailable | ProductPackageDoesNotExist | GroceryListIsEmpty | AuthenticationError | CustomerNotConnected | ProductCatalogDoesNotExist | InvalidParameter | UsernameAlreadyExists | ForgotPasswordWrongAnswer ยข) {
        log.fatal("Critical bug: this command result isn't supposed to return here");
        throw new CriticalError();
    }
    log.info("getAllIngredients command succeed.");
    return new Gson().fromJson(commandWrapper.getData(), new TypeToken<List<Ingredient>>() {
    }.getType());
}
Also used : AuthenticationError(CustomerContracts.ACustomerExceptions.AuthenticationError) CriticalError(SMExceptions.CommonExceptions.CriticalError) CustomerNotConnected(CustomerContracts.ACustomerExceptions.CustomerNotConnected) Gson(com.google.gson.Gson) CommandWrapper(ClientServerApi.CommandWrapper) GroceryListIsEmpty(CustomerContracts.ACustomerExceptions.GroceryListIsEmpty) InvalidParameter(CustomerContracts.ACustomerExceptions.InvalidParameter) SocketTimeoutException(java.net.SocketTimeoutException) AmountBiggerThanAvailable(CustomerContracts.ACustomerExceptions.AmountBiggerThanAvailable) Ingredient(BasicCommonClasses.Ingredient) InvalidCommandDescriptor(CustomerContracts.ACustomerExceptions.InvalidCommandDescriptor) TypeToken(com.google.gson.reflect.TypeToken) ForgotPasswordWrongAnswer(CustomerContracts.ACustomerExceptions.ForgotPasswordWrongAnswer) ProductPackageDoesNotExist(CustomerContracts.ACustomerExceptions.ProductPackageDoesNotExist) UsernameAlreadyExists(CustomerContracts.ACustomerExceptions.UsernameAlreadyExists) ProductCatalogDoesNotExist(CustomerContracts.ACustomerExceptions.ProductCatalogDoesNotExist)

Aggregations

Ingredient (BasicCommonClasses.Ingredient)27 CriticalError (SQLDatabase.SQLDatabaseException.CriticalError)14 ClientNotConnected (SQLDatabase.SQLDatabaseException.ClientNotConnected)11 Test (org.junit.Test)9 SQLDatabaseConnection (SQLDatabase.SQLDatabaseConnection)8 Location (BasicCommonClasses.Location)6 Manufacturer (BasicCommonClasses.Manufacturer)6 CommandWrapper (ClientServerApi.CommandWrapper)6 IngredientNotExist (SQLDatabase.SQLDatabaseException.IngredientNotExist)6 Gson (com.google.gson.Gson)6 CatalogProduct (BasicCommonClasses.CatalogProduct)5 CriticalError (SMExceptions.CommonExceptions.CriticalError)5 HashSet (java.util.HashSet)5 EmployeeNotConnected (EmployeeDefs.AEmployeeException.EmployeeNotConnected)4 IngredientStillUsed (SQLDatabase.SQLDatabaseException.IngredientStillUsed)4 SQLException (java.sql.SQLException)4 ConnectionFailure (EmployeeDefs.AEmployeeException.ConnectionFailure)3 InvalidParameter (EmployeeDefs.AEmployeeException.InvalidParameter)3 ParamIDAlreadyExists (EmployeeDefs.AEmployeeException.ParamIDAlreadyExists)3 ParamIDDoesNotExist (EmployeeDefs.AEmployeeException.ParamIDDoesNotExist)3