Posts

Showing posts from 2017

Task 16 - Javafx Program to Create, Retrieve, Update and Delete records with Database

Image
Your database name must be cuonline and table name users.  Must create users table using below schema: CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(100) DEFAULT NULL, `password` varchar(45) DEFAULT NULL, `city` varchar(100) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, `subjects` varchar(255) DEFAULT NULL, `gender` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 See the above given figure and try to understand what the application intend to do. Implement at least following features: Develop above layout and form. When user fill the form and press Add User button, add new user record in users table as per information filled in the form. Once user is added, update the list shown at lift side. When user click the "Update" button, show a form with an text input field for user ID and a "Show Update Form" button, whe...

Task 15 - Java Database Connectivity with MySQL - Assignment 3, Section A

Image
Assume ‘infosys’ database contains 3 tables i.e. products, product_categories and sales. You can  download the SQL file  to create above database, tables and to insert some records for testing purpose. Make a java class having following static methods (class name shall be your registration number and name): static void updateProductNameAndStatus(int productID, String newName, boolean newStatus) static int getAverageSalePrice(int productID) static ArrayList<String> getProductsNames(int categoryID, String searchQueryString)

Task 14 - Java Database Connectivity with MySQL - Assignment 3, Section B

Image
Assume ‘infosys’ database contains 3 tables i.e. products, product_categories and sales. Column name and data type of each column is shown in below diagram: You can download the SQL file  to create above database, tables and to insert some records for testing purpose. Make a java class having following static methods (class name shall be your registration number and name): static void updateSalePrice(int productID, int invoiceID, double newUnitPrice) static int getTotalSalesBySalemanID(int salemanID) static ArrayList<String> getProductsNamesByInvoiceID(int invoiceID) updateSalePrice shall update the unit price in sales table for the records where invoice ID and productID (passed as argument) matches. getTotalSalesBySalemanID shall return the total sales made by the saleman whose ID is passed as argument. getProductsNamesByInvoiceID shall return the list of products’ names that were sold under the invoiceID passed as argument. Definition of main method is give...

Task 13 - Java JDBC and Basic SQL Practice Exercise

Download SQL script file . Connect MySQL Workbench with MySQL Database server. In Workbench, choose menu: File > Open SQL Script option and select the downloaded file. Run the script to create a database of two tables i.e. products and product_categories. You can open the script in Notepad++ to anaylyze, it contains SQL statements to create database, tables and few insert statement to add some seed data. Write Java application that shall provide following features: Show all categories names with products count of that category e.g. Mobiles - 2 Show list of categories (id and name only) to user to choose a category id by user input. Show product id, name, description, minimum stock level and cost of all products that belongs to the given category id. Show average cost of products the store sell. Show products order by category. Show products where minimum stock level is between 50 and 300 (inclusive). Let user search the products by entering a string and show all products...

Java JDBC CRUD Example with MySQL

Below are the Java code samples that uses Java Database Connectivity API (JDBC) to Create, Retrieve, Update and Delete records using MySQL databases. Before running below examples, you must add Connector/J i.e. MySQL Database driver in your classpath, Click Here to Download Connector/J . I have created a database named cuonline that contains a 'students' table. The SQL statement to create the table is given below: CREATE TABLE `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, `email` varchar(45) DEFAULT NULL, `gender` varchar(45) DEFAULT NULL, `status` tinyint(4) DEFAULT NULL, `city` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1; You noticed, id column is set as 'auto-increment', so it would be automatically initialized if we do not pass its value while inserting new records. For each record, database would increment the value by one while i...

Task 12 - Create Java Program with MySQL Database Connectivity

There are 3 parts of this assignment or programming task. Part 1: Understand Database Server, Client and SQL In MySQL Server, create a database "infosys" that shall have "users" table, using MySQL. The table shall have id, name, gender, phone and status field of type int, varchar, varchar, varchar and boolean/tinyint respectively. After creating the table, do following: Add 4-5 records using MySQL Workbench Retrieve all (using GUI) or selected records and columns from the table using GUI and SQL Delete records, single and multiple using GUI and SQL Update records' different fields using GUI and SQL If you have not attended database introduction or database connectivity lectures. You can watch here: Database Introduction   Database Connectivity Do not start Part 2, until you are comfortable with running CRUD queries from Java program. _____________________________ Part 2: Its continuation of Task 10 . I have also uploaded the solution on this...

Java Interfaces and Exception Handling - Practice Problem with Solution

Problem Statement: Create a UserService Interface with following methods signatures. void addUser(User user) throws UserAlreadyExistException User getUser(int userID) throws UserAccountIsBlockedException void updateUser(User user) void deleteUser(int userID) void unblockUser(int userID) ArrayList getAllUsers() Define InMemoryUserService class that shall implement UserService interface. In InMemoryUserService class, use User ArrayList for storage of user objects.  The methods shall change/read this list to perform the required operations. Test all methods from UserTest class. Getting information from user input is encourged but optional. Define and properly encapsulate atleast id, name and status instance attributes in User class of type int , String and boolean . How you check whether a user account is blocked? If status attribute is false, it means user account is blocked. True represent the account is active. UserAlreadyExistException exception shall be thrown if...

Abstraction in Java with Example Program

You must understand  Polymorphism with example , before you get into details of abstraction. Abstraction means, skipping implementation details of behavior by expressing an entity in a generic way, leaving details to be defined by subclasses. In simple words, we define classes that contain only method prototypes but not the body of the methods, the methods' body is defined by subclasses. This approach help to process objects of subclasses polymorphically. In Java, abstraction is achieved using abstract classes and interfaces. In real life, when we plan something, first we think in terms of what needs to be done, then we go into details of how  it should be done. In same way, in abstraction, we think, what behavior an entity should have and only declare that behavior (but not define it). Then, in each specific concept (or subclass), we define that behavior i.e. 'how' a specific class should act. For example, consider a student in academic system, identify common beha...

Polymorphism in Java with Example Program

Image
Before I explain polymorphism, you must understand what is generalization and specialization in context of object oriented design. Assume following classes exist in an inheritance hierarchy: Object LivingBeing Animal Pet Cat Generalization and Specialization  Assume classes are defined in a way such that, Cat extends Pet, Pet extends Animal and so on ... upto Object. You see, classes are upper side of inheritance hierarchy refers to more generic concepts as compared to classes in bottom side of hierarchy, hence the term generalization. If we look at classes defined in lower side of the hierarchy, these are more specific entities. So we say, Cat is more specific entity compared to Pet (or Pet is generic and Cat is specific). In same way, Pet is more specific compared to Animal, Animal is specific compared to LivingBeing. So, if we view classes from top to bottom of the hierarchy, we move from generalization to specialization (or from generic to specific entity). General...

Task 6b - ArrayList Practice Task

Last Updated On: Nov. 17, 2020 Note: You shall try to complete below listed features. On next Thursday (Nov. 26), during online class, as Assignment 2, I would request you to add 1-2 more features in UserService class or in main method of UserServiceTest and submit me the code. To do that, you shall do this task yourself. Otherwise, you may not be able to even understand the problem statement of Assignment 2. Only the functionality implemented live would be checked, below task is just for practice and has no marks. You can ask any question to do this task during online session, because its not a weighted task. ____ Develop a menu driven application that shall allow user to choose different option numbers to add , search , update and delete users in an ArrayList object. Make a UserService class and implement different methods to perform each operation. These methods shall be called from main metod of  UserServiceTest class. The ArrayList shall be defined as private instance variabl...

Task 6a - Enums

Last Updated on: Nov. 17, 2020 6a.1 Define two enum, first for Gender and another for Month. Gender shall be enumeration of two values i.e. Male and Female. Month enum shall be defined with January, February, ... up to December as values. Month enum shall also store the number of days of each month. Define a User that shall be composed of id, name, gender and birthMonth attributes. Use above created enums for gender and birthMonth fields. Create a User object and initialize it from user input, gender shall be initialized in constructor and birthMonth shall be initialzed using set methed. After the object is initialized, print all fields' values of user object. Also print the number of days of birthMonth. ___________ 6a.2 Define EnumTest class, in main method: Iterate the Month enum (created in 6a.1) to print all months' names, ordinal value, and number of days of each month. Also iterate the Month enum to print a subset of months e.g. from Sep. to Dec. Create sub list of Month ...

How to Search Tweets using Twitter4j Java API

Image
In a recent SEO related project, I used Twitter4J Java API to download 3 million plus tweets. Below is the proof of concept code. There are only three major steps: 1. Download the latest Twitter4J JAR file from http://twitter4j.org/en/  and add into your project library or class path. 2. Create Twitter App by visting https://apps.twitter.com/ Click Create New App button and fill the form by providing app name, URL and app brief description and submit clicking on "Create New Twitter Applicaton" button. Once the application is created, click the application name on dashboard and go to Key and Access Toekn tab. There would see Consumer Key (API Key), Consumer Secret (API Secret). Click on Generate Access Token and Token secret button, it would generate Access Token and Access Token Secret. These 4 things are what you need when making the API call. 3. Just use below code, as-is, it shall fetch the tweets. Modify the code as per your requirements. Its self...

Java Program that Purchases a Computer from Datacenter in London and Install Ubuntu using Linode API

Image
Amazon AWS, Digital Ocean and Linode are well known cloud platform, infrastructure and other services providers. Below I explain how we can write a Java program that buys a computer from Linode London Datacenter, install Ubuntu OS and put it ON. Definitely, you can choose your datacenter of choice among following: Dallas, Fremont, Tokyo, London, Singapore, Frankfurt. I have selected London. Linode provide RESTful services to create and manage different resources e.g. linux box aka Linode, node balancers, setting DNS, IPs, Backup, Storage and scalling system resources. Below program use Linode RESTful API via official wrapper Java API. Lets move step by step: First of all, you must create an account at Linode.com. Login into your account, go to My Profile > API Keys and click on Create New API key. Note it down, we need it to make API calls. Download the Linode official Java API from  https://github.com/synapticloop/linode-api and add the linode-api.jar and runtime dependencie...

Assignment 4 - Point of Sale system

Develop a limited version of Point of Sale system. You have seen it already, its what a salesman use at medical or deparmentsal stores to make invoices. Making complete system is difficult at this level and need more time than we are left with. So build only following functionalities: (I recommend to save all data in MySQL database, DB lecture links already shared at FB Group, you can also use binay files, if you feel not comfortable with using MySQL after watching video lectures). Customers CRUD (Create, Retrieve, Update, Delete) and List functionality using Java GUI. Customer table and class shall have: id, name, email, gender, active, city, cellNumber Create means (provide short key: Ctrl+N), provide a JFrame based form to add new customer.  List means, show all customers ID-Name in JList, so that user could select the customer to perfrom Update, Show/Retrieve or Delete operation.  Update means, user shall be able to update the customer record. He shall select the custome...

Task 11: Java GUI Basics

Task 11.1: Make a form that shall look like this: Name: _____________ (Text field) Email: _____________ Gender: o Male    o Female   (radio button) Subjects: o OOP  o DB  o Web  o Android  o Machine Learning   [Check boxes]                 [ Submit ]            (submit button) Make a class User with name, email, gender and subjects instance attributes of type String, String, Boolean, and ArrayList<String>. When user fill above form and press the submit button, make an object of User using the form data and save that object on file using Serialization. When user run the program again, if user has saved the user object earlier, load the form with user existing data (explore some functions of Swing components using API docs and Googling). ~~~~~~~~~~~~~~~ Task 12 would be Assignment 4 and would be little complex using Swing programming. So make sure you have done task 11.

Task 10b - Interfaces and Exception Handling in Java

Create a UserService Interface with following methods. void addUser(User user) void updateUser(User user) void deleteUser(int userID) User getUser(int userID) void unblockUser(int userID) void blockUser(int userID) ArrayList<User> getAllUsers() Define InMemoryUserService class that shall implement UserService contract or interface. Use ArrayList for storage, update and retrieve operations inside InMemoryUserService i.e. you shall define a static attribute ArrayList<User> users = new ArrayList<>(); The implemented methods shall change/read this list to perform the required operation.  Test all methods from UserTest class. Getting information from user input is encourged but optional.  Define at least id, name, and status instsance attributes in User class of type int, String and Boolean. How you check whether a user account is blocked? If status attribute is false, it means user account is blocked. True represent the account is active. Make ...

Task 9 - Polymorphism in Java

9.1:  Make Circle , Rectangle , Square and Triangle classes that extends Shape.  Shape has color attribute and an abstract double calcArea() method. Circle has radius attribute. Triangle has base and height. Rectangle has length and width.  Square have only one attribute i.e. size (to represent width and height both, as both are same in case of square). In ShapeTest class's main method, ask the user how many shapes he want to create. Then, ask the type of each shape, then get the required data to instantiate that shape object. Keep putting each shape in ArrayList of type Shape . e.g. How many shapes you want to create: 4 Choose 1st Shape type: Press 1, to create Circle Press 2, to create Rectangle Press 3 to create Triangle Press 4 to create Square >1 Enter the radius of circle: > 5 .... .... Then outside the loop, display following information: Sum of area of each shape type  Total shapes of each shape type Total cost to paint each shape type  Cost t...

Task 8 - OOP Assignment 2 - Inheritance + Arrays

Image
Create a class Game with start, stop, restart methods. Define two protected attributes to store player 1 and player 2 names. Methods shall overridden by subclasses of Game class. Subclass shall decide what shall be written in the body of these methods depending on the particular game logic. Create a class TicTacToe, a subclass of Game, that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enum type to represent the value in each cell of the array. The enum’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X in the specified square, and place an O wherever the second player moves. You can get coordinates from each user to place X or 0. Each move must be to an empty square. If user a position that is already occupi...

Task 7 - Inheritance in Java

Last Updated on Nov. 26, 2020 Program 7.1  (With reference to Employee inheritance hierarchy, given in Chapter 9 of our reference book) You studied an inheritance hierarchy in which the class BasePlusCommissionEmployee inherited from class CommissionEmployee. However, not all types of employees are CommissionEmployees. In this exercise, you shall create a more general Employee superclass that factors out the attributes and behaviors in class CommissionEmployee that are common to all Employees. The common attributes and behaviors for all Employees are firstName, lastName, CNIC, getFirstName, getLastName, getCNIC and a portion of method toString. Create a new superclass Employee that contains these instance variables and methods and a constructor. Next, rewrite the class CommissionEmployee from Section 9.4.5 as a subclass of Employee. Class CommissionEmployee should contain only the instance variables and methods that are not declared in its parent type. Class CommissionEmployee’s co...

Apache Solr - Running Search Query

Image
By now, we have indexed sample data  of books.csv that comes with Solr. Lets see how to run Search Query in books data. Running Queries on Solr Open Solr Admin UI in a browser using http://localhost:8983 and choose the core1 under "Core Selector" dropdown list on left nav bar. You can see the number of total documents index by that core in right section of the page, as below: To run search query on core1 , choose the query link at left menu, you would a query builder UI, as below. Figure 2: Setting Search Query Admin UI, see Figure 2, provides user friendly way to build search query. Solr Admin passes all specified parameters to Solr API and shows the results return by the API on right section of the page. Solr Admin Query component is good tool to test search queries before we integrate them in our applications. If you leave all options to their default values and click "Execute Query" button, Solr would return the below JSON. You see, its same da...