Changing instance of a class from another class - class

I am trying to use 1 class to change the values of another class.
My first class is Employees. My second class is address.
public class Employee {
private String name;
private Address address;
constructors:
public Employee(){
address = new Address();
name = "";
}
public Employee(String name){
this.name = name;
this.address = new Address();
}
public String getAddress(){
return address.getAddress();
}
public void changeAddress(String number, String street, String city, String province, String postalCode){
address.setNumber(number);
address.setStreet(street);
address.setCity(city);
address.setProvince(province);
address.setPostalCode(postalCode);
}
In my Address class I have a constructor and setters.
When I'm testing,
public static void main(String[] args){
Employee s1 = new Employee("John Doe");
s1.changeAddress("0141", "No5 Road", "Seattle", "WA", "65897");
This doesn't work, because I didn't create an address class.
so that made me try:
Address a1 = new Address();
but how do I link the new address and the employee class together?
I'm not even sure if I am supposed to manually create an address class using Address a1 = new Address() in my tester; or if I am able to include this in my Employee class so I am able to call the changeAddress method without typing out the new address class every time.
The change address method is in the employee class. The address class only has a constructor and setters.

Related

How to use criteria query on refrence collection in mongo db

How do I find all the person which are having city ="XYZ" in Address collection
public class Person {
#Id
private String id;
private String description
#DBRef
private Address address;
// Getters and Setters
}
public class Address
{
#Id
private String id;
private String area
private String city
// Getters and Setters
}
Mongo understands #DBRef as a reference to another document, in this case, an Address document and ultimately when the object is loaded from MongoDB, those references will be eagerly resolved and this will get populated to the user as a HATEOAS friendly link. You will get back a mapped object that looks the same as if it had been stored embedded within your master document.
You can define your repository, which will map the endpoints to your database, for the given object, like PersonRepository defined below as an example:
import com.mycompany.domain.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface PersonRepository extends MongoRepository<Person, String> {
List<Person> findByCity(#Param("city") String city);
}
Another way you could go around this using the query criteria methods is executing two queries.
First query would be to fetch the address documents which have the city = "XYZ". Resolve the ids from the list returned.
Generate another query on the Person entity using the ids from the previous operation.
The following demonstrates this approach
Query addressQuery = new Query(where("city").is("XYZ"));
addressQuery.fields().include("_id");
List<Address> addressList = mongoTemplate.find(addressQuery, Address.class, "address"); // get the addresses list that satisfy the given city criteria
// Resolve the ids for the addresses
final List<ObjectId> addressIds = new ArrayList<ObjectId>(addressList.length);
for(final Address address : addressList) {
addressIds.add(new ObjectId(address.getId()));
}
// Get the Person list using the ids from the previous operation
Query personQuery = new Query(where("address.$id").in(addressIds));
List<Person> list = mongoTemplate.find(personQuery, Person.class, "person");
If you knew the address id before hand you can then use a custom query:
public interface PersonRepository extends MongoRepository<Person, String> {
#Query("{ 'address': {'$ref': 'address', '$id': { '$oid': ?0 } } }")
List<Person> findByAddres(String addressIdAsString);
}

Populate dropdownlist with a class

I want to create a "package program" for address part of my projects. I need it in almost every project so i wanted to make it easier.
So i decided to create a class to load city names to a dropdownlist. Here i coded:
public class Address
{
string connStr = "Data Source...";
public int id { get; set; }
public string name { get; set; }
public Address(int ID, string Name)
{
this.id = ID;
this.name = Name;
}
public List<Address> LoadCities()
{
List<Address> cities = new List<Address>();
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select x,y from ...", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Address city = new Address(rdr.GetInt32(0), rdr.GetString(1));
cities.Add(city);
}
con.Close();
return cities;
}
}
This is my package program. I added this as a reference to my project. And tried to populate my dropdownlist as follows:
List<Address> cities = ???
ddlCity.DataTextField = "x";
ddlCity.DataValueField = "y";
ddlCity.DataSource = cities;
ddlCity.DataBind();
At ??? position i just wanted to code like this: List cities = Address.Loadcities();
So, i have a mistake here and i couldnt get it. Because i am new at "class" works.
Thanks in advance.
public static List<Address> LoadCities()
You need the function on that class to be static.
Then you just do:
List<Address> cities = Address.LoadCities();
Here's some documentation for those times when you can't sleep:
http://msdn.microsoft.com/en-us/library/98f28cdx.aspx

Disadvantages of interface objected programming

class Person{
private String name;
private int age;
private String gender;
//......
}
class Student extends Person{
private String id;
private String schoolBelongTo;
//......
}
public void showInfoOf(Person person){
System.out.println(person.getName());
//......
}
When using function "showInfoOf" ,if an object of Peron is used as the param,OK.However,if it is the type Student,I cannot get access to the field id and schoolBelongTo.
So I am confused ,how to ?
Actually, I want to know is this one of its(Interface oriented programming's or Supper class oriented programming's) disadvantages???
Two possible solutions:
You can programatically check the type in showInfoOf (Person), and use a cast to access & print the desired fields; or,
You can define a method on Person which will print/provide the desired info -- and either replace showPersonInfo() with that entirely, or call it into it. This is the more OO way.
Example:
abstract class Person {
private String name;
private int age;
private String gender;
public void printInfo() {
System.out.println( name);
}
}
class Student extends Person{
private String id;
private String schoolBelongTo;
#Override
public void printInfo() {
super.printInfo();
System.out.println( id);
System.out.println( schoolBelongTo);
}
}
public void showInfoOf (Person person){
person.printInfo();
}
In this example, all functionality has moved to Person.printInfo() and there is no real functionality remaining in showInfoOf (Person).
However in the real-world, you'd probably want move versatility in a Person.provideInfo() function -- perhaps returning a LinkedHashMap of fields & values (since unlabelled values on their own, are not great design).
The showInfoOf (Person) function could then handle formatting & printing the values to the specific requirement, leaving the Person.provideInfo() function general & multi-purpose.
in showInfoOf() you would have to check that person is of type Student, then cast it as a Student to get id or schoolBelongsTo

CompoundPropertyModel Wicket - Object graphs

I'd like to use the CompoundPropertyModel in Wicket for creating a user.
My user class looks like this:
public class User {
private String username;
...
private Address address;
...
}
public class Address{
private String street;
...
}
If I try to access the street of the address via the User's compoundproperty model, I get a nullpointerexception, of course: "user.address.street". So I have to instantiate the class "Address" on my own in advance. Is there a more elegant way to dynamically instantiate member fields?
Thanks
If a User must have an Address, you should create the instance of Address in the constructor for the User. Otherwise, you might do a null check in your getAddress() method and create a new instance if it's null...
public Address getAddress() {
if (address == null) {
address = new Address();
}
return address;
}

How to edit value of ValueProxy of gwt requestfactory at client side?

I have 2 models: ContactGroup and Contact. ContactGroup contains many Contacts.
In the page, I have to display a list of groups and number of contacts in the correspondence group like this:
Group Foo (12 contacts)
Group Bar (20 contacts)
So I at server side I used a DTO ContactGroupInfo:
public class ContactGroupInfo {
private Integer contactCount;
private Long id;
private String name;
public Integer getContactCount() { return this.contactCount; }
public Long getId() { return this.id; }
public String getName() { return this.name; }
public void setContactCount(Integer count) { this.contactCount = count; }
public void setId(Long id) { this.id = id; }
public void setName(String name) { this.name = name; }
}
In this ContactGroupInfo, I added contactCount field which is not a field in ContactGroup entity.
And at client side, I used a ValueProxy:
#ProxyFor(value = ContactGroupInfo.class, locator = ContactGroupService.class)
public interface LightContactGroupProxy extends ValueProxy {
Integer getContactCount();
Long getId();
String getName();
void setContactCount(Integer count);
void setId(Long id);
void setName(String name);
}
So when server side returns to client side a list of LightContactGroupProxy, I stored that list a in ArrayList to render to a CellTable.
And here is the problem comes to me: when I need to edit the name of the group at client side, I can't edit the LightContactGroupProxy object directly.
So I have to send the new name to server to return a new LightContactGroupProxy with the new name. This is not effective because I have to count contacts again (althought I know the number of contacts does not change).
Or I have to send both the number of contacts and new name to server to create a new LightContactGroupProxy with the new name. This is not I want, because if LightContactGroupProxy has many other fields I have to send many fields.
I don't know why GWT teams designs the immutable proxy. So please, someone has experience on requestfactory please show me the correct way to handle ValueProxy returned from server so that we can use them to render and edit?
Thank you
Maybe you should try something like this :
ContactGroupContext ctx = requestFactory.newContactGroupContext();
LightContactGroupProxy editableProxy = ctx.edit(lightContactGroupProxy);
editableProxy.setName(newName);
ctx.saveInfoAndReturn(editableProxy).fire(receiver); // or just ctx.fire();
Anyway, I wouldn't use ValueProxy in this case, I would directly get the ContactGroup entities with a transiant property contactCount. The property could be a primitive, or a ValueProxy if you don't want it to be calculated every time a ContactGroup is requested.