Retrieve user account - java

I used the following coding to display user accounts in my domain.But in that coding it display only first 100 records.But in my domain nearly 500 users account.I don't know what problem in this coding
import java.net.URL;
import java.util.List;
import com.google.gdata.client.appsforyourdomain.UserService;
import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry;
import com.google.gdata.data.appsforyourdomain.provisioning.UserFeed;
public class Readuser {
public int i3;
public String rn[]=new String[100];
public void read(){
try
{
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials(admin,password);
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/"+domain+"/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(i3=0; i3<entries.size(); i3++) {
UserEntry entry = entries.get(i3);
rn[i3]= entry.getTitle().getPlainText();
System.out.println(rn[i3]);
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(Exception e) { System.out.print(e);}
}
public static void main(String args[])
{
Readuser ru=new Readuser();
ru.read();
}
}

You only allocate 100 entries.
public String rn[]=new String[100];

Hint from your code : public String rn[]=new String[100];
Do you really need to have i3 and rn as class members ? Do you really need rn ? A List seems more comfortable as an Object than a String[].

There is no need for the string array (String[]).
Arrays are fixed size; and in this case you have allocated 100 "slots" for Strings, and when You try to assign a string to position 100 ( you know, the 101:th string) it fails.
You catch an exception in the end. Print the stack trace to find out whats going on
catch(Exception e) {
e.printStackTrace();
}
Learn to read it an find out what is says... However you should not catch the exception in this method. It is better to abort whatever the program was doing. Catch it in your main method - just printing or logging it is fine, so that you can correct the programming error.
Anyway; The result you get is a List of user entries. Lists are part of the (java.util)collections framework. Collections have a lot of features; in this case you want to iterate over all entries in the list. You can do this by using the iterator() method -read the javadoc...OR you can use for-loop syntactic sugar for doing this:
for( UserEntry user : entries ) {
// user is the current UserEntry
System.out.println(user.getTitle().getPlainText());
}
The variables i3 and rn are no good... They shouldn't be class variables, and if you need "temporary" variables, define them close to where you are going to use them.
As for naming of variables, a name like "entry" is less useful than "user". Actually a class called UserEntry should probably be called just User, but I don't know about this API, so...

Related

How do I read files as a object or is there a better solution to this? Please see code bellow for context

So in my java class, we need to read this file and somehow converts its content into an object
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Calendar {
public Appointment[] appointments;
Calendar()
{
appointments = null;
}
Calendar(int capacity, String filename)
{
Appointment[] appointments = new Appointment[capacity];
//you can see that appointments is an Appointment object
readCalendarFromFile(filename);}
private void readCalendarFromFile(String fileName){
Scanner fileRead = null;
try
{
fileRead = new Scanner(new FileInputStream("appointments.txt"));
for(int r = 0; r < 30; r++)
appointments[r]= fileRead.nextLine(); ----> This is where I am getting my error from as I cannot convert String into an object. Is there a way that I can pass this
fileRead.close();
}
catch (FileNotFoundException fe)
{
fe.printStackTrace();
System.err.println("Unable to open the file " + fileName + " for reading.");
}
}
}
Is there any way that I can convert filetext into an object or do I have to do something else with it? I have to make an appointment an object so I can't change it into anything else sadly.
You have to have a class Appointment somewhere, and what you are trying to do is add an object of the type Appointment to the array appointments, based on the info you get from the text file, right?
So, you have your for loop that reads every line from the text file, and then you need to create instances of Appointment for each line.
The class Appointment has some kind of constructor, that you need to call to create a new object (read: "a new instance") from it.
Let's assume it looks like this:
public Appointment(String title, String time, String location) {
this.title = title;
this.time = time;
this.location = location;
}
Let's also assume that every line in the file appointments.txt is formatted in the following way:
<Title>, <Time>, <Location>
Which means, that you would have to parse the line that you read from the file by splitting it (the delimiter in this case would be the ",". Just do a quick research on the internet on how to split Strings in Java, it's pretty easy actually.
When you have all the bits of information in separate variables, you have to call the constructor of Appointment, to create a new appointment that you can then add to your array. Assuming that you have three Strings with the title, the time and the location of the appointment (or whatever info you have in the text file), this would look like this:
try{
fileRead = new Scanner(new FileInputStream("appointments.txt"));
int counter = 0;
while(fileRead.hasNext()) {
String lineRead = fileRead.nextLine();
// here comes the parsing of the line into three String variables
appointments[counter] = new Appointment(title, time, location);
fileRead.close();
}
} catch(FileNotFoundException ex) {
// Do some exception handling in here, or just print the stacktrace
}
The line I want you to pay the most attention to is the Line, where it says new Appointment(title, time, location). The difference between this and the code that you posted is, that here I create a new object of the type Appointment, that corresponds with the type of the array you created earlier, in the line Appointment[] appointments = new Appointment[capacity].
You tried to directly add a String to the array, although you declared an array of the type Appointment, not of the type String.
You should read up on the topic of objects in Java in general, and what constructors are, what they do and how you use them.
For example, this topic gets explained really well and exhaustive in the official Java tutorials from Oracle (the company that develops the Java Language). I linked you the specific section that talks about constructors, but I would suggest that you read at least the whole chapter and everything before it that helps you understand what they actually talk about.
Hope this helps :)

Using java .util.Map & java .util.LinkedHashMap?

I am new to Java (along with programming in general). I was working on a personal project where a user types one character to which it is converted to another character. More specifically, a user would type a romanization of a Japanese character to which the Japanese hiragana equivalent is outputted. I am using two separate classes at the moment:
RomaHiraCore.java
import java.util.*;
public class RomaHiraCore
{
public static void main(String[] args)
{
Table.initialize(); // Table.java needed!
Map<String, String> table = Table.getTable();
Scanner roma = new Scanner(System.in);
System.out.println("Romaji: ");
String romaji = roma.nextLine().toLowerCase();
if (table.containsKey(roma))
{
System.out.println(table.get(roma));
}
else
{
System.out.println("Please enter a valid character (e. g. a, ka)");
}
roma.close();
}
}
Tables.java
import java.util.*;
public class Table
{
private static Map<String, String> table = new LinkedHashMap<>();
public static Map<String, String> getTable()
{
return table;
}
public static void initialize()
{
// a - o
table.put("a", "あ");
table.put("i", "い");
table.put("u", "う");
table.put("e", "え");
table.put("o", "お");
// ka - ko
table.put("ka", "か");
table.put("ki", "き");
table.put("ku", "く");
table.put("ke", "け");
table.put("ko", "こ");
}
}
If anyone can point me in the right direction, I would greatly appreciate it. I've attempted to go over the documentation, but I can't seem to grasp it (maybe I'm overthinking it). When I run the program, it allows me to enter a character; however, it will only continue to the "else" statement rather than scan Table.java to see if the input matches any of the values listed. Either I'm overlooking something or need to use an entirely different method altogether.
In your map, you have String keys, and the String which you provide is in the romaji variable. So your if should look like this: if (table.containsKey(romaji)). What is more, in this situation I think that using LinkedHashMap doesn't give you anything, simple HashMap would be as good as LinkedHashMap(even better), because you don't need to maintain insertion order of your characters.
In your main method, you are currently storing the string value inputted by the user however you never access that variable anywhere else.
You wrote table.containsKey(roma) however roma is the Scanner object and not the string they entered so you should be checking if that string is a valid key by using table.containsKey(romaji).
Next, in your else clause, you ask them to reenter an input but never provide them the chance to because you just terminate the scanner.
What you should be doing is something more like this.
String romaji = roma.nextLine().toLowerCase();
while (true) {
if (table.containsKey(romaji)) {
System.out.println(table.get(romaji));
break;
}
else {
System.out.println("Enter a valid char:";
romaji = roma.nextLine().toLowerCase();
}
}
roma.close();

Loading information from file in different ways

My program currently has this working:
Bank bank = new Bank();
bank.openAccount(new CheckingAccount(10100, new Customer("First", "Last"),500.00,false));
bank.openAccount(new CheckingAccount(10101, new Customer("First", "Last"),2000.00,true));
bank.openAccount(new SavingsAccount(2010, new Customer("First", "Last"),5000.00,0.02));
Now I am trying to load this information from a file instead, but I ran into a bit of a wall. I want the new Customer information to include both the first and last name which are stored in separate index positions as separate variables, but while this will work:
new Customer[FIRST_INDEX],
I can't seem to get it to accept two index positions without creating a new Customer again. This is turn is causing issue with the method in Accounts where I'd like to keep the same format. How can I go about doing this?
public CheckingAccount(int accountNumber, Customer owner, double currentBalance, boolean freeChecks)
{
super(accountNumber, owner, currentBalance);
this.freeChecks = freeChecks;
}
Another problem I am running into is that the last index position can be one of two variables depending on if I am dealing with a checking account or a savings account:
private final static int FREE_CHECKS_INDEX = 4; // This loads a boolean
private final static int INTEREST_INDEX = 4; // This loads a double
Given this, I'm not entirely sure if my above approach would even work at all. The program is supposed to load either a Checking Account or Savings Account object, but since both types of accounts are stored in the same file I am wondering if I could read the last index position of each line of the text file before creating the object, but I'm not really sure how to go about doing that.
To be clear, I have this problem working perfectly without loading the data from the file, I am just unsure about the best approach for adapting it without having to rewrite all my other classes. Here's the new thing I am trying to do which I know isn't right:
protected static void loadAccountInformationFromFile() throws Exception
{
try ( Scanner fin = new Scanner(new File(INPUT_CUSTOMER_FILE)) )
{
String record;
String[] fields;
while ( fin.hasNext() )
{
record = fin.nextLine();
fields = record.split(",");
Bank bank = new Bank();
bank.openAccount
(
new CheckingAccount(Integer.parseInt(accountNumber[ACCOUNT_NUMBER_INDEX]),
new Customer[FIRST_INDEX, LAST_INDEX],
currentBalance[BALANCE_INDEX],
freeChecks[FREE_CHECKS_INDEX]
)
);
}
} catch (Exception e)
{
throw e;
} // end try
}

Advice on Java program

My java project required that I create an array of objects(items), populate the array of items, and then create a main method that asks a user to enter the item code which spits back the corresponding item.
It took me a while to figure out, but I ended up "cheating" by using a public variable to avoid passing/referencing the object between classes.
Please help me properly pass the object back.
This is the class with most of my methods including insert and the find method.
public class Catalog {
private Item[] itemlist;
private int size;
private int nextInsert;
public Item queriedItem;
public Catalog (int max) {
itemlist = new Item[max];
size = 0;
}
public void insert (Item item) {
itemlist[nextInsert] = item;
++nextInsert;
++size;
}
public Item find (int key) {
queriedItem = null;
for (int posn = 0; posn < size; ++posn) {
if (itemlist[posn].getKey() == key) queriedItem = itemlist[posn];
}{
return queriedItem;
}
}
}
This is my main class:
import java.util.*;
public class Program {
public static void main (String[] args) {
Scanner kbd = new Scanner (System.in);
Catalog store;
int key = 1;
store = new Catalog (8);
store.insert(new Item(10, "food", 2.00));
store.insert(new Item(20, "drink", 1.00));
while (key != 0) {
System.out.printf("Item number (0 to quit) ?%n");
key = kbd.nextInt();
if (key == 0) {
System.out.printf("Exiting program now!");
System.exit(0);
}
store.find(key);
if (store.queriedItem != null) {
store.queriedItem.print();
}
else System.out.printf("No Item found for %d%n", key);
}
}
}
Thanks I appreciate the help!!!!!!
store.find(key); returns an Item you should use it and delete the public field from Catalog
public Item find (int key) {
Item queriedItem = null;
//....
}
Item searched = store.find(key);
if (searched != null)
searched.print();
else
System.out.printf("No Item found for %d%n", key);
Remove your use of queriedItem entirely and just return the item from find: Replace
store.find(key);
if (store.queriedItem != null){store.queriedItem.print();}else System.out.printf("No Item found for %d%n", key);
With
Item foundItem = store.find(key);
if (foundItem != null) {
foundItem.print();
} else System.out.printf("No Item found for %d%n", key);
Well, here are some suggesetions (choose complexity at your own discretion, but all of them is highly recommended):
Research Properties, for example here. Or XML. You could populate the array with values from a configuration file for greater flexibility.
Use constanst for literals in your code (where they are necessary).
Create an ApplicationFactory the initializes the whole application for you. Things like this need to be separated from your domain logic.
Create a UserInputProvider interface so you can easily change the way the input of the user is read without affecting anything else. Implement it with a ConsoleInputProvider class for example.
In general, try using interfaces for everything that's not a pure domain object (here, the only one you have is probably Item).
Try to keep your methods as short as possible. Instead of doing many things in a method, have it invoke other methods (grouping related logic) named appropriately to tell what it is doing.
If you're not allowed to cheat and use List or a Map, devise your own implementation of one, separating data structure and handling from the logic represented by Catalog (i.e. Catalog in turn will delegate to, for example, Map.get or equivalent method of your data structure implementation)
Your main should basically just have ApplicationFactory (or an IoC framework) to build and initialize your application, invoke the UserInputProvider (it should not know the exact implementation it is using) to get user input, validate and convert the data as required, invoke Catalog to find the appropriate Item and then (similarly to the input interface) send the result (the exact data it got, not some string or alike) to some implementation of a SearchResultView interface that decides how to display this result (in this case it will be a console-based implementation, that prints a string representing the Item it got).
Generally, the higher the level of decoupling you can achieve, the better your program will be.
The Single Responsibility Principle states: " every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class". This is also true for methods: they should have one and only one well defined task without any side effects.

storing names and other information

I am creating a prison system where I need to store the names and because I need to print out all the prisoner information in one of the methods. I want to make it remember and store information such as name, id and crimes etc. How can I go about doing this?
About the posted answers, I don't think it needs to be something that complicated because I haven't learnt any of this for the assignment. All I want is for my program to print out the prisoner ID, name, starting and ending date, crime with just one run of the program after I am prompted to enter the information.
INPUT/OUTPUT
New Prisoner
Enter Name:
Enter crime:
Enter Name:
Enter crime:
Prisoner information
(name) has committed (crime)
(name) has committed (crime)
The short answer is "a database."
Your question indicates that the following could be overwhelming but it could be worth some effort to read about "Macto," an end-to-end sample Ayende Rahein has been writing about.
You haven't made particularly clear in your question as to whether you just want to store the prisoner details in memory while the program is running, or if you want to persist the prisoners to disk, so that you can close your program and load them again next time you start it.
If its the former, you can just store the prisoners in an array or a list. For example assuming your prisoner class looks something like this:
public class Prisoner {
private String name;
private String crime;
public Prisoner(String name, String crime) {
this.name = name;
this.crime = crime;
}
public String getName() {
return name;
}
public String getCrime() {
return crime;
}
}
You can then store the prisoners in a list...
List<Prisoner> prisoners = new LinkedList<Prisoner>();
prisoners.add(new Prisoner("Bob", "Murder"));
prisoners.add(new Prisoner("John", "Fraud"));
...and then iterate over the list and print the details out...
for(Prisoner p : prisoners) {
System.out.println(p.getName() + " committed " + p.getCrime());
}
If you're looking for a way to persist the prisoner details between runs of the program there are a number of possible approaches, most of which have already mentioned. In most cases a database is the best solution for storing records with JDBC being the simplest way of connecting to and interacting with a database.
For simplicity however, I would suggest storing the details in a CSV (comma separated value) file. A CSV file is simply a plain text file that stores each record on a new line, with a comma separating each field. For example:
Bob, Murder
John, Fraud
There are a number of CSV reading libraries around (see here), however its quite easy to read + write to a CSV file with no external libraries. Below is an example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class PrisonerStore {
/**
* The file the prisoners are stored in
*/
private File store;
public PrisonerStore(File store) {
this.store = store;
}
/**
* Saves the specified prisoner to the file
* #param prisoner
*/
public void savePrisoner(Prisoner prisoner) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(store, true));
writer.write(prisoner.getName() + "," + prisoner.getCrime());
writer.newLine();
writer.close();
}
/**
* Reads all prisoners from the file and returns a list of prisoners
* #return
*/
public List<Prisoner> loadPrisoners() throws IOException{
List<Prisoner> prisoners = new LinkedList<Prisoner>();
BufferedReader br = new BufferedReader(new FileReader(store));
//Read each line of the file and create a Prisoner object from it
String line = null;
while((line = br.readLine()) != null) {
String[] parts = line.split(",");
Prisoner p = new Prisoner(parts[0], parts[1]);
prisoners.add(p);
}
br.close();
return prisoners;
}
}
In your code you can then do something like the following:
PrisonerStore store = new PrisonerStore(new File("C:\\myFile.csv"));
Prisoner p1 = new Prisoner("Bob", "Murder");
Prisoner p2 = new Prisoner("John", "Fraud");
try {
store.savePrisoner(p1);
store.savePrisoner(p2);
List<Prisoner> list = store.loadPrisoners();
for(Prisoner p : list) {
System.out.println(p.getName() + " committed " + p.getCrime());
}
} catch (IOException e) {
System.out.println("Error storing prisoners");
}
If these informations need to persist beyond the life of the VM, you'll have to write them on a physical storage (actually, persistence is the mechanism that allow to pass from a physical storage to an in memory representation).
There are several solutions for this purpose:
Java Object Serialization
A prevalent system with a library like Prevalayer
XML serialization with a library like XStream
A database (relational or not)
Serialization is Java built-in persistence mechanism but is very fragile. Prevalence is based on serialization but I have no experience with it and I'm not sure it solves the weakness of serialization. XML serialization is interesting and quite fast to put in place, especially with a library like XSteam. Finally, a database is the most "standard" solution but introduces some complexity. Depending on your needs, use straight JDBC or JPA for the data access.
My advice: If you don't need a database, go for XML serialization and use XStream. See the Two Minute Tutorial on XStream web site to get started. If you don't need persistence at all (beyond the life of the VM), just store the prisoners in a List.
Where do you want store information ?
If you want store information in program (memory), you can use a static member variables,like this:
// Prisoner.java
class Prisoner {
public String Name;
public int Age;
}
// Prisoners.java
class Prisoners {
public static Prisoner[] GetAll() {
Prisoner[] _data;
// Load from database to _data;
return _data;
}
}
// test.java
class test() {
public static void out() {
System.out.println(main.allPrisoner.getLength());
}
}
// main.java
public class main{
public static Prisoner[] allPrisoner;
public static main(String args[]){
public allPrisoner = Prisoners.GetAll();
// From now all prisoners will be stored in program memory until you close it
}
}
So, If you are Web Development, you can use WebCache
If you are looking to use a database, one place to start is with Hibernate. Its a java library that can provide java object to relational database table mapping.
If you want to persist to a file system using an object serialization routine, I'd recommend XStream to serialize XML or JSON text.
Based on the added text to the question, I'd recommend having a look at XStream just because it is so simple to use if you need to get the data structures to a file on the disk. However, more basically...
You probably just need to make a Prisoner class that has the stuff you need Prisoner to have, such as a name, identifier, etc, etc.
public class Prisoner
{
private String name;
private int identifier;
public Prisoner(String aName, int anId)
{
name = aName;
identifier = anId;
}
public String toString()
{
return "Prisoner[ name = " + name + ", id = " + identifier + " ]";
}
}
Then you can store them in a Map<String, Prisoner> to make finding them easier.
Map<String, Prisoner> prisonMap = new HashMap<String, Prisoner>();
To enter them in from the command line, you'll probably need to use System.in
Sun provides a good tutorial for it.
If you just want to print them back out on the command line, you'll iterate over the Map's keyset and get each value or just iterate over the values and just use System.out.println() to print them out.
for(Prisoner p : prisonMap.values())
{
System.out.println(p);
}
Or, use XStream to print out the XML to file or the System.out stream.

Categories

Resources