diff --git a/.gitignore b/.gitignore index 8399968..925de21 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -**/*.class \ No newline at end of file +**/*.class +/mod4/FirstMavenProject/target/ diff --git a/console.sql b/console.sql new file mode 100644 index 0000000..f794a1a --- /dev/null +++ b/console.sql @@ -0,0 +1 @@ +select * from Book \ No newline at end of file diff --git a/mod2/hopenlop aka simple java I O/.vscode/settings.json b/mod2/Class roster/.vscode/settings.json similarity index 100% rename from mod2/hopenlop aka simple java I O/.vscode/settings.json rename to mod2/Class roster/.vscode/settings.json diff --git a/mod2/Class roster/Class roster.jar b/mod2/Class roster/Class roster.jar new file mode 100644 index 0000000..f7fcf3b Binary files /dev/null and b/mod2/Class roster/Class roster.jar differ diff --git a/mod2/hopenlop aka simple java I O/README.md b/mod2/Class roster/README.md similarity index 100% rename from mod2/hopenlop aka simple java I O/README.md rename to mod2/Class roster/README.md diff --git a/mod2/Class roster/audit.txt b/mod2/Class roster/audit.txt new file mode 100644 index 0000000..1c3a22a --- /dev/null +++ b/mod2/Class roster/audit.txt @@ -0,0 +1,11 @@ +2022-05-09T20:00:54.681710 : Student 1111 CREATED. +2022-05-10T08:32:30.927770 : ||||||||||||||| Sucesfull: start runing program ||||||||||||||| +2022-05-10T08:32:54.832127 : Student 1111 REMOVED. +2022-05-10T08:47:44.467095 : ||||||||||||||| Sucesfull: start runing program ||||||||||||||| +2022-05-10T08:48:25.732196 : Student 1111 REMOVED. +2022-05-10T08:49:19.643601 : Student 1112 CREATED. +2022-05-10T08:49:26.906286 : Student 1111 REMOVED. +2022-05-10T08:49:37.850037 : ||||||||||||||| Sucesfull: stop program ||||||||||||||| +2022-05-11T10:36:21.716903 : ||||||||||||||| Sucesfull: start runing program ||||||||||||||| +2022-05-11T10:36:34.449032 : Student 1111 REMOVED. +2022-05-11T10:36:43.859600 : ||||||||||||||| Sucesfull: stop program ||||||||||||||| diff --git a/mod2/Class roster/roster.txt b/mod2/Class roster/roster.txt new file mode 100644 index 0000000..33f6905 --- /dev/null +++ b/mod2/Class roster/roster.txt @@ -0,0 +1 @@ +1112::bhima::raisz::java 2021-2025 diff --git a/mod2/Class roster/src/App.java b/mod2/Class roster/src/App.java new file mode 100644 index 0000000..9cc3420 --- /dev/null +++ b/mod2/Class roster/src/App.java @@ -0,0 +1,29 @@ +import IO.ClassRosterView; +import IO.Console; +import audit.ClassRosterAuditDaoFileImpl; +import controller.ClassRosterControl; +import dao.ClassRosterDaoFileImpl; +import interfaces.ClassRosterAuditDao; +import interfaces.ClassRosterDao; +import interfaces.ClassRosterServiceLayer; +import interfaces.ConsoleIo; +import serviceLayer.ClassRosterServiceLayerFileImpl; + +public class App { + public static void main(String[] args) throws Exception { + // Instantiate the UserIO implementation + ConsoleIo myIo = new Console(); + // Instantiate the View and wire the UserIO implementation into it + ClassRosterView myView = new ClassRosterView(myIo); + // Instantiate the DAO + ClassRosterDao myDao = new ClassRosterDaoFileImpl(); + // Instantiate the Audit DAO + ClassRosterAuditDao myAuditDao = new ClassRosterAuditDaoFileImpl(); + // Instantiate the Service Layer and wire the DAO and Audit DAO into it + ClassRosterServiceLayer myService = new ClassRosterServiceLayerFileImpl(myDao, myAuditDao); + // Instantiate the Controller and wire the Service Layer into it + ClassRosterControl controller = new ClassRosterControl(myService, myView); + // Kick off the Controller + controller.run(); + } +} diff --git a/mod2/Class roster/src/IO/ClassRosterView.java b/mod2/Class roster/src/IO/ClassRosterView.java new file mode 100644 index 0000000..4476f0d --- /dev/null +++ b/mod2/Class roster/src/IO/ClassRosterView.java @@ -0,0 +1,100 @@ +package IO; + +import java.util.List; + +import interfaces.ConsoleIo; +import model.Student; + +public class ClassRosterView { + ConsoleIo io; + + public ClassRosterView(ConsoleIo io) { + this.io = io; + } + + public int printMenuAndGetSelection() { + io.print("Main Menu"); + io.print("1. List Student IDs"); + io.print("2. Create New Student"); + io.print("3. View a Student"); + io.print("4. Remove a Student"); + io.print("5. Exit"); + + return io.readInt("Please select from the above choices.", 1, 5); + } + + public Student getNewStudentInfo() { + String studentId = io.readString("Please enter Student ID"); + String firstName = io.readString("Please enter First Name"); + String lastName = io.readString("Please enter Last Name"); + String cohort = io.readString("Please enter Cohort"); + Student currentStudent = new Student(studentId); + currentStudent.setFirstName(firstName); + currentStudent.setLastName(lastName); + currentStudent.setCohort(cohort); + return currentStudent; + } + + public void displayCreateStudentBanner() { + io.print("=== Create Student ==="); + } + + public void displayCreateSuccessBanner() { + io.readString( + "Student successfully created. Please hit enter to continue"); + } + + public void displayStudentList(List studentList) { + for (Student currentStudent : studentList) { + io.print(currentStudent.getStudentId() + ": " + + currentStudent.getFirstName() + " " + + currentStudent.getLastName()); + } + io.readString("Please hit enter to continue."); + } + + public void displayDisplayAllBanner() { + io.print("=== Display All Students ==="); + } + + public void displayDisplayStudentBanner() { + io.print("=== Display Student ==="); + } + + public String getStudentIdChoice() { + return io.readString("Please enter the Student ID."); + } + + public void displayStudent(Student student) { + if (student != null) { + io.print(student.getStudentId()); + io.print(student.getFirstName() + " " + student.getLastName()); + io.print(student.getCohort()); + io.print(""); + } else { + io.print("No such student."); + } + io.readString("Please hit enter to continue."); + } + + public void displayRemoveStudentBanner() { + io.print("=== Remove Student ==="); + } + + public void displayRemoveSuccessBanner() { + io.readString("Student successfully removed. Please hit enter to continue."); + } + + public void displayExitBanner() { + io.print("Good Bye!!!"); + } + + public void displayUnknownCommandBanner() { + io.print("Unknown Command!!!"); + } + + public void displayErrorMessage(String errorMsg) { + io.print("=== ERROR ==="); + io.print(errorMsg); + } +} diff --git a/mod2/Class roster/src/IO/Console.java b/mod2/Class roster/src/IO/Console.java new file mode 100644 index 0000000..3a7ac0c --- /dev/null +++ b/mod2/Class roster/src/IO/Console.java @@ -0,0 +1,173 @@ +package IO; + +import java.util.Scanner; + +import interfaces.ConsoleIo; + +public class Console implements ConsoleIo { + private Scanner sc = new Scanner(System.in); + + @Override + public int readInt(String prompt) { + boolean isCorrect = false; + int value = 0; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Integer.parseInt(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("that was not a number please try again"); + } + } + return value; + } + + @Override + public int readInt(String prompt, int min, int max) { + boolean isCorrect = false; + int value; + do { + value = this.readInt(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public float readFloat(String prompt) { + boolean isCorrect = false; + float value = 0; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Float.parseFloat(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("that was not a number please try again"); + } + } + return value; + } + + @Override + public float readFloat(String prompt, float min, float max) { + boolean isCorrect = false; + float value; + do { + value = this.readFloat(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public double readDouble(String prompt) { + boolean isCorrect = false; + double value = 0; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Double.parseDouble(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("That was not a double. Please try again"); + } + } + return value; + } + + @Override + public double readDouble(String prompt, Double min, Double max) { + boolean isCorrect = false; + double value; + do { + value = this.readDouble(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public boolean readboolean(String prompt) { + boolean isCorrect = false; + boolean value = false; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Boolean.parseBoolean(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("That was not a boolean. Please try again"); + } + } + return value; + } + + @Override + public long readLong(String prompt) { + boolean isCorrect = false; + String userInput; + long value = 0; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Long.parseLong(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("That was not a double. Please try again"); + } + } + return value; + } + + public long readLong(String prompt, long min, long max) { + boolean isCorrect = false; + long value; + do { + value = this.readLong(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public String readString(String prompt) { + this.print(prompt); + return this.sc.nextLine(); + } + + @Override + public void print(String msg) { + System.out.println(msg); + + } +} diff --git a/mod2/Class roster/src/audit/ClassRosterAuditDaoFileImpl.java b/mod2/Class roster/src/audit/ClassRosterAuditDaoFileImpl.java new file mode 100644 index 0000000..00dccfb --- /dev/null +++ b/mod2/Class roster/src/audit/ClassRosterAuditDaoFileImpl.java @@ -0,0 +1,30 @@ +package audit; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.time.LocalDateTime; + +import exceptions.ClassRosterPersistenceException; +import interfaces.ClassRosterAuditDao; + +public class ClassRosterAuditDaoFileImpl implements ClassRosterAuditDao { + + public static final String AUDIT_FILE = "audit.txt"; + + @Override + public void writeAuditEntry(String entry) throws ClassRosterPersistenceException { + PrintWriter out; + + try { + out = new PrintWriter(new FileWriter(AUDIT_FILE, true)); + } catch (IOException e) { + throw new ClassRosterPersistenceException("Could not persist audit information.", e); + } + + LocalDateTime timestamp = LocalDateTime.now(); + out.println(timestamp.toString() + " : " + entry); + out.flush(); + } + +} diff --git a/mod2/Class roster/src/controller/ClassRosterControl.java b/mod2/Class roster/src/controller/ClassRosterControl.java new file mode 100644 index 0000000..61dabde --- /dev/null +++ b/mod2/Class roster/src/controller/ClassRosterControl.java @@ -0,0 +1,110 @@ +package controller; + +import java.util.List; + +import IO.ClassRosterView; +import exceptions.ClassRosterDataValidationException; +import exceptions.ClassRosterDuplicateIdException; +import exceptions.ClassRosterPersistenceException; +import interfaces.ClassRosterServiceLayer; +import model.Student; + +public class ClassRosterControl { + private ClassRosterView view; + private ClassRosterServiceLayer service; + ClassRosterPersistenceException e; + + public ClassRosterControl(ClassRosterServiceLayer service, ClassRosterView view) { + this.service = service; + this.view = view; + } + + /** + * runs program + */ + public void run() { + boolean keepGoing = true; + int menuSelection = 0; + try { + this.service.run(); + while (keepGoing) { + + menuSelection = getMenuSelection(); + + switch (menuSelection) { + case 1: + listStudents(); + break; + case 2: + createStudent(); + break; + case 3: + viewStudent(); + break; + case 4: + removeStudent(); + break; + case 5: + keepGoing = false; + service.stopProgram(); + break; + default: + unknownCommand(); + } + + } + exitMessage(); + } catch (ClassRosterPersistenceException | ClassRosterDataValidationException | ClassRosterDuplicateIdException e) { + view.displayErrorMessage(e.getMessage()); + } + } + + private int getMenuSelection() { + return view.printMenuAndGetSelection(); + } + + private void createStudent() throws ClassRosterPersistenceException, ClassRosterDataValidationException, + ClassRosterDuplicateIdException { + view.displayCreateStudentBanner(); + boolean hasErrors = false; + do { + Student currentStudent = view.getNewStudentInfo(); + try { + service.createStudent(currentStudent); + view.displayCreateSuccessBanner(); + hasErrors = false; + } catch (ClassRosterDuplicateIdException | ClassRosterDataValidationException e) { + hasErrors = true; + view.displayErrorMessage(e.getMessage()); + } + } while (hasErrors); + } + + private void listStudents() throws ClassRosterPersistenceException { + view.displayDisplayAllBanner(); + List studentList = service.getAllStudents(); + view.displayStudentList(studentList); + } + + private void viewStudent() throws ClassRosterPersistenceException { + view.displayDisplayStudentBanner(); + String studentId = view.getStudentIdChoice(); + Student student = service.getStudent(studentId); + view.displayStudent(student); + } + + private void removeStudent() throws ClassRosterPersistenceException { + view.displayRemoveStudentBanner(); + String studentId = view.getStudentIdChoice(); + service.removeStudent(studentId); + view.displayRemoveSuccessBanner(); + } + + private void unknownCommand() { + view.displayUnknownCommandBanner(); + } + + private void exitMessage() { + view.displayExitBanner(); + } +} diff --git a/mod2/Class roster/src/dao/ClassRosterDaoFileImpl.java b/mod2/Class roster/src/dao/ClassRosterDaoFileImpl.java new file mode 100644 index 0000000..e304f63 --- /dev/null +++ b/mod2/Class roster/src/dao/ClassRosterDaoFileImpl.java @@ -0,0 +1,160 @@ +package dao; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import exceptions.ClassRosterPersistenceException; +import interfaces.ClassRosterDao; +import model.Student; + +public class ClassRosterDaoFileImpl implements ClassRosterDao { + private Map students = new HashMap<>(); + public static final String ROSTER_FILE = "roster.txt"; + public static final String DELIMITER = "::"; + + @Override + public Student addStudent(String studentId, Student student) throws ClassRosterPersistenceException { + Student newStudent = students.put(studentId, student); + writeRoster(); + return newStudent; + } + + @Override + public List getAllStudents() throws ClassRosterPersistenceException { + loadRoster(); + return new ArrayList(students.values()); + } + + @Override + public Student getStudent(String studentId) throws ClassRosterPersistenceException { + + return students.get(studentId); + } + + @Override + public Student removeStudent(String studentId) throws ClassRosterPersistenceException { + Student removedStudent = students.remove(studentId); + this.writeRoster(); + return removedStudent; + } + + @Override + public void run() throws ClassRosterPersistenceException { + this.loadRoster(); + } + + @Override + public void stopProgram() throws ClassRosterPersistenceException { + this.writeRoster(); + } + + /** + * reads all students from file + * preferably at startup + * + * @throws ClassRosterPersistenceException if an error occurs wile reading the + * file + */ + private void loadRoster() throws ClassRosterPersistenceException { + Scanner scanner; + + try { + // Create Scanner for reading the file + scanner = new Scanner( + new BufferedReader( + new FileReader(ROSTER_FILE))); + } catch (FileNotFoundException e) { + throw new ClassRosterPersistenceException( + "-_- Could not load roster data into memory.", e); + } + // currentLine holds the most recent line read from the file + String currentLine; + // currentTokens holds each of the parts of the currentLine after it has + // been split on our DELIMITER + // NOTE FOR APPRENTICES: In our case we use :: as our delimiter. If + // currentLine looks like this: + // 1234::Joe::Smith::Java-September2013 + // then currentTokens will be a string array that looks like this: + // + // ___________________________________ + // | | | | | + // |1234|Joe|Smith|Java-September2013| + // | | | | | + // ----------------------------------- + // [0] [1] [2] [3] + String[] currentTokens; + // Go through ROSTER_FILE line by line, decoding each line into a + // Student object. + // Process while we have more lines in the file + while (scanner.hasNextLine()) { + // get the next line in the file + currentLine = scanner.nextLine(); + // break up the line into tokens + currentTokens = currentLine.split(DELIMITER); + // Create a new Student object and put it into the map of students + // NOTE FOR APPRENTICES: We are going to use the student id + // which is currentTokens[0] as the map key for our student object. + // We also have to pass the student id into the Student constructor + Student currentStudent = new Student(currentTokens[0]); + // Set the remaining vlaues on currentStudent manually + currentStudent.setFirstName(currentTokens[1]); + currentStudent.setLastName(currentTokens[2]); + currentStudent.setCohort(currentTokens[3]); + + // Put currentStudent into the map using studentID as the key + students.put(currentStudent.getStudentId(), currentStudent); + } + // close scanner + scanner.close(); + } + + /** + * Writes all students in the roster out to a ROSTER_FILE. See loadRoster + * for file format. + * + * @throws ClassRosterPersistenceException if an error occurs writing to the + * file + */ + private void writeRoster() throws ClassRosterPersistenceException { + // NOTE FOR APPRENTICES: We are not handling the IOException - but + // we are translating it to an application specific exception and + // then simple throwing it (i.e. 'reporting' it) to the code that + // called us. It is the responsibility of the calling code to + // handle any errors that occur. + PrintWriter out; + + try { + out = new PrintWriter(new FileWriter(ROSTER_FILE)); + } catch (IOException e) { + throw new ClassRosterPersistenceException( + "Could not save student data.", e); + } + + // Write out the Student objects to the roster file. + // NOTE TO THE APPRENTICES: We could just grab the student map, + // get the Collection of Students and iterate over them but we've + // already created a method that gets a List of Students so + // we'll reuse it. + List studentList = this.getAllStudents(); + for (Student currentStudent : studentList) { + // write the Student object to the file + out.println(currentStudent.getStudentId() + DELIMITER + + currentStudent.getFirstName() + DELIMITER + + currentStudent.getLastName() + DELIMITER + + currentStudent.getCohort()); + // force PrintWriter to write line to the file + out.flush(); + } + // Clean up + out.close(); + } +} \ No newline at end of file diff --git a/mod2/Class roster/src/exceptions/ClassRosterDataValidationException.java b/mod2/Class roster/src/exceptions/ClassRosterDataValidationException.java new file mode 100644 index 0000000..cdbd42b --- /dev/null +++ b/mod2/Class roster/src/exceptions/ClassRosterDataValidationException.java @@ -0,0 +1,14 @@ +package exceptions; + +public class ClassRosterDataValidationException extends Exception { + + public ClassRosterDataValidationException(String message) { + super(message); + } + + public ClassRosterDataValidationException(String message, + Throwable cause) { + super(message, cause); + } + +} diff --git a/mod2/Class roster/src/exceptions/ClassRosterDuplicateIdException.java b/mod2/Class roster/src/exceptions/ClassRosterDuplicateIdException.java new file mode 100644 index 0000000..2c4276d --- /dev/null +++ b/mod2/Class roster/src/exceptions/ClassRosterDuplicateIdException.java @@ -0,0 +1,14 @@ +package exceptions; + +public class ClassRosterDuplicateIdException extends Exception { + + public ClassRosterDuplicateIdException(String message) { + super(message); + } + + public ClassRosterDuplicateIdException(String message, + Throwable cause) { + super(message, cause); + } + +} diff --git a/mod2/Class roster/src/exceptions/ClassRosterPersistenceException.java b/mod2/Class roster/src/exceptions/ClassRosterPersistenceException.java new file mode 100644 index 0000000..b9ae706 --- /dev/null +++ b/mod2/Class roster/src/exceptions/ClassRosterPersistenceException.java @@ -0,0 +1,14 @@ +package exceptions; + +public class ClassRosterPersistenceException extends Exception{ + + public ClassRosterPersistenceException(String message) { + super(message); + } + + public ClassRosterPersistenceException(String message, + Throwable cause) { + super(message, cause); + } + +} diff --git a/mod2/Class roster/src/interfaces/ClassRosterAuditDao.java b/mod2/Class roster/src/interfaces/ClassRosterAuditDao.java new file mode 100644 index 0000000..b6d13f6 --- /dev/null +++ b/mod2/Class roster/src/interfaces/ClassRosterAuditDao.java @@ -0,0 +1,15 @@ +package interfaces; + +import exceptions.ClassRosterPersistenceException; + +public interface ClassRosterAuditDao { + + /** + * writes a Audit + * + * @param entry + * @throws ClassRosterPersistenceException + */ + void writeAuditEntry(String entry) throws ClassRosterPersistenceException; + +} diff --git a/mod2/Class roster/src/interfaces/ClassRosterDao.java b/mod2/Class roster/src/interfaces/ClassRosterDao.java new file mode 100644 index 0000000..91b063b --- /dev/null +++ b/mod2/Class roster/src/interfaces/ClassRosterDao.java @@ -0,0 +1,69 @@ +package interfaces; + +import java.util.List; + +import exceptions.ClassRosterPersistenceException; +import model.Student; + +public interface ClassRosterDao { + /** + * Adds the given Student to the roster and associates it with the given + * student id. If there is already a student associated with the given + * student id it will return that student object, otherwise it will + * return null. + * + * @param studentId id with which student is to be associated + * @param student student to be added to the roster + * @return the Student object previously associated with the given + * student id if it exists, null otherwise + * @throws ClassRosterPersistenceException + */ + Student addStudent(String studentId, Student student) throws ClassRosterPersistenceException; + + /** + * Returns a String array containing the student ids of all + * students in the roster. + * + * @return String array containing the ids of all the students + * in the roster + * @throws ClassRosterPersistenceException + */ + List getAllStudents() throws ClassRosterPersistenceException; + + /** + * Returns the student object associated with the given student id. + * Returns null if no such student exists + * + * @param studentId ID of the student to retrieve + * @return the Student object associated with the given student id, + * null if no such student exists + * @throws ClassRosterPersistenceException + */ + Student getStudent(String studentId) throws ClassRosterPersistenceException; + + /** + * Removes from the roster the student associated with the given id. + * Returns the student object that is being removed or null if + * there is no student associated with the given id + * + * @param studentId id of student to be removed + * @return Student object that was removed or null if no student + * was associated with the given student id + * @throws ClassRosterPersistenceException + */ + Student removeStudent(String studentId) throws ClassRosterPersistenceException; + + /** + * insantiates all the students + * + * @throws ClassRosterPersistenceException + */ + void run() throws ClassRosterPersistenceException; + + /** + * writes all students to file + * + * @throws ClassRosterPersistenceException + */ + void stopProgram() throws ClassRosterPersistenceException; +} diff --git a/mod2/Class roster/src/interfaces/ClassRosterServiceLayer.java b/mod2/Class roster/src/interfaces/ClassRosterServiceLayer.java new file mode 100644 index 0000000..4f38e77 --- /dev/null +++ b/mod2/Class roster/src/interfaces/ClassRosterServiceLayer.java @@ -0,0 +1,64 @@ +package interfaces; + +import java.util.List; + +import exceptions.ClassRosterDataValidationException; +import exceptions.ClassRosterDuplicateIdException; +import exceptions.ClassRosterPersistenceException; +import model.Student; + +public interface ClassRosterServiceLayer { + + /** + * creates a student but also thows an Exeption if the students id matches + * another id + * + * @param student + * @throws ClassRosterDuplicateIdException + * @throws ClassRosterDataValidationException + * @throws ClassRosterPersistenceException + */ + void createStudent(Student student) throws ClassRosterDuplicateIdException, + ClassRosterDataValidationException, + ClassRosterPersistenceException; + + /** + * gets all students in the student librairy while also checking the Scanner + * + * @return all students as a list + * @throws ClassRosterPersistenceException + */ + List getAllStudents() throws ClassRosterPersistenceException; + + /** + * gets a student by searching it by id + * + * @param studentId + * @return searched student + * @throws ClassRosterPersistenceException + */ + Student getStudent(String studentId) throws ClassRosterPersistenceException; + + /** + * gets a student and then removes it + * + * @param studentId + * @return deleted student + * @throws ClassRosterPersistenceException + */ + Student removeStudent(String studentId) throws ClassRosterPersistenceException; + + /** + * instantiates all students at run time and then writes to an audit + * + * @throws ClassRosterPersistenceException + */ + void run() throws ClassRosterPersistenceException; + + /** + * writes to file and then writes to audit + * + * @throws ClassRosterPersistenceException + */ + void stopProgram() throws ClassRosterPersistenceException; +} diff --git a/mod2/Class roster/src/interfaces/ConsoleIo.java b/mod2/Class roster/src/interfaces/ConsoleIo.java new file mode 100644 index 0000000..3ea93b2 --- /dev/null +++ b/mod2/Class roster/src/interfaces/ConsoleIo.java @@ -0,0 +1,26 @@ +package interfaces; + +public interface ConsoleIo { + public void print(String msg); + + public int readInt(String prompt); + + public int readInt(String prompt, int min, int max); + + public float readFloat(String prompt); + + public float readFloat(String prompt, float min, float max); + + public double readDouble(String prompt); + + public double readDouble(String prompt, Double min, Double max); + + public boolean readboolean(String prompt); + + public String readString(String prompt); + + public long readLong(String prompt); + + public long readLong(String prompt, long min, long max); + +} diff --git a/mod2/Class roster/src/model/Student.java b/mod2/Class roster/src/model/Student.java new file mode 100644 index 0000000..0ca9adb --- /dev/null +++ b/mod2/Class roster/src/model/Student.java @@ -0,0 +1,40 @@ +package model; + +public class Student { + private String firstName; + private String lastName; + private String studentId; + private String cohort; // Java or .Net + cohort month/year + + public Student(String studentId) { + this.studentId = studentId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getStudentId() { + return studentId; + } + + public String getCohort() { + return cohort; + } + + public void setCohort(String cohort) { + this.cohort = cohort; + } +} diff --git a/mod2/Class roster/src/serviceLayer/ClassRosterServiceLayerFileImpl.java b/mod2/Class roster/src/serviceLayer/ClassRosterServiceLayerFileImpl.java new file mode 100644 index 0000000..70ebe14 --- /dev/null +++ b/mod2/Class roster/src/serviceLayer/ClassRosterServiceLayerFileImpl.java @@ -0,0 +1,97 @@ +package serviceLayer; + +import java.util.List; + +import exceptions.ClassRosterDataValidationException; +import exceptions.ClassRosterDuplicateIdException; +import exceptions.ClassRosterPersistenceException; +import interfaces.ClassRosterAuditDao; +import interfaces.ClassRosterDao; +import interfaces.ClassRosterServiceLayer; +import model.Student; + +public class ClassRosterServiceLayerFileImpl implements ClassRosterServiceLayer { + + private ClassRosterAuditDao auditDao; + + private ClassRosterDao dao; + + public ClassRosterServiceLayerFileImpl(ClassRosterDao dao, ClassRosterAuditDao auditDao) { + this.dao = dao; + this.auditDao = auditDao; + } + + private void validateStudentData(Student student) throws ClassRosterDataValidationException { + + if (student.getFirstName() == null + || student.getFirstName().trim().length() == 0 + || student.getLastName() == null + || student.getLastName().trim().length() == 0 + || student.getCohort() == null + || student.getCohort().trim().length() == 0) { + + throw new ClassRosterDataValidationException( + "ERROR: All fields [First Name, Last Name, Cohort] are required."); + } + } + + @Override + public void createStudent(Student student) throws ClassRosterDataValidationException, + ClassRosterPersistenceException, ClassRosterDuplicateIdException { + + // First check to see if there is alreay a student + // associated with the given student's id + // If so, we're all done here - + // throw a ClassRosterDuplicateIdException + if (dao.getStudent(student.getStudentId()) != null) { + throw new ClassRosterDuplicateIdException( + "ERROR: Could not create student. Student Id " + + student.getStudentId() + + " already exists"); + } + + // Now validate all the fields on the given Student object. + // This method will throw an + // exception if any of the validation rules are violated. + validateStudentData(student); + + // We passed all our business rules checks so go ahead + // and persist the Student object + dao.addStudent(student.getStudentId(), student); + + // The student was successfully created, now write to the audit log + auditDao.writeAuditEntry( + "Student " + student.getStudentId() + " CREATED."); + } + + @Override + public List getAllStudents() throws ClassRosterPersistenceException { + return dao.getAllStudents(); + } + + @Override + public Student getStudent(String studentId) throws ClassRosterPersistenceException { + return dao.getStudent(studentId); + } + + @Override + public Student removeStudent(String studentId) throws ClassRosterPersistenceException { + Student removedStudent = dao.removeStudent(studentId); + // Write to audit log + auditDao.writeAuditEntry("Student " + studentId + " REMOVED."); + return removedStudent; + + } + + @Override + public void run() throws ClassRosterPersistenceException { + dao.run(); + auditDao.writeAuditEntry("||||||||||||||| Sucesfull: start runing program |||||||||||||||"); + } + + @Override + public void stopProgram() throws ClassRosterPersistenceException { + dao.stopProgram(); + auditDao.writeAuditEntry("||||||||||||||| Sucesfull: stop program |||||||||||||||"); + } +} diff --git a/mod2/Librairy/bin/storage/OutFile.txt b/mod2/Librairy/bin/storage/OutFile.txt index df29ab0..ab35ce3 100644 --- a/mod2/Librairy/bin/storage/OutFile.txt +++ b/mod2/Librairy/bin/storage/OutFile.txt @@ -1 +1 @@ -fyfyus::hasgfgdfh::sfgsfg::false::0 +rock::god::hat::false::0 diff --git a/mod2/Librairy/src/App.java b/mod2/Librairy/src/App.java index 82f7217..f03083f 100644 --- a/mod2/Librairy/src/App.java +++ b/mod2/Librairy/src/App.java @@ -23,7 +23,7 @@ public static void main(String[] args) throws Exception { String getBookNamePrompt = "what is the title of this book"; String getBookAuthorPrompt = "who is the author of this book"; String getBookGenrePrompt = "which genre is this book located"; - //String getBookIdPrompt = "what is the id of this book"; + // String getBookIdPrompt = "what is the id of this book"; String getBookTypePrompt = "what type will you serch by"; impl.install(); System.out.println("welcome to the library"); @@ -42,9 +42,9 @@ public static void main(String[] args) throws Exception { break; case 2: bookType = console.getString(getBookTypePrompt); - if ( !bookType.equals("author") && !bookType.equals("genre")) { + if (!bookType.equals("author") && !bookType.equals("genre")) { sampleBook = impl.findType(bookType, sampleBook); - if (sampleBook != null ){ + if (sampleBook != null) { console.printBook(sampleBook); } } else if (bookType.equals("author") || bookType.equals("genre")) { @@ -53,14 +53,14 @@ public static void main(String[] args) throws Exception { console.printBook(sampleList); } } - + break; case 3: impl.print(); break; case 4: bookType = console.getString(getBookTypePrompt); - if (!bookType.equals("author") && !bookType.equals("Genre")){ + if (!bookType.equals("author") && !bookType.equals("Genre")) { sampleBook = impl.findType(bookType, sampleBook); if (sampleBook != null && sampleBook.getCheckedOut() == false) { impl.checkOut(sampleBook, true); diff --git a/mod2/Librairy/src/console/Console.java b/mod2/Librairy/src/console/Console.java index 6766c64..eb83fa2 100644 --- a/mod2/Librairy/src/console/Console.java +++ b/mod2/Librairy/src/console/Console.java @@ -7,12 +7,13 @@ public class Console { private Scanner sc; + public Console(Scanner sc) { this.sc = sc; } - public void printMenue(){ - + public void printMenue() { + System.out.println("1: add a book to the library"); System.out.println("2: search for a book in the librairy"); System.out.println("3: list the books in the librairy"); @@ -20,6 +21,7 @@ public void printMenue(){ System.out.println("5: return a book to the librairy"); System.out.println("6: exit the librairy"); } + public void printBook(Book book) { System.out.println("___________________________"); System.out.println("title: " + book.getTitle()); @@ -29,64 +31,66 @@ public void printBook(Book book) { System.out.println("is checked out: " + book.getCheckedOut()); System.out.println("___________________________"); } + public void printBook(List librairyList) { for (Book book : librairyList) { this.printBook(book); } } + public int getInt(String prompt) { boolean isCorrect = false; int value = 0; String userInput; - while(!isCorrect) { - System.out.println(prompt); - userInput = this.sc.nextLine(); + while (!isCorrect) { + userInput = this.getString(prompt); try { value = Integer.parseInt(userInput); isCorrect = true; } catch (Exception e) { System.out.println("That was not a int. Please try again"); } - } + } return value; } + public float getFloat(String prompt) { boolean isCorrect = false; float value = 0; String userInput; - while(!isCorrect) { - System.out.println(prompt); - userInput = this.sc.nextLine(); + while (!isCorrect) { + userInput = this.getString(prompt); try { value = Float.parseFloat(userInput); isCorrect = true; } catch (Exception e) { System.out.println("That was not a float. Please try again"); } - } + } return value; } + public double getDouble(String prompt) { boolean isCorrect = false; double value = 0; String userInput; - while(!isCorrect) { - System.out.println(prompt); - userInput = this.sc.nextLine(); + while (!isCorrect) { + userInput = this.getString(prompt); try { value = Double.parseDouble(userInput); isCorrect = true; } catch (Exception e) { System.out.println("That was not a double. Please try again"); } - } + } return value; } + public boolean getboolean(String prompt) { boolean isCorrect = false; boolean value = false; String userInput; - while(!isCorrect) { + while (!isCorrect) { userInput = this.getString(prompt); try { value = Boolean.parseBoolean(userInput); @@ -94,22 +98,22 @@ public boolean getboolean(String prompt) { } catch (Exception e) { System.out.println("That was not a boolean. Please try again"); } - } + } return value; } + public String getString(String prompt) { System.out.println(prompt); return this.sc.nextLine(); } - public boolean getYesOrNo(String prompt, String yes, String no){ + public boolean getYesOrNo(String prompt, String yes, String no) { String whatToDo = null; boolean satifaction = false; boolean yn = false; - + do { - System.out.println(prompt + " " + yes + "/" + no); - whatToDo = sc.nextLine(); + whatToDo = this.getString(prompt + " " + yes + "/" + no); if (whatToDo.equals(yes)) { yn = true; satifaction = true; diff --git a/mod2/Librairy/src/dao/LibraryFileImpl.java b/mod2/Librairy/src/dao/LibraryFileImpl.java index 5b86300..a1e17f0 100644 --- a/mod2/Librairy/src/dao/LibraryFileImpl.java +++ b/mod2/Librairy/src/dao/LibraryFileImpl.java @@ -1,59 +1,101 @@ package dao; +import java.io.BufferedReader; +import java.io.FileReader; import java.io.PrintWriter; +import java.util.ArrayList; import java.util.List; +import java.util.Scanner; +import console.Console; import interfaces.LibraryInterface; import model.Book; import model.Client; -public class LibraryFileImpl implements LibraryInterface{ +public class LibraryFileImpl implements LibraryInterface { + private List libraryList = new ArrayList<>(); + private static int id; + private static Scanner scanner = new Scanner(System.in); + private static Console console = new Console(scanner); + public Book wrongBook = new Book("uh oh", "uh oh", "uh oh"); @Override public void create(Book book, PrintWriter writer) { - writer.println(book.getTitle() + "::" + book.getAuthor() + "::" + book.getGenre() + "::" + book.getCheckedOut() + "::" + book.getId()); + book.setId(id++); + book.setCheckedOut(false); + libraryList.add(book); + for (Book book2 : libraryList) { + writer.println( + book2.getTitle() + "::" + book2.getAuthor() + "::" + book2.getGenre() + "::" + book2.getCheckedOut() + + "::" + book2.getId()); + writer.flush(); + writer.close(); + } } @Override public Book searchById(String value) { - // TODO Auto-generated method stub + int id; + try { + id = Integer.parseInt(value); + for (Book b : libraryList) { + if (id == b.getId()) { + return b; + } + } + } catch (Exception e) { + return wrongBook; + } return null; } @Override public Book searchByName(String value) { - // TODO Auto-generated method stub + for (Book b : libraryList) { + if (value.equals(b.getTitle())) { + return b; + } + } return null; } @Override public List searchByAuthor(String value) { - // TODO Auto-generated method stub - return null; + List bookList = new ArrayList<>(); + for (Book b : libraryList) { + if (value.equals(b.getAuthor())) { + bookList.add(b); + } + } + return bookList; } @Override public List searchByGenre(String value) { - // TODO Auto-generated method stub - return null; + List bookList = new ArrayList<>(); + for (Book b : libraryList) { + if (value.equals(b.getGenre())) { + bookList.add(b); + } + } + return bookList; } @Override public void checkOut(Book book, boolean checkedOut) { - // TODO Auto-generated method stub - + this.searchByName(book.getTitle()).setCheckedOut(checkedOut); } @Override public Client create(Client client) { - // TODO Auto-generated method stub return null; } @Override public void print() { - // TODO Auto-generated method stub - + for (Book book : libraryList) { + console.printBook(book); + } } @Override @@ -70,7 +112,25 @@ public List findType(String bookType, List sampleList) { @Override public void install() throws Exception { - + Scanner read = new Scanner( + new BufferedReader(new FileReader("/home/bhima/dev/mod2/Librairy/src/storage/OutFile.txt"))); + String[] parts; + String line; + while (read.hasNextLine()) { + line = read.nextLine(); + parts = line.split("::"); + Book b = new Book(); + b.setTitle(parts[0]); + b.setAuthor(parts[1]); + b.setGenre(parts[2]); + b.setCheckedOut(Boolean.parseBoolean(parts[3])); + b.setId(Integer.parseInt(parts[4])); + // add to in memory list for fast lookup + libraryList.add(b); + if (!read.hasNextLine()) { + id = Integer.parseInt(parts[4]) + 1; + } + } + } - } diff --git a/mod2/Librairy/src/dao/LibraryInMemoryImpl.java b/mod2/Librairy/src/dao/LibraryInMemoryImpl.java index a1f3d9d..4168e10 100644 --- a/mod2/Librairy/src/dao/LibraryInMemoryImpl.java +++ b/mod2/Librairy/src/dao/LibraryInMemoryImpl.java @@ -13,10 +13,10 @@ import model.Book; import model.Client; -public class LibraryInMemoryImpl implements LibraryInterface{ +public class LibraryInMemoryImpl implements LibraryInterface { private List libraryList = new ArrayList<>(); private HashMap librairyMap = new HashMap<>(); - //private List clientList = new ArrayList<>(); + // private List clientList = new ArrayList<>(); private static int id; private static int id2; Scanner sc = new Scanner(System.in); @@ -24,16 +24,18 @@ public class LibraryInMemoryImpl implements LibraryInterface{ public Book wrongBook = new Book("uh oh", "uh oh", "uh oh"); @Override - public void create(Book book, PrintWriter writer){ + public void create(Book book, PrintWriter writer) { book.setId(id++); book.setCheckedOut(false); libraryList.add(book); - writer.println(book.getTitle() + "::" + book.getAuthor() + "::" + book.getGenre() + "::" + book.getCheckedOut() + "::" + book.getId()); + writer.println(book.getTitle() + "::" + book.getAuthor() + "::" + book.getGenre() + "::" + book.getCheckedOut() + + "::" + book.getId()); writer.flush(); writer.close(); } + @Override - public Book searchById(String value){ + public Book searchById(String value) { int id; try { id = Integer.parseInt(value); @@ -47,17 +49,19 @@ public Book searchById(String value){ } return null; } + @Override - public Book searchByName(String value){ - for (Book b: libraryList) { + public Book searchByName(String value) { + for (Book b : libraryList) { if (value.equals(b.getTitle())) { return b; } } return null; } + @Override - public List searchByAuthor(String value){ + public List searchByAuthor(String value) { List bookList = new ArrayList<>(); for (Book b : libraryList) { if (value.equals(b.getAuthor())) { @@ -66,6 +70,7 @@ public List searchByAuthor(String value){ } return bookList; } + @Override public List searchByGenre(String value) { List bookList = new ArrayList<>(); @@ -76,29 +81,32 @@ public List searchByGenre(String value) { } return bookList; } + @Override - public void checkOut(Book book, boolean checkedOut){ + public void checkOut(Book book, boolean checkedOut) { this.searchByName(book.getTitle()).setCheckedOut(checkedOut); } @Override - public Client create(Client client){ + public Client create(Client client) { client.setId(id2++); client.setAge(client.getAge()); client.setBooks(client.getBooks()); client.setName(client.getName()); return client; } + @Override public void print() { - for (Book b : libraryList) { - console.printBook(b); - } + for (Book b : libraryList) { + console.printBook(b); + } } + @Override public Book findType(String bookType, Book sampleBook) { - + String getBookNamePrompt = "what is the title of this book"; String getBookAuthorPrompt = "who is the author of this book"; String getBookIdPrompt = "what is the id of this book"; @@ -128,7 +136,7 @@ public Book findType(String bookType, Book sampleBook) { } @Override - public List findType(String bookType, List sampleList){ + public List findType(String bookType, List sampleList) { String getBookAuthorPrompt = "who is the author of this book"; String getBookGenrePrompt = "which genre is this book located"; @@ -155,14 +163,15 @@ public List findType(String bookType, List sampleList){ } return null; } - + @Override - public void install() throws Exception{ - Scanner read = new Scanner(new BufferedReader(new FileReader("/home/bhima/dev/mod2/Librairy/src/storage/OutFile.txt"))); - String[] parts; - String line; - boolean ischeckedout; - int id; + public void install() throws Exception { + Scanner read = new Scanner( + new BufferedReader(new FileReader("/home/bhima/dev/mod2/Librairy/src/storage/OutFile.txt"))); + String[] parts; + String line; + boolean ischeckedout; + int id; while (read.hasNextLine()) { line = read.nextLine(); parts = line.split("::"); @@ -172,9 +181,9 @@ public void install() throws Exception{ b.setAuthor(parts[1]); b.setTitle(parts[0]); b.setCheckedOut(ischeckedout); - b.setGenre(parts [2]); + b.setGenre(parts[2]); b.setId(id); - //add to in memory list for fast lookup + // add to in memory list for fast lookup libraryList.add(b); if (!read.hasNextLine()) { this.id = id; diff --git a/mod2/Librairy/src/interfaces/LibraryInterface.java b/mod2/Librairy/src/interfaces/LibraryInterface.java index 5c764be..02bb331 100644 --- a/mod2/Librairy/src/interfaces/LibraryInterface.java +++ b/mod2/Librairy/src/interfaces/LibraryInterface.java @@ -8,15 +8,25 @@ public interface LibraryInterface { public void create(Book book, PrintWriter writer); + public Book searchById(String value); + public Book searchByName(String value); + public List searchByAuthor(String value); + public List searchByGenre(String value); + public void checkOut(Book book, boolean checkedOut); + public Client create(Client client); + public void print(); + public Book findType(String bookType, Book sampleBook); + public List findType(String bookType, List sampleList); + public void install() throws Exception; // public boolean delete(String value, String type); } diff --git a/mod2/Librairy/src/model/Book.java b/mod2/Librairy/src/model/Book.java index 79a7453..bae8de5 100644 --- a/mod2/Librairy/src/model/Book.java +++ b/mod2/Librairy/src/model/Book.java @@ -8,13 +8,11 @@ public class Book { private String genre; private boolean checkedOut; - - - public Book () { + public Book() { } - public Book (String title, String author, String genre) { + public Book(String title, String author, String genre) { this.title = title; this.author = author; this.genre = genre; @@ -28,8 +26,6 @@ public void setCheckedOut(Boolean checkedOut) { this.checkedOut = checkedOut; } - - public String getGenre() { return this.genre; } @@ -37,6 +33,7 @@ public String getGenre() { public void setGenre(String genre) { this.genre = genre; } + public boolean isIsAvailable() { return this.isAvailable; } @@ -45,8 +42,6 @@ public void setIsAvailable(boolean isAvailable) { this.isAvailable = isAvailable; } - - public String getTitle() { return this.title; } @@ -71,9 +66,9 @@ public void setId(int id) { this.id = id; } - public String toString () { - + public String toString() { + return ""; } - + } diff --git a/mod2/Librairy/src/model/Client.java b/mod2/Librairy/src/model/Client.java index e83dc8e..dabcbc0 100644 --- a/mod2/Librairy/src/model/Client.java +++ b/mod2/Librairy/src/model/Client.java @@ -6,11 +6,11 @@ public class Client { private int age; private int books; - public Client(){ + public Client() { } - public Client(int id, String name, int age){ + public Client(int id, String name, int age) { this.age = age; this.id = id; this.name = name; @@ -23,6 +23,7 @@ public int getBooks() { public void setBooks(int books) { this.books = books; } + public int getId() { return this.id; } diff --git a/mod2/Librairy/src/storage/OutFile.txt b/mod2/Librairy/src/storage/OutFile.txt index df29ab0..ab35ce3 100644 --- a/mod2/Librairy/src/storage/OutFile.txt +++ b/mod2/Librairy/src/storage/OutFile.txt @@ -1 +1 @@ -fyfyus::hasgfgdfh::sfgsfg::false::0 +rock::god::hat::false::0 diff --git a/mod2/adress Book/.vscode/settings.json b/mod2/adress Book/.vscode/settings.json new file mode 100644 index 0000000..3ae42db --- /dev/null +++ b/mod2/adress Book/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "java.project.sourcePaths": ["src"], + "java.project.outputPath": "bin", + "java.project.referencedLibraries": [ + "lib/**/*.jar" + ], + "java.dependency.packagePresentation": "flat" +} diff --git a/mod2/adress Book/README.md b/mod2/adress Book/README.md new file mode 100644 index 0000000..7c03a53 --- /dev/null +++ b/mod2/adress Book/README.md @@ -0,0 +1,18 @@ +## Getting Started + +Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. + +## Folder Structure + +The workspace contains two folders by default, where: + +- `src`: the folder to maintain sources +- `lib`: the folder to maintain dependencies + +Meanwhile, the compiled output files will be generated in the `bin` folder by default. + +> If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. + +## Dependency Management + +The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). diff --git a/mod2/adress Book/adress Book.jar b/mod2/adress Book/adress Book.jar new file mode 100644 index 0000000..9db92df Binary files /dev/null and b/mod2/adress Book/adress Book.jar differ diff --git a/mod2/hopenlop aka simple java I O/src/App.java b/mod2/adress Book/src/App.java similarity index 90% rename from mod2/hopenlop aka simple java I O/src/App.java rename to mod2/adress Book/src/App.java index 7e88056..2add349 100644 --- a/mod2/hopenlop aka simple java I O/src/App.java +++ b/mod2/adress Book/src/App.java @@ -1,5 +1,5 @@ public class App { public static void main(String[] args) throws Exception { - + } } diff --git a/mod2/adress Book/src/Contrllers/Controller.java b/mod2/adress Book/src/Contrllers/Controller.java new file mode 100644 index 0000000..11d912c --- /dev/null +++ b/mod2/adress Book/src/Contrllers/Controller.java @@ -0,0 +1,58 @@ +package Contrllers; + +import IO.Veiw; + +public class Controller { + Veiw veiw; + + public Controller(Veiw veiw){ + this.veiw = veiw; + } + + public void run() { + boolean keepGoing = true; + int menuSelection = 0; + while (keepGoing) { + + menuSelection = getMenu(); + + switch (menuSelection) { + case 1: + listStudents(); + break; + case 2: + createStudent(); + break; + case 3: + viewStudent(); + break; + case 4: + removeStudent(); + break; + case 5: + keepGoing = false; + break; + default: + + } + + } + } + + + private void removeStudent() { + } + + private void viewStudent() { + } + + private void createStudent() { + } + + private void listStudents() { + } + + private int getMenu() { + return veiw.printMenu(); + } +} diff --git a/mod2/adress Book/src/IO/IO.java b/mod2/adress Book/src/IO/IO.java new file mode 100644 index 0000000..6259346 --- /dev/null +++ b/mod2/adress Book/src/IO/IO.java @@ -0,0 +1,177 @@ +package IO; + +import java.util.Scanner; + +import interfaces.consoleIO; + +public class IO implements consoleIO { + private Scanner sc; + + IO(Scanner sc) { + this.sc = sc; + } + + @Override + public int readInt(String prompt) { + boolean isCorrect = false; + int value = 0; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Integer.parseInt(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("that was not a number please try again"); + } + } + return value; + } + + @Override + public int readInt(String prompt, int min, int max) { + boolean isCorrect = false; + int value; + do { + value = this.readInt(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public float readFloat(String prompt) { + boolean isCorrect = false; + float value = 0; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Float.parseFloat(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("that was not a number please try again"); + } + } + return value; + } + + @Override + public float readFloat(String prompt, float min, float max) { + boolean isCorrect = false; + float value; + do { + value = this.readFloat(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public double readDouble(String prompt) { + boolean isCorrect = false; + double value = 0; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Double.parseDouble(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("That was not a double. Please try again"); + } + } + return value; + } + + @Override + public double readDouble(String prompt, Double min, Double max) { + boolean isCorrect = false; + double value; + do { + value = this.readDouble(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public boolean readboolean(String prompt) { + boolean isCorrect = false; + boolean value = false; + String userInput; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Boolean.parseBoolean(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("That was not a boolean. Please try again"); + } + } + return value; + } + + @Override + public long readLong(String prompt) { + boolean isCorrect = false; + String userInput; + long value = 0; + while (!isCorrect) { + userInput = this.readString(prompt); + try { + value = Long.parseLong(userInput); + isCorrect = true; + } catch (Exception e) { + this.print("That was not a double. Please try again"); + } + } + return value; + } + + public long readLong(String prompt, long min, long max) { + boolean isCorrect = false; + long value; + do { + value = this.readLong(prompt); + if (value > max) { + this.print("that number was to high"); + } else if (value < min) { + this.print("that number was to low"); + } else { + isCorrect = true; + } + } while (!isCorrect); + return value; + } + + @Override + public String readString(String prompt) { + this.print(prompt); + return this.sc.nextLine(); + } + + @Override + public void print(String msg) { + System.out.println(msg); + + } +} diff --git a/mod2/adress Book/src/IO/Veiw.java b/mod2/adress Book/src/IO/Veiw.java new file mode 100644 index 0000000..812e8b7 --- /dev/null +++ b/mod2/adress Book/src/IO/Veiw.java @@ -0,0 +1,34 @@ +package IO; + +import interfaces.consoleIO; + +public class Veiw { + consoleIO io; + private final String SPACE = " "; + + Veiw(consoleIO io) { + this.io = io; + } + + public int printMenu() { + io.print("=================="); + io.print("chose one of the folowing"); + io.print(SPACE + "1: create adress"); + io.print(SPACE + "2: list all adresses"); + io.print(SPACE + "3: search for a adress"); + io.print(SPACE + "4: count all the adresses"); + io.print(SPACE + "5: remove an adress"); + io.print(SPACE + "6: EXIT"); + + return io.readInt("", 1, 5); + } + + public void baner(String msg) { + io.print("===== " + msg + " ====="); + } + + public void errorMessage(String errorMsg) { + io.print("==== ERROR ===="); + io.print(errorMsg); + } +} diff --git a/mod2/adress Book/src/ServiceLayer/ServiceLayerFileImpl.java b/mod2/adress Book/src/ServiceLayer/ServiceLayerFileImpl.java new file mode 100644 index 0000000..413b884 --- /dev/null +++ b/mod2/adress Book/src/ServiceLayer/ServiceLayerFileImpl.java @@ -0,0 +1,12 @@ +package ServiceLayer; + +import interfaces.Dao; +import interfaces.ServiceLayer; + +public class ServiceLayerFileImpl implements ServiceLayer { + Dao dao; + + public ServiceLayerFileImpl(Dao dao) { + this.dao = dao; + } +} diff --git a/mod2/adress Book/src/audit/AuditDao.java b/mod2/adress Book/src/audit/AuditDao.java new file mode 100644 index 0000000..72e68f8 --- /dev/null +++ b/mod2/adress Book/src/audit/AuditDao.java @@ -0,0 +1,28 @@ +package audit; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.time.LocalDateTime; + +import exceptions.PersistenceException; +import interfaces.Audit; + +public class AuditDao implements Audit { + public static final String AUDIT_FILE = "audit.txt"; + + @Override + public void writeAuditEntry(String entry) throws PersistenceException { + PrintWriter out; + + try { + out = new PrintWriter(new FileWriter(AUDIT_FILE, true)); + } catch (IOException e) { + throw new PersistenceException("Could not persist audit information.", e); + } + + LocalDateTime timestamp = LocalDateTime.now(); + out.println(timestamp.toString() + " : " + entry); + out.flush(); + } +} diff --git a/mod2/adress Book/src/dao/DaoFileImpl.java b/mod2/adress Book/src/dao/DaoFileImpl.java new file mode 100644 index 0000000..f551f0b --- /dev/null +++ b/mod2/adress Book/src/dao/DaoFileImpl.java @@ -0,0 +1,163 @@ +package dao; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import exceptions.PersistenceException; +import interfaces.Dao; +import modle.Adress; + +public class DaoFileImpl implements Dao { + private Map adressMap = new HashMap<>(); + public static final String ADRESS_FILE = "book.txt"; + public static final String DELIMITER = "::"; + + @Override + public Adress createAdress(Adress myAdress) throws PersistenceException { + Adress newAdress = adressMap.put(myAdress.getAdressName(), myAdress); + return newAdress; + } + + @Override + public Adress deleteAdress(Adress myAdress) throws PersistenceException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Adress getAdress(String name) throws PersistenceException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getAllAdresses() throws PersistenceException { + this.loadRoster(); + return new ArrayList(adressMap.values()); + } + + @Override + public void run() throws PersistenceException { + // TODO Auto-generated method stub + + } + + @Override + public void close() throws PersistenceException { + // TODO Auto-generated method stub + + } + + @Override + public int count() { + return adressMap.size(); + } + + /** + * reads all Adresss from file + * preferably at startup + * + * @throws PersistenceException if an error occurs wile reading the + * file + */ + private void loadRoster() throws PersistenceException { + Scanner scanner; + + try { + // Create Scanner for reading the file + scanner = new Scanner( + new BufferedReader( + new FileReader(ADRESS_FILE))); + } catch (FileNotFoundException e) { + throw new PersistenceException( + "-_- Could not load roster data into memory.", e); + } + // currentLine holds the most recent line read from the file + String currentLine; + // currentTokens holds each of the parts of the currentLine after it has + // been split on our DELIMITER + // NOTE FOR APPRENTICES: In our case we use :: as our delimiter. If + // currentLine looks like this: + // 1234::Joe::Smith::Java-September2013 + // then currentTokens will be a string array that looks like this: + // + // ___________________________________ + // | | | | | + // |1234|Joe|Smith|Java-September2013| + // | | | | | + // ----------------------------------- + // [0] [1] [2] [3] + String[] currentTokens; + // Go through ROSTER_FILE line by line, decoding each line into a + // Adress object. + // Process while we have more lines in the file + while (scanner.hasNextLine()) { + // get the next line in the file + currentLine = scanner.nextLine(); + // break up the line into tokens + currentTokens = currentLine.split(DELIMITER); + // Create a new Adress object and put it into the map of Adress + // NOTE FOR APPRENTICES: We are going to use the Adress id + // which is currentTokens[0] as the map key for our Adress object. + // We also have to pass the Adress id into the Adress constructor + Adress currentAdress = new Adress(currentTokens[0]); + // Set the remaining vlaues on currentAdress manually + currentAdress.setFirstName(currentTokens[1]); + currentAdress.setLastName(currentTokens[2]); + // Put currentAdress into the map using AdressID as the key + adressMap.put(currentAdress.getFirstName(), currentAdress); + } + // close scanner + scanner.close(); + } + + /** + * Writes all Adresss in the roster out to a ROSTER_FILE. See loadRoster + * for file format. + * + * @throws PersistenceException if an error occurs writing to the + * file + */ + private void writeRoster() throws PersistenceException { + // NOTE FOR APPRENTICES: We are not handling the IOException - but + // we are translating it to an application specific exception and + // then simple throwing it (i.e. 'reporting' it) to the code that + // called us. It is the responsibility of the calling code to + // handle any errors that occur. + PrintWriter out; + + try { + out = new PrintWriter(new FileWriter(ADRESS_FILE)); + } catch (IOException e) { + throw new PersistenceException( + "Could not save Adress data.", e); + } + + // Write out the Adress objects to the roster file. + // NOTE TO THE APPRENTICES: We could just grab the Adress map, + // get the Collection of Adresss and iterate over them but we've + // already created a method that gets a List of Adresss so + // we'll reuse it. + List AdressList = this.getAllAdresses(); + for (Adress currentAdress : AdressList) { + // write the Adress object to the file + out.println(currentAdress.getAdressName() + DELIMITER + + currentAdress.getFirstName() + DELIMITER + + currentAdress.getLastName()); + // force PrintWriter to write line to the file + out.flush(); + } + // Clean up + out.close(); + } + +} diff --git a/mod2/adress Book/src/exceptions/DataVialationException.java b/mod2/adress Book/src/exceptions/DataVialationException.java new file mode 100644 index 0000000..a5102f9 --- /dev/null +++ b/mod2/adress Book/src/exceptions/DataVialationException.java @@ -0,0 +1,11 @@ +package exceptions; + +public class DataVialationException extends Exception { + DataVialationException(String msg) { + super(msg); + } + + DataVialationException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/mod2/adress Book/src/exceptions/PersistenceException.java b/mod2/adress Book/src/exceptions/PersistenceException.java new file mode 100644 index 0000000..b7816d2 --- /dev/null +++ b/mod2/adress Book/src/exceptions/PersistenceException.java @@ -0,0 +1,11 @@ +package exceptions; + +public class PersistenceException extends Exception { + PersistenceException(String msg) { + super(msg); + } + + public PersistenceException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/mod2/adress Book/src/exceptions/SameAdressException.java b/mod2/adress Book/src/exceptions/SameAdressException.java new file mode 100644 index 0000000..b61f0c7 --- /dev/null +++ b/mod2/adress Book/src/exceptions/SameAdressException.java @@ -0,0 +1,11 @@ +package exceptions; + +public class SameAdressException extends Exception { + SameAdressException(String msg) { + super(msg); + } + + SameAdressException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/mod2/adress Book/src/interfaces/Audit.java b/mod2/adress Book/src/interfaces/Audit.java new file mode 100644 index 0000000..42cc056 --- /dev/null +++ b/mod2/adress Book/src/interfaces/Audit.java @@ -0,0 +1,13 @@ +package interfaces; + +import exceptions.PersistenceException; + +public interface Audit { + /** + * writes a Audit + * + * @param entry + * @throws ClassRosterPersistenceException + */ + void writeAuditEntry(String entry) throws PersistenceException; +} diff --git a/mod2/adress Book/src/interfaces/Dao.java b/mod2/adress Book/src/interfaces/Dao.java new file mode 100644 index 0000000..2e53e4e --- /dev/null +++ b/mod2/adress Book/src/interfaces/Dao.java @@ -0,0 +1,66 @@ +package interfaces; + +import java.util.List; + +import exceptions.PersistenceException; +import modle.Adress; + +public interface Dao { + /** + * creates an adress + * + * @param myAdress + * @return created adress + * @throws PersistenceException + */ + Adress createAdress(Adress myAdress) throws PersistenceException; + + /** + * deletes an adress + * + * @param myAdress + * @return deleted adress + * @throws PersistenceException + */ + Adress deleteAdress(Adress myAdress) throws PersistenceException; + + /** + * gets an adress by searching by name + * + * @param name + * @return searched adress + * @throws PersistenceException + */ + Adress getAdress(String name) throws PersistenceException; + + /** + * gets all the adresses + * + * @return all the adresses + * @throws PersistenceException + */ + List getAllAdresses() throws PersistenceException; + + /** + * instantiates all adresses to run the program and also makes the file if it + * does not exist + * + * @throws PersistenceException + */ + void run() throws PersistenceException; + + /** + * puts all the adresses into long term memory so you can close the program + * + * @throws PersistenceException + */ + void close() throws PersistenceException; + + /** + * counts all the adresses + * + * @return the number of adresses + * @throws PersistenceException + */ + int count() throws PersistenceException; +} diff --git a/mod2/adress Book/src/interfaces/ServiceLayer.java b/mod2/adress Book/src/interfaces/ServiceLayer.java new file mode 100644 index 0000000..ea67983 --- /dev/null +++ b/mod2/adress Book/src/interfaces/ServiceLayer.java @@ -0,0 +1,5 @@ +package interfaces; + +public interface ServiceLayer { + +} diff --git a/mod2/adress Book/src/interfaces/consoleIO.java b/mod2/adress Book/src/interfaces/consoleIO.java new file mode 100644 index 0000000..36ae013 --- /dev/null +++ b/mod2/adress Book/src/interfaces/consoleIO.java @@ -0,0 +1,50 @@ +package interfaces; + +public interface consoleIO { + /** + * prints msg + * + * @param msg + */ + public void print(String msg); + + /** + * gets an string and converts it to a int unless the string is not a number + * + * @param prompt + * @return the int that has been created + */ + public int readInt(String prompt); + + /** + * uses .readInt and only between min and max + * + * @param prompt + * @param min + * @param max + * @return the int between min and max + */ + public int readInt(String prompt, int min, int max); + + /** + * + * + * @param prompt + * @return + */ + public float readFloat(String prompt); + + public float readFloat(String prompt, float min, float max); + + public double readDouble(String prompt); + + public double readDouble(String prompt, Double min, Double max); + + public boolean readboolean(String prompt); + + public String readString(String prompt); + + public long readLong(String prompt); + + public long readLong(String prompt, long min, long max); +} diff --git a/mod2/adress Book/src/modle/Adress.java b/mod2/adress Book/src/modle/Adress.java new file mode 100644 index 0000000..3d28faa --- /dev/null +++ b/mod2/adress Book/src/modle/Adress.java @@ -0,0 +1,36 @@ +package modle; + +public class Adress { + private String firstName; + private String lastName; + private String adressName; + + public Adress(String adressName) { + this.setAdressName(adressName); + } + + public String getFirstName() { + return this.firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return this.lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAdressName() { + return this.adressName; + } + + public void setAdressName(String adressName) { + this.adressName = adressName; + } + +} diff --git a/mod2/d&d.vs/src/modle/Person.java b/mod2/d&d.vs/src/modle/Person.java index 32ea353..d1cdf69 100644 --- a/mod2/d&d.vs/src/modle/Person.java +++ b/mod2/d&d.vs/src/modle/Person.java @@ -1,5 +1,6 @@ package modle; -import java.util.List; + +import javax.annotation.processing.RoundEnvironment; public class Person { private int str; @@ -82,7 +83,6 @@ public int getWism() { return this.wism; } - private int car; public int getCar() { @@ -99,5 +99,5 @@ public int getCarm() { return this.carm; } - //private List itemList = new List(); + // private List itemList = new List(); } diff --git a/mod2/d&d.vs/src/modle/item.java b/mod2/d&d.vs/src/modle/item.java index b293ce5..2c5b437 100644 --- a/mod2/d&d.vs/src/modle/item.java +++ b/mod2/d&d.vs/src/modle/item.java @@ -1,5 +1,6 @@ package modle; public class item { - + private String name; + private int weight; } diff --git a/mod2/d&d.vs/things .txt b/mod2/d&d.vs/things .txt new file mode 100644 index 0000000..9a00bdd --- /dev/null +++ b/mod2/d&d.vs/things .txt @@ -0,0 +1,3 @@ + Math. round () - this method rounds a number to the nearest integer. ... + Math. floor () - this method rounds a number downward to the nearest integer. ... + Math. ceil() - this method rounds a number upward to its nearest integer. \ No newline at end of file diff --git a/mod4/FirstMavenProject/pom.xml b/mod4/FirstMavenProject/pom.xml new file mode 100644 index 0000000..2feec73 --- /dev/null +++ b/mod4/FirstMavenProject/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.mycompany.firstmavenproject + FirstMavenProject + 1.0-SNAPSHOT + + UTF-8 + 18 + 18 + com.mycompany.firstmavenproject.FirstMavenProject + + + + org.springframework + spring-context + 4.3.4.RELEASE + + + + junit + junit + 4.11 + test + + + + \ No newline at end of file diff --git a/mod4/FirstMavenProject/src/main/java/com/mycompany/firstmavenproject/FirstMavenProject.java b/mod4/FirstMavenProject/src/main/java/com/mycompany/firstmavenproject/FirstMavenProject.java new file mode 100644 index 0000000..a564b20 --- /dev/null +++ b/mod4/FirstMavenProject/src/main/java/com/mycompany/firstmavenproject/FirstMavenProject.java @@ -0,0 +1,20 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Project/Maven2/JavaApp/src/main/java/${packagePath}/${mainClassName}.java to edit this template + */ + +package com.mycompany.firstmavenproject; + +/** + * + * @author bhima + */ +public class FirstMavenProject { + + public static void main(String[] args) { + System.out.println("Hello World!"); + } + + + +} diff --git a/mod4/FirstMavenProject/src/main/java/greatParty/GreatParty.java b/mod4/FirstMavenProject/src/main/java/greatParty/GreatParty.java new file mode 100644 index 0000000..a029af6 --- /dev/null +++ b/mod4/FirstMavenProject/src/main/java/greatParty/GreatParty.java @@ -0,0 +1,24 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package greatParty; + +/** + * + * @author bhima + */ +public class GreatParty { + // When squirrels get together for a party, they like to have cigars. +// A squirrel party is successful when the number of cigars is between +// 40 and 60, inclusive. Unless it is the weekend, in which case there +// is no upper bound on the number of cigars. Return true if the party +// with the given values is successful, or false otherwise. +// +// greatParty(30, false) → false +// greatParty(50, false) → true +// greatParty(70, true) → true +public boolean greatParty(int cigars, boolean isWeekend) { + throw new UnsupportedOperationException("Not implemented"); +} +} diff --git a/mod4/FirstMavenProject/src/main/java/greatParty/GreatPartyTest.java b/mod4/FirstMavenProject/src/main/java/greatParty/GreatPartyTest.java new file mode 100644 index 0000000..adf336f --- /dev/null +++ b/mod4/FirstMavenProject/src/main/java/greatParty/GreatPartyTest.java @@ -0,0 +1,34 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package greatParty; + +import org.JU + +/** + * + * @author bhima + */ +public class GreatPartyTest { + GreatParty party = new GreatParty(); + + public GreatPartyTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void teardown() { + } +} diff --git a/mod4/datetime/datetime.jar b/mod4/datetime/datetime.jar new file mode 100755 index 0000000..2fce0f7 Binary files /dev/null and b/mod4/datetime/datetime.jar differ diff --git a/mod4/datetime/pom.xml b/mod4/datetime/pom.xml new file mode 100644 index 0000000..6d29bcc --- /dev/null +++ b/mod4/datetime/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + + com.bhima + datetime + 1.0-SNAPSHOT + + datetime + + http://www.example.com + + + UTF-8 + 1.7 + 1.7 + + + + + junit + junit + 4.11 + test + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + diff --git a/mod4/datetime/src/main/java/com/bhima/App.java b/mod4/datetime/src/main/java/com/bhima/App.java new file mode 100644 index 0000000..45d8f22 --- /dev/null +++ b/mod4/datetime/src/main/java/com/bhima/App.java @@ -0,0 +1,56 @@ +package com.bhima; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.Date; + +public class App { + public App(String[] args) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + LocalDate ld = LocalDate.parse("02/07/2010", formatter); + String formatted = ld.format(formatter); + Date legacyDate = new Date(); + ZonedDateTime zdt = ZonedDateTime.ofInstant( + legacyDate.toInstant(), ZoneId.systemDefault()); + ld = zdt.toLocalDate(); + formatted = ld.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)); + System.out.println(formatted); + InnerApp_1 iApp_1 = new InnerApp_1(args); + } +} + +class InnerApp { + public static void main(String[] args) { + BigDecimal a = new BigDecimal("42.35"); + BigDecimal b; + b = a.setScale(1, RoundingMode.HALF_UP); + System.out.println(b.toString()); + b = a.setScale(1, RoundingMode.HALF_DOWN); + System.out.println(b.toString()); // 42.3 + BigDecimal op1 = new BigDecimal("10"); + BigDecimal op2 = new BigDecimal("4"); + BigDecimal c = op1.divide(op2); // ERROR + System.out.println(c); + c = op1.divide(op2, RoundingMode.HALF_UP); // 2 + System.out.println(c.toString()); + + c = op1.divide(op2, 2, RoundingMode.HALF_UP); // 1.67 + System.out.println(c.toString()); + + c = op1.divide(op2, 2, RoundingMode.DOWN); // 1.66 + System.out.println(c.toString()); + App app = new App(args); + + } +} + +class InnerApp_1 { + public InnerApp_1(String[] args) { + + } +} diff --git a/mod4/datetime/src/test/java/com/bhima/AppTest.java b/mod4/datetime/src/test/java/com/bhima/AppTest.java new file mode 100644 index 0000000..6e23f01 --- /dev/null +++ b/mod4/datetime/src/test/java/com/bhima/AppTest.java @@ -0,0 +1,20 @@ +package com.bhima; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Unit test for simple App. + */ +public class AppTest +{ + /** + * Rigorous Test :-) + */ + @Test + public void shouldAnswerWithTrue() + { + assertTrue( true ); + } +} diff --git a/mod4/demo/pom.xml b/mod4/demo/pom.xml new file mode 100644 index 0000000..24e5e42 --- /dev/null +++ b/mod4/demo/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + + com.example.bhima + demo + 1.0-SNAPSHOT + + demo + + http://www.example.com + + + UTF-8 + 1.7 + 1.7 + + + + + junit + junit + 4.11 + test + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + diff --git a/mod4/demo/src/main/java/com/example/bhima/App.java b/mod4/demo/src/main/java/com/example/bhima/App.java new file mode 100644 index 0000000..53e39e2 --- /dev/null +++ b/mod4/demo/src/main/java/com/example/bhima/App.java @@ -0,0 +1,13 @@ +package com.example.bhima; + +/** + * Hello world! + * + */ +public class App +{ + public static void main( String[] args ) + { + System.out.println( "Hello World!" ); + } +} diff --git a/mod4/demo/src/test/java/com/example/bhima/AppTest.java b/mod4/demo/src/test/java/com/example/bhima/AppTest.java new file mode 100644 index 0000000..d1b2e10 --- /dev/null +++ b/mod4/demo/src/test/java/com/example/bhima/AppTest.java @@ -0,0 +1,20 @@ +package com.example.bhima; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Unit test for simple App. + */ +public class AppTest +{ + /** + * Rigorous Test :-) + */ + @Test + public void shouldAnswerWithTrue() + { + assertTrue( true ); + } +} diff --git a/mod4/myspringproject/.gitignore b/mod4/myspringproject/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/mod4/myspringproject/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/mod4/myspringproject/.mvn/wrapper/maven-wrapper.jar b/mod4/myspringproject/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..c1dd12f Binary files /dev/null and b/mod4/myspringproject/.mvn/wrapper/maven-wrapper.jar differ diff --git a/mod4/myspringproject/.mvn/wrapper/maven-wrapper.properties b/mod4/myspringproject/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..b7cb93e --- /dev/null +++ b/mod4/myspringproject/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar diff --git a/mod4/myspringproject/mvnw b/mod4/myspringproject/mvnw new file mode 100755 index 0000000..8a8fb22 --- /dev/null +++ b/mod4/myspringproject/mvnw @@ -0,0 +1,316 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + 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 + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mod4/myspringproject/mvnw.cmd b/mod4/myspringproject/mvnw.cmd new file mode 100644 index 0000000..1d8ab01 --- /dev/null +++ b/mod4/myspringproject/mvnw.cmd @@ -0,0 +1,188 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. 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, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/mod4/myspringproject/pom.xml b/mod4/myspringproject/pom.xml new file mode 100644 index 0000000..b685067 --- /dev/null +++ b/mod4/myspringproject/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + com.example + serving-web-content-complete + 0.0.1-SNAPSHOT + serving-web-content-complete + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/mod4/myspringproject/src/main/java/com/bhima/myspringproject/Book.java b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/Book.java new file mode 100644 index 0000000..34c88c7 --- /dev/null +++ b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/Book.java @@ -0,0 +1,46 @@ +package com.bhima.myspringproject; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; + + +import org.springframework.data.annotation.Id; + +@Entity +public class Book { + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + private Integer id; + private String title; + private String author; + + public Book(String title){ + this.setTitle(title); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return this.author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/mod4/myspringproject/src/main/java/com/bhima/myspringproject/GreetingController.java b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/GreetingController.java new file mode 100644 index 0000000..e7150c7 --- /dev/null +++ b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/GreetingController.java @@ -0,0 +1,22 @@ +package com.bhima.myspringproject; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +public class GreetingController { + + @GetMapping("/greeting") + public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) { + model.addAttribute("name", name); + return "greeting"; + } + + @GetMapping("/error") + public String error() { + return "error"; + } + +} \ No newline at end of file diff --git a/mod4/myspringproject/src/main/java/com/bhima/myspringproject/MyspringprojectApplication.java b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/MyspringprojectApplication.java new file mode 100644 index 0000000..f5a5e88 --- /dev/null +++ b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/MyspringprojectApplication.java @@ -0,0 +1,13 @@ +package com.bhima.myspringproject; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MyspringprojectApplication { + + public static void main(String[] args) { + SpringApplication.run(MyspringprojectApplication.class, args); + } + +} diff --git a/mod4/myspringproject/src/main/java/com/bhima/myspringproject/RootReposotory.java b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/RootReposotory.java new file mode 100644 index 0000000..e69de29 diff --git a/mod4/myspringproject/src/main/java/com/bhima/myspringproject/ServletInitializer.java b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/ServletInitializer.java new file mode 100644 index 0000000..e7548ab --- /dev/null +++ b/mod4/myspringproject/src/main/java/com/bhima/myspringproject/ServletInitializer.java @@ -0,0 +1,13 @@ +package com.bhima.myspringproject; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +public class ServletInitializer extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(MyspringprojectApplication.class); + } + +} diff --git a/mod4/myspringproject/src/main/resources/application.properties b/mod4/myspringproject/src/main/resources/application.properties new file mode 100644 index 0000000..346fdd4 --- /dev/null +++ b/mod4/myspringproject/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:mysql://localhost:3306/library +spring.datasource.username=root +spring.datasource.passsword=mynewpassword +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver \ No newline at end of file diff --git a/mod4/myspringproject/src/main/resources/static/index.html b/mod4/myspringproject/src/main/resources/static/index.html new file mode 100644 index 0000000..bb4cc32 --- /dev/null +++ b/mod4/myspringproject/src/main/resources/static/index.html @@ -0,0 +1,21 @@ + + + + Getting Started: Serving Web Content + + + +

this is my first spring boot!

+

jdk!

+
  • Get your greeting here.
  • +
  • + click to make errors apere!!! +
  • + + + \ No newline at end of file diff --git a/mod4/myspringproject/src/main/resources/templates/error.html b/mod4/myspringproject/src/main/resources/templates/error.html new file mode 100644 index 0000000..00cd423 --- /dev/null +++ b/mod4/myspringproject/src/main/resources/templates/error.html @@ -0,0 +1,22 @@ + + + + What the HECK! + + +

    + 2022-06-01 12:04:47.975 INFO 47920 --- [ restartedMain] c.b.m.MyspringprojectApplication : Starting MyspringprojectApplication using Java 11.0.15 on bhima-Lenovo-ideapad-310-Touch-15ISK with PID 47920 (/home/bhima/dev/mod4/myspringproject/target/classes started by bhima in /home/bhima/dev/mod4/myspringproject) + 2022-06-01 12:04:47.976 INFO 47920 --- [ restartedMain] c.b.m.MyspringprojectApplication : No active profile set, falling back to default profiles: default + 2022-06-01 12:04:48.444 INFO 47920 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): ${name} (http) + 2022-06-01 12:04:48.447 INFO 47920 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] + 2022-06-01 12:04:48.448 INFO 47920 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56] + 2022-06-01 12:04:48.463 INFO 47920 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext + 2022-06-01 12:04:48.464 INFO 47920 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 482 ms + 2022-06-01 12:04:48.577 INFO 47920 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html] + 2022-06-01 12:04:48.640 INFO 47920 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 + 2022-06-01 12:04:48.680 INFO 47920 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' + 2022-06-01 12:04:48.691 INFO 47920 --- [ restartedMain] c.b.m.MyspringprojectApplication : Started MyspringprojectApplication in 0.763 seconds (JVM running for 1725.67) + 2022-06-01 12:04:48.697 INFO 47920 --- [ restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged +

    + + \ No newline at end of file diff --git a/mod4/myspringproject/src/main/resources/templates/greeting.html b/mod4/myspringproject/src/main/resources/templates/greeting.html new file mode 100644 index 0000000..6ec386d --- /dev/null +++ b/mod4/myspringproject/src/main/resources/templates/greeting.html @@ -0,0 +1,10 @@ + + + + Getting Started: Serving Web Content + + + +

    + + diff --git a/mod4/myspringproject/src/test/java/com/bhima/myspringproject/MyspringprojectApplicationTests.java b/mod4/myspringproject/src/test/java/com/bhima/myspringproject/MyspringprojectApplicationTests.java new file mode 100644 index 0000000..c747228 --- /dev/null +++ b/mod4/myspringproject/src/test/java/com/bhima/myspringproject/MyspringprojectApplicationTests.java @@ -0,0 +1,13 @@ +package com.bhima.myspringproject; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MyspringprojectApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/mod4/randomWord/.vscode/settings.json b/mod4/randomWord/.vscode/settings.json new file mode 100644 index 0000000..e112a70 --- /dev/null +++ b/mod4/randomWord/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "java.project.sourcePaths": ["src"], + "java.project.outputPath": "bin", + "java.project.referencedLibraries": [ + "lib/**/*.jar" + ] +} diff --git a/mod4/randomWord/README.md b/mod4/randomWord/README.md new file mode 100644 index 0000000..7c03a53 --- /dev/null +++ b/mod4/randomWord/README.md @@ -0,0 +1,18 @@ +## Getting Started + +Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. + +## Folder Structure + +The workspace contains two folders by default, where: + +- `src`: the folder to maintain sources +- `lib`: the folder to maintain dependencies + +Meanwhile, the compiled output files will be generated in the `bin` folder by default. + +> If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. + +## Dependency Management + +The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). diff --git a/mod4/randomWord/java b/mod4/randomWord/java new file mode 100644 index 0000000..e69de29 diff --git a/mod4/randomWord/json b/mod4/randomWord/json new file mode 100644 index 0000000..e69de29 diff --git a/mod4/randomWord/random word.jar b/mod4/randomWord/random word.jar new file mode 100644 index 0000000..8fe453c Binary files /dev/null and b/mod4/randomWord/random word.jar differ diff --git a/mod4/randomWord/src/App.java b/mod4/randomWord/src/App.java new file mode 100644 index 0000000..790395f --- /dev/null +++ b/mod4/randomWord/src/App.java @@ -0,0 +1,111 @@ +import java.util.Random; + +public class App { + public static void main(String[] args) throws Exception { + Random random = new Random(); + System.out.println(getWord(random)); + } + + private static String getWord(Random random) { + int times = randomNum(random, 10) + 1; + String word = ""; + for (int i = 0; i < times; i++) { + word = word + numToWord(randomNum(random, 27)); + } + + return word; + } + + private static String numToWord(int num) { + + switch (num) { + case 0: + return "a"; + case 1: + + return "b"; + case 2: + + return "c"; + case 3: + + return "d"; + case 4: + + return "e"; + case 5: + + return "f"; + case 6: + + return "g"; + case 7: + + return "h"; + case 8: + + return "i"; + case 9: + + return "j"; + case 10: + + return "k"; + case 11: + + return "l"; + case 12: + + return "m"; + case 13: + + return "n"; + case 14: + + return "o"; + case 15: + + return "p"; + case 16: + + return "q"; + case 17: + + return "r"; + case 18: + + return "s"; + case 19: + + return "t"; + case 20: + + return "u"; + case 21: + + return "v"; + case 22: + + return "w"; + case 23: + + return "x"; + case 24: + + return "y"; + case 25: + + return "z"; + case 26: + + return " "; + case 27: + return ""; + } + return null; + } + + private static int randomNum(Random random, int bound) { + return random.nextInt(bound); + } +} diff --git a/mod4/randomWord/src/RandomWord.java b/mod4/randomWord/src/RandomWord.java new file mode 100644 index 0000000..ab55975 --- /dev/null +++ b/mod4/randomWord/src/RandomWord.java @@ -0,0 +1,111 @@ +import java.util.Random; + +public class RandomWord { + private Random random; + public RandomWord(Random random){ + this.random = random; + } + + public String getWord() { + int times = this.randomNum(this.random, 12) + 1; + String word = ""; + for (int i = 0; i < times; i++) { + word = word + this.numToWord(randomNum(this.random, 27)); + } + + return word; + } + + private String numToWord(int num) { + + switch (num) { + case 0: + return "a"; + case 1: + + return "b"; + case 2: + + return "c"; + case 3: + + return "d"; + case 4: + + return "e"; + case 5: + + return "f"; + case 6: + + return "g"; + case 7: + + return "h"; + case 8: + + return "i"; + case 9: + + return "j"; + case 10: + + return "k"; + case 11: + + return "l"; + case 12: + + return "m"; + case 13: + + return "n"; + case 14: + + return "o"; + case 15: + + return "p"; + case 16: + + return "q"; + case 17: + + return "r"; + case 18: + + return "s"; + case 19: + + return "t"; + case 20: + + return "u"; + case 21: + + return "v"; + case 22: + + return "w"; + case 23: + + return "x"; + case 24: + + return "y"; + case 25: + + return "z"; + case 26: + + return " "; + case 27: + return ""; + } + return null; + } + + private int randomNum(Random random, int bound) { + return random.nextInt(bound); + } +} diff --git a/mod4/rats/.vscode/settings.json b/mod4/rats/.vscode/settings.json new file mode 100644 index 0000000..d71dfa0 --- /dev/null +++ b/mod4/rats/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "java.configuration.updateBuildConfiguration": "automatic", + "maven.view": "flat" +} \ No newline at end of file diff --git a/mod4/rats/pom.xml b/mod4/rats/pom.xml new file mode 100644 index 0000000..035aef9 --- /dev/null +++ b/mod4/rats/pom.xml @@ -0,0 +1,80 @@ + + + + 4.0.0 + + com.text + rats + 1.0-SNAPSHOT + + rats + + http://www.example.com + + + UTF-8 + 1.7 + 1.7 + + + + + junit + junit + 4.11 + test + + + org.springframework + spring-context + 5.3.20 + + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + \ No newline at end of file diff --git a/mod4/rats/src/main/applicationContext.xml b/mod4/rats/src/main/applicationContext.xml new file mode 100644 index 0000000..bd4594a --- /dev/null +++ b/mod4/rats/src/main/applicationContext.xml @@ -0,0 +1,20 @@ + + + + + + \ No newline at end of file diff --git a/mod4/rats/src/main/java/com/text/App.java b/mod4/rats/src/main/java/com/text/App.java new file mode 100644 index 0000000..7798015 --- /dev/null +++ b/mod4/rats/src/main/java/com/text/App.java @@ -0,0 +1,22 @@ +package com.text; + +public class App { + // When squirrels get together for a party, they like to have cigars. + // A squirrel party is successful when the number of cigars is between + // 40 and 60, inclusive. Unless it is the weekend, in which case there + // is no upper bound on the number of cigars. Return true if the party + // with the given values is successful, or false otherwise. + // + // greatParty(30, false) → false + // greatParty(50, false) → true + // greatParty(70, true) → true + public boolean greatParty(int cigars, boolean isWeekend) { + if (cigars > 40 && cigars < 60 && !isWeekend) { + return true; + } else if (cigars > 40 && isWeekend) { + return true; + } else { + return false; + } + } +} diff --git a/mod4/rats/src/test/java/com/text/GreatePartyTest.java b/mod4/rats/src/test/java/com/text/GreatePartyTest.java new file mode 100644 index 0000000..fa27c89 --- /dev/null +++ b/mod4/rats/src/test/java/com/text/GreatePartyTest.java @@ -0,0 +1,5 @@ +package com.text; + +public class GreatePartyTest { + +} diff --git a/mod4/server of the gods/.vscode/settings.json b/mod4/server of the gods/.vscode/settings.json new file mode 100644 index 0000000..e112a70 --- /dev/null +++ b/mod4/server of the gods/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "java.project.sourcePaths": ["src"], + "java.project.outputPath": "bin", + "java.project.referencedLibraries": [ + "lib/**/*.jar" + ] +} diff --git a/mod4/server of the gods/README.md b/mod4/server of the gods/README.md new file mode 100644 index 0000000..7c03a53 --- /dev/null +++ b/mod4/server of the gods/README.md @@ -0,0 +1,18 @@ +## Getting Started + +Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. + +## Folder Structure + +The workspace contains two folders by default, where: + +- `src`: the folder to maintain sources +- `lib`: the folder to maintain dependencies + +Meanwhile, the compiled output files will be generated in the `bin` folder by default. + +> If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. + +## Dependency Management + +The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). diff --git a/mod4/server of the gods/src/App.java b/mod4/server of the gods/src/App.java new file mode 100644 index 0000000..a21cba8 --- /dev/null +++ b/mod4/server of the gods/src/App.java @@ -0,0 +1,7 @@ +import java.util.Random; + +public class App { + public static void main(String[] args) throws Exception { + RandomWord foo = new RandomWord(new Random()); + } +} diff --git a/mod4/server of the gods/src/dao/DaoMemoryImpl.java b/mod4/server of the gods/src/dao/DaoMemoryImpl.java new file mode 100644 index 0000000..d57c431 --- /dev/null +++ b/mod4/server of the gods/src/dao/DaoMemoryImpl.java @@ -0,0 +1,76 @@ +package dao; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import interfaces.dao; +import modle.Server; + +public class DaoMemoryImpl implements dao { + + private Map serverMap = new HashMap<>(); + + @Override + public void addServer(Server server) { + serverMap.put(server.getName(), server); + } + + @Override + public Server getServer(String name) { + return serverMap.get(name); + } + + @Override + public void removeServer(String name) { + serverMap.remove(name); + } + + @Override + public List getAllServers() { + return new ArrayList(serverMap.values()); + } + + @Override + public Map> getAllServersGroupByManufacturer() { + return serverMap.values() + .stream() + .collect(Collectors.groupingBy(Server::getManufacturer)); + } + + @Override + public List getServersByManufacturer(String manufacturer) { + return serverMap.values() + .stream() + .filter(s -> s.getManufacturer().equalsIgnoreCase(manufacturer)) + .collect(Collectors.toList()); + } + + @Override + public List getServersOlderThan(int ageInYears) { + return serverMap.values() + .stream() + .filter(s -> s.getServerAge() > ageInYears) + .collect(Collectors.toList()); + } + + @Override + public Map> getServersOlderThanGroupByManufacturer(int ageInYears) { + return this.getServersOlderThan(ageInYears) + .stream() + .collect(Collectors.groupingBy(Server::getManufacturer)); + } + + @Override + public double getAverageServerAge() { + return serverMap.values() + .stream() + .mapToLong(s -> s.getServerAge()) + // .mapToLong(Server::getServerAge) + .average() + .getAsDouble(); + } + +} diff --git a/mod4/server of the gods/src/interfaces/dao.java b/mod4/server of the gods/src/interfaces/dao.java new file mode 100644 index 0000000..c446db1 --- /dev/null +++ b/mod4/server of the gods/src/interfaces/dao.java @@ -0,0 +1,18 @@ +package interfaces; + +import java.util.List; +import java.util.Map; + +import modle.Server; + +public interface dao { + public void addServer(Server server); + public Server getServer(String name); + public void removeServer(String name); + public List getAllServers(); + public Map> getAllServersGroupByManufacturer(); + public List getServersByManufacturer(String manufacturer); + public List getServersOlderThan(int ageInYears); + public Map> getServersOlderThanGroupByManufacturer(int ageInYears); + public double getAverageServerAge(); +} diff --git a/mod4/server of the gods/src/modle/Server.java b/mod4/server of the gods/src/modle/Server.java new file mode 100644 index 0000000..89855ae --- /dev/null +++ b/mod4/server of the gods/src/modle/Server.java @@ -0,0 +1,75 @@ +package modle; + +import java.time.LocalDate; +import java.time.Period; + +public class Server { + private String name; + private String ip; + private String manufacturer; + private int ram; + private int numProcessors; + private LocalDate purchaseDate; + + public Server(String name, String ip, String manufacturer, int ram, int numProcessors, LocalDate purchaseDate){ + this.setIp(ip); + this.setManufacturer(manufacturer); + this.setNumProcessors(numProcessors); + this.setPurchaseDate(purchaseDate); + this.setRam(ram); + this.setName(name); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + + public int getRam() { + return ram; + } + + public void setRam(int ram) { + this.ram = ram; + } + + public int getNumProcessors() { + return numProcessors; + } + + public void setNumProcessors(int numProcessors) { + this.numProcessors = numProcessors; + } + + public LocalDate getPurchaseDate() { + return purchaseDate; + } + + public void setPurchaseDate(LocalDate purchaseDate) { + this.purchaseDate = purchaseDate; + } + + public long getServerAge() { + Period p = purchaseDate.until(LocalDate.now()); + return p.getYears(); + } +}