ArrayList of objects sort using comparable - java

so I'm working on an address book assignment and I'm stuck on getting Comparable to sort the contacts by last name. I'm trying stuff that we haven't really learned like ArrayLists of objects, comparable and Serializable and comparable is confusing me the most.
Any tips on why the contacts aren't sorting? Second question, I wanted to try and make the first character of the first and last name an uppercase but I just couldn't figure it out so I made the whole thing uppercase in the toString method, any ideas how to get only the first char upper?
public class AddressBook implements Serializable{
private ArrayList<String> newBook = new ArrayList<String>();
private String dataFile;
private ArrayList<Contact> card =new ArrayList<Contact>(50);
private Contact[] contacts;
private int size = 0;
private int capacity = 0;
private String firstName;
private String lastName;
public static void main(String[] args) {
AddressBook AB = new AddressBook();
AB.addressBookMenu();
}
public void addressBookMenu() {
Scanner scan = new Scanner(System.in);
String option = "";
System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
System.out.println("\t add --> Add a new contact ");
System.out.println("\t find --> Find a contact ");
System.out.println("\t edit --> Edit an existing contact ");
System.out.println("\t view --> View the current address book");
System.out.println("\t save --> Save the current address book");
System.out.println("\t quit --> quit");
System.out.println();
option = scan.nextLine();
while(!(option.equalsIgnoreCase("quit"))) {
Contact con = new Contact(firstName, lastName);
if(option.equalsIgnoreCase("add")) {
System.out.println("Enter First Name: ");
String tempFirst = scan.nextLine();
System.out.println("Enter Last Name: ");
String tempLast = scan.nextLine();
con.setFirstName(tempFirst);
con.setLastName(tempLast);
card.add(con);
writeContact();
}
//View address book
if(option.equalsIgnoreCase("view")) {
System.out.println("\tADDRESS BOOK" + "\n" +
"=============================");
Collections.sort(card);
con.getFullName();
readContact();
}
System.out.println();
System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
System.out.println("\t add --> Add a new contact ");
System.out.println("\t find --> Find a contact ");
System.out.println("\t edit --> Edit an existing contact ");
System.out.println("\t view --> View the current address book");
System.out.println("\t save --> Save the current address book");
System.out.println("\t quit --> quit");
System.out.println();
option = scan.nextLine();
}
}
public void writeContact() {
try (FileOutputStream out = new FileOutputStream("addressbook.txt")) {
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(card);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readContact() {
try (FileInputStream in = new FileInputStream("addressbook.txt")) {
ObjectInputStream is = new ObjectInputStream(in);
ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();
for(Contact temp : card) {
System.out.println(temp);
}
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Contact Class
public class Contact implements Comparable<Contact>, Serializable{
private String firstName;
private String lastName;
private String email;
private String phone;
public Contact() {
firstName = "";
lastName = "";
}
public Contact(String ln, String fn) {
lastName = ln;
firstName = fn;
}
public void setFirstName(String fn) {
firstName = fn;
}
public void setLastName(String ln) {
lastName = ln;
}
public void setFullName(String fn, String ln) {
firstName = fn;
lastName = ln;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return lastName + firstName;
}
public String toString() {
return
"FIRST NAME: " + getFirstName().substring(0).toUpperCase() + "\t" +
"LAST NAME: " + getLastName().substring(0).toUpperCase() + "\n";
}
#Override
public int compareTo(Contact nextContact) {
return lastName.compareTo(nextContact.lastName);
}
}

Your problem is as follows:
This code snippet
Collections.sort(card);
con.getFullName();
readContact();
is actually sorting the card collection you have, and then you call readContact() method which creates a local card collection inside it, which shadows the card collection you have in your main program, and prints its contacts, as they were written to the file before. they don't get sorted.
the solution would be like this:
if(option.equalsIgnoreCase("view")) {
System.out.println("\tADDRESS BOOK" + "\n" +
"=============================");
con.getFullName(); // <------ ALSO, NOT QUITE SURE WHAT THIS IS FOR
readContact();
}
public void readContact() {
try (FileInputStream in = new FileInputStream("addressbook.txt")) {
ObjectInputStream is = new ObjectInputStream(in);
ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();
Collections.sort(card); // <----------- THIS ADDED
for(Contact temp : card) {
System.out.println(temp);
}
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Any tips on why the contacts aren't sorting?
They are sorting. But then you don't print the sorted card.
You re-read the contacts in readContact and then print them, unsorted.
Probably you meant to write it this way instead:
if(option.equalsIgnoreCase("view")) {
System.out.println("\tADDRESS BOOK" + "\n" +
"=============================");
readContact();
Collections.sort(card);
printContacts();
}
And in readContact change this line:
ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();
To this:
card = (ArrayList<Contact>)is.readObject();
And move the printing out from readContact to its own method:
void printContacts() {
for(Contact temp : card) {
System.out.println(temp);
}
}
Second question, [...] any ideas how to get only the first char upper?
Sure, with a helper method like this:
private String toTitleCase(String name) {
return Character.toTitleCase(name.charAt(0)) + name.substring(1).toLowerCase();
}

Related

Java program not saving object to HashMap

Either my save_product function in my Repository.java class doesn't save correctly into the map product_repository or, maybe it does save, but I'm not outputting it correctly in my find_product function in my Repository.java class. I think I'm using the correct function to search for the value in the map, .get
I experimented with product_repository.keySet().iterator().forEachRemaining(System.out::println); but that's the first time I ever used that... also please forgive how I insert the keyinto the map product_repository in the create_new_product function in the Controller.java class. I'm new to java ...
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
Product.java
package com.company;
public class Product {
private String product_name;
private String product_brand;
private int product_cost;
private int product_count;
private boolean product_availability;
public Product() {
}
public Product(String product_name, String product_brand,
int product_cost, int product_count, boolean product_availability) {
this.product_name = product_name;
this.product_brand = product_brand;
this.product_cost = product_cost;
this.product_count = product_count;
this.product_availability = product_availability;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_cost() {
return product_cost;
}
public void setProduct_cost(int product_cost) {
this.product_cost = product_cost;
}
public int getProduct_count() {
return product_count;
}
public void setProduct_count(int product_count) {
this.product_count = product_count;
}
public boolean isProduct_availability() {
return product_availability;
}
public void setProduct_availability(boolean product_availability) {
this.product_availability = product_availability;
}
}
Controller.java
package com.company;
import java.util.Scanner;
public class Controller {
private static Long key;
public static void create_new_product(){
Repository repository = new Repository();
//Supplier supplier = new Supplier();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
key = 0L;
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
key++;
repository.save_product(key, product);
}
public void search_product(){
Repository repository = new Repository();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
repository.find_product(id);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
repository.find_product(name);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
Repository.java
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
You have to make Repository repository a field of your Controller class. You are currently throwing the repositories away after your methods create_new_product and search_product have executed. Therefore you need to remove the first line of each of these methods.
Another problem is inside your find_product(String name) method where your call product_repository.get(name) but name is a String and the get method expects an ID, i.e. a Long so this call will always return null.
As it was pointed out before the repository has to be made global. However, the entire code is a bit messy. You are searching for a product id but the id is not shown to you. It is like searching for database records but the ids are autogenerated. Good luck with that. So I would suggest to allow this program to enter the id as well. It makes much more sense if you want to search for the id.
Otherwise, if you are interested in only the value, id can be taken out.
Below you can find the modified code that works for all the methods.
//main stays the same
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
//controller is a bit changed. Added global repository and improved the search.
import java.util.Collection;
import java.util.Scanner;
public class Controller {
private static Long key;
Repository repository = new Repository();
public void create_new_product() {
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product id: ");
long id = Long.parseLong(scanner.nextLine());
product.setProductId(id);
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
repository.save_product(id, product);
}
public void search_product() {
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
Product product = repository.find_product(id);
try {
if (product.getProduct_count() > 0) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
} else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
Collection<Product> products = repository.find_products(name);
if (products.size() > 0) {
for (Product product : products) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} else {
System.out.println(" out of stock.");
}
} else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
//Added a new field to the Repository so you can also search by key.
import java.util.*;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap) {
try {
if (!product_repository.containsKey(key)) {
product_repository.put(key, newProductMap);
} else {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public Product find_product(final Long key) {
try {
if (product_repository.containsKey(key)) {
System.out.println("Found product: " + product_repository.get(key).getProduct_name());
return product_repository.get(key);
} else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
return null;
}
// Overload
public Collection<Product> find_products(final String name) {
Collection<Product> values = new ArrayList<>();
for (Map.Entry<Long, Product> productEntry : product_repository.entrySet()) {
if (productEntry.getValue().getProduct_name().equals(name)) {
System.out.println("matches were found for product name: " + name);
values.add(productEntry.getValue());
}
}
return values;
}
}

How can I format the different sections of the input .txt in Java

I need to format the I/O text, which comes from a .txt file. I am able to print it, but I can't separate it in the different categories.
public class Main {
public static void main(String[] args) throws Exception {
class Recipe implements java.io.Serializable {
private String name, ingredients, steps;
public Recipe(String name, String ingredients, String steps) {
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
}
public String toString(){
return "dishName: " + name + " ingredients: " + ingredients + " steps: ";
}
}
Scanner input = null;
try {
//Choose the file that you will use.
input = new Scanner (new BufferedReader(new FileReader ("Root/src/recipes.txt")));
while ( input.hasNext() ) {
System.out.println(input.nextLine());
}
//Read your input and create the Objects Recipe
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null){
input.close();
}
} finally {
if (input != null){
input.close();
}
}
}
}
}

Client-server application in Java

I have a server application in Java, that holds a list of Student objects (implementing Serializable). The client application sends a message with an integer - index of Student object to fetch. Then the selected Student is sent to the client, the client modifies its value and sends back. The application however freezes at some point, and it's probably a problem with the lines I emphasized in the code below.
Server:
public class Server {
public static void main(String[] arg) {
ArrayList <Student> studentList = new ArrayList <Student> ();
studentList.add(new Student(170435, "justyna", "kaluzka", new ArrayList <Float>()));
studentList.add(new Student(170438, "michal", "szydlowski", new ArrayList <Float>()));
studentList.add(new Student(170436, "marek", "polewczyk", new ArrayList <Float>()));
studentList.add(new Student(170439, "jakub", "szydlowski", new ArrayList <Float>()));
studentList.add(new Student(170430, "anna", "majchrzak", new ArrayList <Float>()));
studentList.add(new Student(170425, "krzysztof", "krawczyk", new ArrayList <Float>()));
studentList.add(new Student(170445, "adam", "szydlowski", new ArrayList <Float>()));
studentList.add(new Student(170415, "karol", "chodkiewicz", new ArrayList <Float>()));
studentList.add(new Student(170465, "artur", "schopenhauer", new ArrayList <Float>()));
ServerSocket socketConnection = null;
ObjectInputStream serverInputStream = null;
ObjectOutputStream serverOutputStream = null;
try {
socketConnection = new ServerSocket(11111);
System.out.println("Server Waiting");
Socket pipe = socketConnection.accept();
serverOutputStream = new ObjectOutputStream( pipe.getOutputStream());
serverInputStream = new ObjectInputStream( pipe.getInputStream());
int index = serverInputStream.readInt();
System.out.println(index);
// HERE'S WHEN THE PROBLEM STARTS
serverOutputStream.writeObject(studentList.get(index));
Student student = (Student) serverInputStream.readObject();
System.out.println(student.toString());
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
serverInputStream.close();
serverOutputStream.close();
socketConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client:
public class Client {
public static void main(String[] arg) {
Student student = null;
Socket socketConnection = null;
ObjectOutputStream clientOutputStream = null;
ObjectInputStream clientInputStream = null;
try {
socketConnection = new Socket("127.0.0.1", 11111);
clientOutputStream = new ObjectOutputStream(socketConnection.getOutputStream());
clientInputStream = new ObjectInputStream(socketConnection.getInputStream());
clientOutputStream.writeInt(0);
student = (Student) clientInputStream.readObject();
student.setFamilyName("Konopnicka");
clientOutputStream.writeObject(student);
} catch (Exception e) {
System.out.println(e);
} finally {
try {
clientOutputStream.close();
clientInputStream.close();
socketConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My knowledge of client-server sockets is vague, so it's most likely a simple mistake. Any ideas?
EDIT:
Student class
public class Student implements Serializable {
private static final long serialVersionUID = -5169551431906499332L;
private int indexNumber;
private String name;
private String familyName;
private ArrayList<Float> marks;
private float average;
public Student(int indexNumber, String name, String familyName,
ArrayList<Float> marks) {
this.indexNumber = indexNumber;
this.name = name;
this.familyName = familyName;
this.marks = marks;
this.average = 0;
generateMarks();
calculateAverage();
}
public int getIndexNumber() {
return indexNumber;
}
public void setIndexNumber(int indexNumber) {
this.indexNumber = indexNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public float getAverage() {
return average;
}
public void setAverage(float average) {
this.average = average;
}
/**
* Calculates average of all Student's marks.
*/
public void calculateAverage() {
float sum = 0;
for (int i = 0; i < marks.size(); i++) {
sum += marks.get(i);
}
this.average = sum / marks.size();
}
/**
* Generates a random set of marks for the student.
*/
public void generateMarks() {
for (int i = 0; i < 10; i++) {
addMark(new Random().nextFloat() * 5);
}
}
/**
* Mark getter
*
* #return String representation of marks
*/
public String getMarks() {
String marksstr = "";
for (int i = 0; i < marks.size(); i++) {
marksstr += marks.get(i).toString() + " ";
}
return marksstr;
}
/**
* Adds a mark to the list.
*
* #param mark
*/
public void addMark(float mark) {
marks.add(mark);
}
#Override
public String toString() {
return "Index number:" + indexNumber + "\tName:" + name
+ "\tFamily name:" + familyName + "\t\tAverage:" + getAverage()
+ "\n";
}
}
Initialize your ObjectOutputStream before your ObjectInputSteam on your server.
When you initialize an ObjectInputStream, it waits for "header" data. Your server is waiting for that header data. You need to initialize your ObjectOutputStream first (which sends the header data), THEN your ObjectInputStream.
You can find more about this in here
You must flush your ObjectOutputStream after writing the int. When you write data to a stream, it gets written into a buffer. Data from that buffer is only sent when the stream's buffer is full. An int does not fill it, so you must flush() it to manually send the data from the buffer.

How to call different remote objects on same interface method and maintain their own data? java RMI

I have server class which implements common interface between client and server. I have multiple remote objects bonded to different rim registry(diff ports and rim_id). Client will lookup the registry based on clientID for e.g. IF clientID is EXE1111 then it should connects to EXE server remote object. I want each server object to have its own hashtable to store data given by client. Here is server code::
enter code here
public class StationServers extends UnicastRemoteObject implements StationService{
private static final long serialVersionUID = 8119533223378875144L;
private String criminalRecordID="CR";
private String missingRecordID="MR";
private int count=11111;
protected StationServers() throws RemoteException {
super();
}
public static void main(String args[]){
try {
bindSPVMServer(new StationServers());
bindSPLServer(new StationServers());
bindSPBServer(new StationServers());
System.out.print("Servers are up and running on ");
System.out.println(InetAddress.getLocalHost().getHostName());
} catch (Exception e) {
System.err.println("Server start up error: "+e.getMessage());
e.printStackTrace();
}
}
private static void bindSPVMServer(StationServers spvmObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPVM_RMI_PORT);
reg.bind(Constants.SPVM_RMI_ID, spvmObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void bindSPLServer(StationServers splObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPL_RMI_PORT);
reg.bind(Constants.SPL_RMI_ID, splObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void bindSPBServer(StationServers spbObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPB_RMI_PORT);
reg.bind(Constants.SPB_RMI_ID, spbObject);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void createCRecord(String firstName, String lastName,
String description, RecordStatus status) throws RemoteException {
}
#Override
public void createMRecord(String firstName, String lastName,
String address, String lastDate, String lastLocation,
RecordStatus status) throws RemoteException {
// TODO Auto-generated method stub
}
#Override
public String getRecordCounts() throws RemoteException {
// TODO Auto-generated method stub
return null;
}
#Override
public void editCRecord(String lastName, String recordID,
RecordStatus newStatus) throws RemoteException {
// TODO Auto-generated method stub
}
}
Client Code::
enter code here
public class OfficerClients implements Runnable{
public static void showMenu() {
System.out.println("\n****Welcome to DPIS****\n");
System.out.println("Please select an option (1-5)");
System.out.println("1. Create Criminal Record");
System.out.println("2. Create Missing Record");
System.out.println("3. Get Records Count");
System.out.println("4. Edit Record");
System.out.println("5. Exit");
}
public static void main(String[] args) {
try {
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
new Thread(new OfficerClients()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private static RecordStatus getRecordStatus(String status, int userChoice) {
if (userChoice == 1) {
if (RecordStatus.CAPTURED.name().equals(status))
return RecordStatus.CAPTURED;
else if (RecordStatus.ONTHERUN.name().equals(status))
return RecordStatus.ONTHERUN;
else
throw new IllegalArgumentException("Invalid status for Criminal Record");
} else if (userChoice == 2) {
if (RecordStatus.FOUND.name().equals(status))
return RecordStatus.FOUND;
else if (RecordStatus.MISSING.name().equals(status))
return RecordStatus.MISSING;
else
throw new IllegalArgumentException("Invalid status for Missing Record");
} else if (userChoice == 3) {
if (RecordStatus.CAPTURED.name().equals(status))
return RecordStatus.CAPTURED;
else if (RecordStatus.ONTHERUN.name().equals(status))
return RecordStatus.ONTHERUN;
else if (RecordStatus.FOUND.name().equals(status))
return RecordStatus.FOUND;
else if (RecordStatus.MISSING.name().equals(status))
return RecordStatus.MISSING;
}
throw new IllegalArgumentException("No Enum specified for this string");
}
private static StationService getRemoteObjectStub(String stationName) {
String url = "rmi://localhost:";
Remote lookup = null;
try {
if ("SPVM".equals(stationName))
url += Constants.SPVM_RMI_PORT;
else if ("SPL".equals(stationName))
url += Constants.SPL_RMI_PORT;
else if ("SPB".equals(stationName))
url += Constants.SPB_RMI_PORT;
url += "/" + stationName;
System.out.println("URL==" + url);
if (url != null && !url.isEmpty())
lookup = Naming.lookup(url);
} catch (Exception e) {
e.printStackTrace();
}
return (StationService) lookup;
}
#Override
public void run() {
int userChoice = 0;
String firstName = "", lastName = "", description = "", address = "", lastDate = "", lastLocation = "", badgeID = "", recStatus = "", recordID = "";
RecordStatus status;
String requestBadgeID = "Please enter your unique BadgeID: ";
String requestRecordID = "Please enter RecordID: ";
String requestFName = "First Name: ";
String requestLName = "Last Name: ";
String requestDesc = "Description of Crime: ";
String requestAddress = "Last Known Address: ";
String requestDate = "Date last seen: ";
String requestPlace = "Place last seen: ";
String requestStatus = "Status: ";
String requestNewStatus = "New Status: ";
showMenu();
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
try{
while (true) {
Boolean valid = false;
System.out.print(requestBadgeID);
badgeID = br.readLine().toUpperCase();
System.out.println(badgeID);
String stationName = badgeID.replaceAll("[0-9]", "").trim();
System.out.println(stationName);
StationService server = getRemoteObjectStub(stationName);
while (!valid) {
try {
System.out.print("Enter your choice: ");
userChoice = Integer.parseInt(br.readLine());
valid = true;
} catch (Exception e) {
System.out
.println("Invalid Input, please enter an integer: ");
valid = false;
}
}
switch (userChoice) {
case 1:
System.out.print(requestFName);
firstName = br.readLine().trim().toUpperCase();
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestDesc);
description = br.readLine().trim().toUpperCase();
System.out.print(requestStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.createCRecord(firstName, lastName, description,
status);
showMenu();
break;
case 2:
System.out.print(requestFName);
firstName = br.readLine().trim().toUpperCase();
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestAddress);
address = br.readLine().trim().toUpperCase();
System.out.print(requestDate);
lastDate = br.readLine().trim().toUpperCase();
System.out.print(requestPlace);
lastLocation = br.readLine().trim().toUpperCase();
System.out.print(requestStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.createMRecord(firstName, lastName, requestAddress,
lastDate, lastLocation, status);
showMenu();
break;
case 3:
String recordCounts = server.getRecordCounts();
System.out.println(recordCounts);
showMenu();
break;
case 4:
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestRecordID);
recordID = br.readLine().trim().toUpperCase();
System.out.print(requestNewStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.editCRecord(lastName, recordID, status);
showMenu();
break;
case 5:
System.out.println("Have a nice day!");
br.close();
System.exit(0);
default:
System.out.println("Invalid Input, please try again.");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
I am new to RMI so I don't have any idea how to maintain each remote object and invoke based on client request and store records in hash table (per remote object).
please help...
You've described most of it yourself. Just create multiple instances of the remote object; bind each one into the Registry under a different name; have the client look up the appropriate name every time it wants that specific instance; and call the method via the stub that gets returned by that lookup.
Bingo.

ArrayList becomes null while writing to file

My arraylist<"obj"> becomes null after trying to write to a file.
In WriteToFile class arraylist info becomes null after executing the last line
writer.write(info.get(i).getIpadd().toString()+"\n");
It works on the first instance when i am writing another list to file but does not when i run it the 2nd instance. I dun understand why its happening. Below is the whole code and the stack trace.
WriteToFile Class:
public class WriteToFile {
public WriteToFile(ArrayList<Information> info,String location)
{
FileWriter writer=null;
try
{
writer = new FileWriter(location);
System.out.println(info.size());
for(int i=0;i<info.size()-1;i++)
{
writer.write(info.get(i).getDate().toString()+",");
writer.write(info.get(i).getAccount().toString()+",");
writer.write(info.get(i).getStatus().toString()+",");
writer.write(info.get(i).getIpadd().toString()+"\n");
System.out.println(info.get(i).getAccount());
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StackTrace:
java.lang.NullPointerException
at WriteToFile.<init>(WriteToFile.java:17)
at Gen_Report.<init>(Gen_Report.java:45)
at Gen_Report.main(Gen_Report.java:57)
main:
public class Gen_Report {
public Gen_Report()
{
// TODO Auto-generated constructor stub
//locate file and read all text from .log file to .csv
//file is found.so read text from it and extract all date/time, email add ,accepts and rejects,ip add, delete
Date date=new Date();
String[] dateTokens=date.toString().split(" ");
String dateString=dateTokens[2]+dateTokens[1]+dateTokens[5]+"_"+dateTokens[3].substring(0, 2)+dateTokens[3].substring(3,5)+dateTokens[3].substring(6, 8);
String logFileLocation = "/Users/gundu_87/Documents/workspace/GenFLRReport/";
ReaderFromLog rfl = new ReaderFromLog(logFileLocation+"radsecproxy.log");
//include duplicates
WriteToFile wtf = new WriteToFile(rfl.log,logFileLocation+dateString+"_FLRlogduplicates.txt");
//exclude duplicates
RemoveDuplicatesInList rdil = new RemoveDuplicatesInList(logFileLocation+dateString+"_FLRlogduplicates.txt");
for(int i=0;i<rdil.log.size();i++)
{
System.out.println(rdil.log.get(i).getAccount());
}
wtf = new WriteToFile(rdil.log,logFileLocation+dateString+"_FLRlog.txt");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen_Report gr= new Gen_Report();
}
}
Information class:
public class Information {
private String ipadd;
private String status;
private String account;
private String date;
public String getIpadd() {
return ipadd;
}
public void setIpadd(String ipadd) {
this.ipadd = ipadd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReaderFromLog class
public class ReaderFromLog {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public ReaderFromLog(String logFileLocation) {
// TODO Auto-generated constructor stub
File logFile = new File(logFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Access-Accept for user"))
{
newUser.setStatus("Accept");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
else if(line.contains("Access-Reject for user"))
{
newUser.setStatus("Reject");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
}while(s1.hasNextLine());
}
}
RemoveDuplicate class:
public class RemoveDuplicatesInList {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public RemoveDuplicatesInList(String duplicateFileLocation)
{
// TODO Auto-generated constructor stub
File logFile = new File(duplicateFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
boolean sameAccount=false;
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Accept"))
{
newUser.setStatus("Accept");
String[] sb=line.split(",");
sameAccount=false;
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
else if(line.contains("Reject"))
{
newUser.setStatus("Reject");
String[] sb=line.split(",");
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
}while(s1.hasNextLine());
}
}
Check value of
info.get(i).getIpadd()
if value of this is null then .toString(0 will give you NullPointerException

Categories