How should I use mock for certain case? - java

Suppose that there are classes like:
CivilAddSystem class :
class CivilAddSystem{
List<People> people = new ArrayList<>();
List<Town> towns = new ArrayList<>();
public People addPeople(People people) {
people.add(people);
return people;
}
public Town addTown(Town town) {
towns.add(town);
return town;
}
public House addHouse (House house, String townName) throws IllegalStateException {
Town town = getTown(townName);
if (null == town) throw new IllegalStateException("No matching town");
town.addHouse(house);
return house;
}
public List<String> getTown(String name) {
for (Town town : towns) {
if (town.getName().equals(name)) return town;
}
return null;
}
}
Town class:
public class Town {
List<House> houses = new ArrayList<>();
String name;
String abbreviation;
public Town (String name, String abbreviation) {
this.name = name;
this.abbreviation = abbreviation;
}
public String getName() {
return name;
}
public String getAbbreviation() {
return abbreviation;
}
public void addHouse(House house) {
houses.add(house);
}
public House getHouse(String unitNumber) {
for (House house : houses) {
if (house.getUnitNumber().equals(unitNumber)) return house;
}
return null;
}
}
House class
public class House {
private final List<People> people = new ArrayList<>();
private final String unitNumber;
private final String houseName;
public House (String unitNumber, String houseName) {
this.unitNumber= unitNumber;
this.houseName= houseName;
}
public String getUnitNumber() {
return unitNumber;
}
public String getHouseName() {
return houseName;
}
private People checkMovedInPeople(People person) {
if (null == person) throw new NullPointerException();
for (People movedIn : people) {
if (movedIn.getName().equals(person.getName())) return movedIn;
if (movedIn.getPersonID().equals(person.getPersonID())) return movedIn;
}
return null;
}
public void moveInPeople(People person) throws IllegalArgumentException, IllegalStateException {
if (null == person) throw new IllegalArgumentException("Person shouldn't be null");
if (null != checkMovedInPeople(person)) throw new IllegalStateException("Person is already in the house");
people.add(person);
}
public List<String> getPeople() {
List<String> results = new ArrayList<>();
for (People person: people) {
results.add(person.getPersonID());
}
return results;
}
public People getPerson(String match) {
for (People person: people) {
if (person.getPersonID().equals(match)) return person;
if (person.getName().equals(match)) return person;
}
return null;
}
}
And for the people class, it just has two variables: String PersonID and String Name and their getter methods.
So, what I want to achieve is that, I am currently trying to test the addPeople method in CivilAddSystem class and I want to test it independently using mockito.
The test case I wrote using JUnit is like this:
#Test
public void testAddPeople() {
CivilAddSystem CAS = new CivilAddSystem();
Town town = CAS.addTown("BlueTown", "BT");
House house = CAS.addHouse("U180", "BlueHouse", "BlueTown");
People bob = CAS.addPeople("1", "Bob");
Assert.assertEquals(CAS.getTown("BlueTown").getHouse("U180").getPerson("1"), null);
house.moveInPeople(bob);
Assert.assertEquals(CAS.getTown("BlueTown").getHouse("U180").getPerson("1").getPersonID, 1);
}
But I am really struggling with applying mockito for this test case.
What I did so far is just mocking Town, House and People classes, (not the CivilAddSystem class since it is the one that is being tested), and stopped there...
Can anyone gives me a hint on how to apply mockito for that above test case?
p.s) A little bit of modification for the codes above is accepted (for example, applying dependency injection and something like this are accepted).
Thanks in advance!

Related

How to sort two different object list which has name property common

How to sort object which has two different types of object list property. both the list are type of different objects.
public class Member {
private List<Group> groups;
private List<Person> persons;
}
public class Group {
private String groupName;
}
public class Person {
private String personName;
}
Is there way to sort these two list and get combined result which will be sorted based on the name.
expected result
groupName : alex
personName : bob
groupName: christan
groupName: Dan
perosnName: Kat
Try this:
abstract class BaseClass implements Comparable{ // you could name this class as you want
protected String name;
#Override
public int compareTo(Object o) {
return this.name.compareToIgnoreCase(((BaseClass)o).name);
}
}
class Group extends BaseClass{
public Group(String name) {
this.name = name;
}
#Override
public String toString() {
return "groupName : " + name;
}
}
class Person extends BaseClass{
public Person(String name) {
this.name = name;
}
#Override
public String toString() {
return "personName : " + name;
}
}
Then to use it:
public class Main {
public static void main(String[] args) {
List<Group> groups = new ArrayList<>();
groups.add(new Group("alex"));
groups.add(new Group("christan"));
groups.add(new Group("Dan"));
List<Person> persons = new ArrayList<>();
persons.add(new Person("bob"));
persons.add(new Person("Kat"));
List<BaseClass> members = new ArrayList<>();
members.addAll(groups);
members.addAll(persons);
members.sort(BaseClass::compareTo);
members.forEach(System.out::println);
}
}
Output:
groupName : alex
personName : bob
groupName : christan
groupName : Dan
personName : Kat

No results querying a Neo4j database using Spring Data Neo4j repositories

I have created a graph database as hierarchical tree as a result of converting a MySQL database in another Neo4j database. The transformation worked fine.
On the top level exist a node labeled as Root, on the second level are the countries labeled as Country. Every country has cities that is the third level labeled as City. And down for every city there are a subset of addresses labeled as Address. The relationships should be,
(root)-[:IS_ROOT]->(country)-[:HAS_CITY]->(city)-[:HAS_ADDRESS]->(address)
Later, using Spring Data Neo4j repositories, I tried to query the database with no result.
For the MySQL database I use JDBC, and for the Neo4j database I use Spring Data Neo4j as mentioned before.
This is the controller I use to create the Neo4j database,
#Controller("importer")
public class SakilaDbImportController {
private static final Logger logger = LoggerFactory.getLogger(SakilaDbImportController.class);
#Autowired
#Lazy
AddressNeoRepository addressRepo;
#Autowired
#Lazy
CityNeoRepository cityRepo;
#Autowired
#Lazy
CountryNeoRepository countryRepo;
#Autowired
#Lazy
RootRepository rootRepo;
#Autowired
Neo4jTemplate template;
#Autowired
SakilaDbApiClient client;
public SakilaDbImportController() {
}
#Transactional
public RootNeo createGraphDb() {
RootNeo root = doImportRoot();
return root;
}
#Transactional
public RootNeo importRoot() {
return doImportRoot();
}
private RootNeo doImportRoot() {
logger.debug("Importing root");
RootNeo root = new RootNeo("1", "Root");
root.addLabel("_Root");
//root.addLabel("Root");
System.out.println("root created " + root);
List<Country> data = client.readAllCountries();
if (data.isEmpty()) throw new RuntimeException("Data for Root not found.");
Map<CountryNeo, RoleIsRoot> roles = relateCountriesToRoot(root, data);
//template.save(root);
Set<CountryNeo> set = roles.keySet();
for(Iterator<CountryNeo> it = set.iterator(); it.hasNext();) {
root.isRoot(it.next());
}
rootRepo.save(root);
/*
for(RoleIsRoot role: roles){
template.save(role);
}
*/
return root;
}
private Map<CountryNeo, RoleIsRoot> relateCountriesToRoot(RootNeo root, List<Country> data) {
Map<CountryNeo, RoleIsRoot> roles = new HashMap<CountryNeo, RoleIsRoot>();
for (Country country : data) {
if(country.getCountry().equalsIgnoreCase("Canada"))
continue;
CountryNeo countryNeo = doImportCountryNeo(country);
RoleIsRoot role = root.isRoot(countryNeo, "IS_ROOT_OF");
System.out.println("RoleIsRoot: " + role);
roles.put(countryNeo, role);
}
return roles;
}
#Transactional
public CountryNeo importCountryNeo(Country country) {
return doImportCountryNeo(country);
}
private CountryNeo doImportCountryNeo(Country country) {
logger.debug("Importing countryNeo");
CountryNeo countryNeo = new CountryNeo(generateIndex(country.getCountryId()), country.getCountry());
countryNeo.addLabel("_Country");
//countryNeo.addLabel("Country");
System.out.println("new country: " + countryNeo);
List<City> data = client.readAllCitiesByCountry(country);
if (data.isEmpty()) throw new RuntimeException("Data for Country not found.");
Map<CityNeo, RoleHasCity> roles = relateCitiesToCountry(countryNeo, data);
Set<CityNeo> set = roles.keySet();
for(Iterator<CityNeo> it = set.iterator(); it.hasNext();) {
countryNeo.hasCity(it.next());
}
countryRepo.save(countryNeo);
/*
template.save(countryNeo);
for(RoleHasCity role: roles){
template.save(role);
}
*/
return countryNeo;
}
private Map<CityNeo, RoleHasCity> relateCitiesToCountry(CountryNeo countryNeo, List<City> data) {
Map<CityNeo, RoleHasCity> roles = new HashMap<CityNeo, RoleHasCity>();
for (City city : data) {
CityNeo cityNeo = doImportCityNeo(city);
RoleHasCity role = countryNeo.hasCity(cityNeo, "IS_CITY_FROM");
System.out.println("RoleHasCity: " + role);
roles.put(cityNeo, role);
}
return roles;
}
#Transactional
public CityNeo importCityNeo(City city) {
return doImportCityNeo(city);
}
private CityNeo doImportCityNeo(City city) {
logger.debug("Importing cityNeo");
CityNeo cityNeo = new CityNeo(generateIndex(city.getCityId()), city.getCity());
cityNeo.addLabel("_City");
//cityNeo.addLabel("City");
System.out.println("new city: " + cityNeo);
List<Address> data = client.readAllAddressesByCity(city);
if (data.isEmpty()) throw new RuntimeException("Data for City not found.");
Map<AddressNeo, RoleHasAddress> roles = relateAddressesToCity(cityNeo, data);
Set<AddressNeo> set = roles.keySet();
for(Iterator<AddressNeo> it = set.iterator(); it.hasNext();) {
cityNeo.hasAddress(it.next());
}
cityRepo.save(cityNeo);
/*
template.save(cityNeo);
for(RoleHasAddress role: roles){
template.save(role);
}
*/
return cityNeo;
}
private Map<AddressNeo, RoleHasAddress> relateAddressesToCity(CityNeo cityNeo, List<Address> data) {
Map<AddressNeo, RoleHasAddress> roles = new HashMap<AddressNeo, RoleHasAddress>();
for(Address address: data) {
AddressNeo addressNeo = doImportAddressNeo(address);
RoleHasAddress role = cityNeo.hasAddress(addressNeo, "IS_ADDRESS_IN");
System.out.println("RoleHasAddress: " + role);
roles.put(addressNeo, role);
}
return roles;
}
#Transactional
public AddressNeo importAddressNeo(Address address) {
return doImportAddressNeo(address);
}
private AddressNeo doImportAddressNeo(Address address) {
logger.debug("Importing addressNeo");
if (address == null) throw new RuntimeException("Address not found.");
AddressNeo addressNeo = new AddressNeo(generateIndex(address.getAddressId()), address.getAddress());
addressNeo.addLabel("_Address");
//addressNeo.addLabel("Address");
System.out.println("new address: " + addressNeo);
addressNeo.setPostalCode(address.getPostalCode());
addressRepo.save(addressNeo);
/*
template.save(addressNeo);
*/
return addressNeo;
}
private String generateIndex(int index) {
return String.valueOf(index);
}
}
And this is the service that, using the repositories, does the queries,
#Service
public class SakilaDbQueries {
#Autowired
#Lazy
AddressNeoRepository addressRepo;
#Autowired
#Lazy
CityNeoRepository cityRepo;
#Autowired
#Lazy
CountryNeoRepository countryRepo;
#Autowired
#Lazy
RootRepository rootRepo;
public SakilaDbQueries() {
}
public List<String> findAllCountryNames() {
CountryNeoData names = countryRepo.findAllCountryNames();
Collection<String> collection = names.getCountries();
List<String> list = new ArrayList<String>();
for(Iterator<String> it = collection.iterator(); it.hasNext(); ) {
list.add(it.next());
}
return list;
}
public List<CountryNeo> findAllCountries() {
Result<CountryNeo> result = countryRepo.findAll();
List<CountryNeo> list = new ArrayList<CountryNeo>();
for(Iterator<CountryNeo> it = result.iterator(); it.hasNext(); ) {
list.add(it.next());
}
return list;
}
}
And as an example,
Here is the NodeEntity Place as generic one,
#NodeEntity
public class Place {
#GraphId Long nodeId;
#Indexed(unique=true)
String id;
#Indexed(indexType=IndexType.FULLTEXT, indexName = "place")
String name;
#Labels
private Collection<String> labels = Collections.emptySet();
protected Place(String id, String name) {
this.id = id;
this.name = name;
}
protected Place() {
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addLabel(String label) {
HashSet<String> newLabels = new HashSet<>(this.labels);
if (newLabels.add(label)) this.labels = newLabels;
}
public void removeLabel(String label) {
HashSet<String> newLabels = new HashSet<>(this.labels);
if (newLabels.remove(label)) this.labels = newLabels;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Place place = (Place) o;
if (nodeId == null) return super.equals(o);
return nodeId.equals(place.nodeId);
}
#Override
public int hashCode() {
return nodeId != null ? nodeId.hashCode() : super.hashCode();
}
#Override
public String toString() {
return String.format("%s [%s]", name, id);
}
}
and CountryNeo that extends Place,
#NodeEntity
public class CountryNeo extends Place {
#RelatedTo(type = "HAS_CITY", direction = Direction.OUTGOING)
Set<CityNeo> cities;
#Fetch #RelatedToVia(type = "IS_ROOT", direction = Direction.INCOMING)
Iterable<RoleIsRoot> roles;
public CountryNeo() {
}
public CountryNeo(String id, String name) {
super(id, name);
}
public Set<CityNeo> getCities() {
return cities;
}
public void hasCity(CityNeo city) {
if(cities == null)
cities = new HashSet<CityNeo>();
cities.add(city);
}
public RoleHasCity hasCity(CityNeo city, String roleName) {
return new RoleHasCity(this, city, roleName);
}
public Collection<RoleIsRoot> getRoles() {
Iterable<RoleIsRoot> allRoles = roles;
return allRoles == null ? Collections.<RoleIsRoot>emptyList() : IteratorUtil.asCollection(allRoles);
}
}
The used roles,
#RelationshipEntity(type = "HAS_CITY")
public class RoleHasCity {
#GraphId Long id;
#StartNode CountryNeo country;
#EndNode CityNeo city;
String name;
public RoleHasCity() {
}
public RoleHasCity(CountryNeo country, CityNeo city, String roleName) {
this.country = country;
this.city = city;
this.name = roleName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CountryNeo getCountry() {
return country;
}
public void setCountry(CountryNeo country) {
this.country = country;
}
public CityNeo getCity() {
return city;
}
public void setCity(CityNeo city) {
this.city = city;
}
#Override
public String toString() {
return String.format("%s %s %s", city, name, country);
}
}
And the repository,
public interface CountryNeoRepository extends GraphRepository<CountryNeo> {
#Query("MATCH (n:CountryNeo) RETURN COLLECT(n.name) AS countries")
CountryNeoData findAllCountryNames();
#QueryResult
public class CountryNeoData {
Collection<String> countries = Collections.emptyList();
public Collection<String> getCountries() {
return countries;
}
}
}
And here is the main bean,
public class SakilaImporter {
private GraphDatabaseService graphDatabase;
private SakilaDbImportController importer;
private SakilaDbQueries queries;
public SakilaImporter(GraphDatabaseService graphDatabase,
SakilaDbImportController importer,
SakilaDbQueries queries) {
this.graphDatabase = graphDatabase;
this.importer = importer;
this.queries = queries;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
GraphDatabaseService graphDatabase = ctx.getBean("graphDatabaseService", GraphDatabaseService.class);
SakilaDbImportController importer = ctx.getBean("importer", SakilaDbImportController.class);
SakilaDbQueries queries = ctx.getBean("queries", SakilaDbQueries.class);
SakilaImporter sakilaImporter = new SakilaImporter(graphDatabase, importer, queries);
Transaction tx = graphDatabase.beginTx();
try {
sakilaImporter.createDatabase();
sakilaImporter.queryDatabase();
tx.success();
} finally {
tx.close();
}
ctx.close();
}
public void createDatabase() {
System.out.println("Importing data...");
final long start = System.currentTimeMillis();
RootNeo root = importer.createGraphDb();
if(root != null) {
final long time = System.currentTimeMillis() - start;
System.out.println("Import places took " + time + " ms.");
} else {
System.out.println("root: " + root);
}
}
public void queryDatabase() {
System.out.println();System.out.println();
System.out.println("List of countries.-");
List<CountryNeo> countries = queries.findAllCountries();
for(CountryNeo country: countries) {
System.out.println(country);
}
System.out.println();System.out.println();
System.out.println("List of country names.-");
List<String> names = queries.findAllCountryNames();
for(String name: names) {
System.out.println(name);
}
}
}
The result of both queries is an empty list
spring 2.5.6
spring framework 4.0.0.RELEASE
neo4j 2.1.8
spring data neo4j 3.1.2.RELEASE

Merge two Arrays of different objects into one Array/collection

I'm facing this task:
I have class A and class B. These two classes are different but almost the same.
I need to somehow merge them into 1 Single array of objects so I will be able to use them later in a list that combines both classes.
Class A:
public class Followers {
private String request_id;
private String number_sender;
private String state;
public String getRequest_id() {
return request_id;
}
public String getNumber_sender() {
return number_sender;
}
public String getState() {
return state;
}
}
Class B:
public class Following {
private String name;
private String state;
private String request_id;
public String getRequest_id() {
return request_id;
}
public String getName() {
return name;
}
public String getState() {
return state;
}
}
I've tried doing this next move:
Object[] obj1 = (Object[]) followers;
Object[] obj2 = (Object[]) followings;
Object[] completeArray = ArrayUtils.addAll(obj1, obj2);
Where followers and followings are both arrays of the corresponding classes. Then in my list adapter I use:
if (values[currentItem] instanceof Followers) { BLA BLA BLA}
else if (values[currentItem] instanceof Following) { BLA BLA BLA}
But I get this exception:
Caused by: java.lang.ArrayStoreException: source[0] of type json.objects.Following cannot be stored in destination array of type json.objects.Followers[]
What will be the best way to merge two arrays of different objects into one array?
Will just implementing the same interface between them do the job and then they will basically be in an array of the interface type?
what other ways do you recommend?
Try this
Object[] completeArray = new Object[0];
completeArray = ArrayUtils.addAll(completeArray, obj1);
completeArray = ArrayUtils.addAll(completeArray, obj2);
If you make both classes implement a common interface you can manipulate arrays/lists of them as if they contains instances of the interface.
public interface Follow {
public String getRequest_id();
public String getState();
}
public class Follower implements Follow {
private String request_id;
private String number_sender;
private String state;
public String getRequest_id() {
return request_id;
}
public String getNumber_sender() {
return number_sender;
}
public String getState() {
return state;
}
}
public class Following implements Follow {
private String name;
private String state;
private String request_id;
public String getRequest_id() {
return request_id;
}
public String getName() {
return name;
}
public String getState() {
return state;
}
}
public void test() {
List<Follow> all = new ArrayList<>();
all.add(new Following());
all.add(new Follower());
for ( Follow f : all ) {
String id = f.getRequest_id();
String state = f.getState();
}
}
Alternatively you could put them in a hierarchy:
public class Entity {
private String request_id;
private String state;
public String getRequest_id() {
return request_id;
}
public String getState() {
return state;
}
}
public class Follower extends Entity {
private String number_sender;
public String getNumber_sender() {
return number_sender;
}
}
public class Following extends Entity {
private String name;
public String getName() {
return name;
}
}
public void test() {
List<Entity> all = new ArrayList<>();
all.add(new Following());
all.add(new Follower());
for ( Entity f : all ) {
String id = f.getRequest_id();
String state = f.getState();
}
}
Or you could make the extra fields into attributes.
enum Attribute {
Follows,
Followed;
}
public static class Entity {
private String request_id;
private String state;
EnumMap<Attribute, String> attributes = new EnumMap<>(Attribute.class);
public String getRequest_id() {
return request_id;
}
public String getState() {
return state;
}
// Factory to make entities.
static Entity make(Attribute attribute, String value) {
Entity e = new Entity();
e.attributes.put(attribute, value);
return e;
}
}
public void test() {
List<Entity> all = new ArrayList<>();
all.add(Entity.make(Attribute.Follows, "Fred"));
all.add(Entity.make(Attribute.Followed, "Gill"));
for (Entity f : all) {
String id = f.getRequest_id();
String state = f.getState();
}
}
There are an infinite number of possibilities.
USE concat
var combined= obj1.concat(obj2); // Merges both arrays
Try this.
private Object[] appendObj(Object[] obj, Object newObj) {
ArrayList<Object> temp = new ArrayList<Object>(Arrays.asList(obj));
temp.add(newObj);
return temp.toArray();
}

Deleting complex object in Java list (for implementation on WSDL)

I am following those three tutorials and I have completed it with success.
http://oracleadfhowto.blogspot.in/2013/03/create-simple-web-service-using-oracle.html
http://oracleadfhowto.blogspot.in/2013/03/consuming-web-service-using-web-service.html
http://oracleadfmobile.blogspot.in/2013/03/consuming-soap-web-service-in-adf.html
But then, as author haven't implemented removeCountries method I tried to create it.
What I did initially was to just add to class Countries this method:
public boolean removeCountry(Country country) {
return countries.remove(country);
}
But although compiler wasn't complaining it didn't work. Actually it worked last night (before reboot) but not today.
Must be some SOAP iterator/bindig thing or whatever. Or I thought that it worked but in fact it didn't.
Here are original classes:
//-------------------------------
public class Country {
String CountryId;
String CountryName;
public Country() {
super();
}
public Country( String id, String name ) {
super();
this.CountryId = id;
this.CountryName = name;
}
public void setCountryId(String CountryId) {
this.CountryId = CountryId;
}
public String getCountryId() {
return CountryId;
}
public void setCountryName(String CountryName) {
this.CountryName = CountryName;
}
public String getCountryName() {
return CountryName;
}
}
//----------------------------------
public class Countries {
List<Country> countries = new ArrayList<Country>();
public Countries() {
super();
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
public List<Country> getCountries() {
if ( countries.size() == 0 ) {
countries.add( new Country("IT","ITALY"));
countries.add( new Country("IN","INDIA"));
countries.add( new Country("US","UNITED STATES"));
}
return countries;
}
public boolean addCountry( Country country ) {
return countries.add( country );
}
// I added this
public boolean removeCountry( Country country ) {
return countries.remove( country );
}
}
//----------------------------------
Then I decided to write (for a start) just plain Java classes and now it looks like below shown code.
It works in IDE, not yet implemented on weblogic server. I hope it would work.
//----------------------------------
package client;
public class Country {
String CountryId;
String CountryName;
public Country() {
super();
}
public Country(String id, String name) {
super();
this.CountryId = id;
this.CountryName = name;
}
public void setCountryId(String CountryId) {
this.CountryId = CountryId;
}
public String getCountryId() {
return CountryId;
}
public void setCountryName(String CountryName) {
this.CountryName = CountryName;
}
public String getCountryName() {
return CountryName;
}
}
//------------------------
package client;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Countries {
List<Country> countries = new ArrayList<Country>();
public Countries() {
super();
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
public List<Country> getCountries() {
if (countries.size() == 0) {
countries.add(new Country("IT", "ITALY"));
countries.add(new Country("IN", "INDIA"));
countries.add(new Country("US", "UNITED STATES"));
}
return countries;
}
public boolean addCountry(Country country) {
return countries.add(country);
}
// This left unused
public boolean removeCountry(Country country) {
return countries.remove(country);
}
// I added this - what would be more elegant or smarter way to do this?
public void removeCountry(String CountryId, String countryName) {
Iterator<Country> iterator = countries.iterator();
while (iterator.hasNext()) {
Country value = iterator.next();
if (CountryId.equals(value.CountryId) || countryName.equals(value.CountryName)) {
iterator.remove();
break;
}
}
}
}
//------------------
This class is just for test it won't go on server (JDeveloper integrated web logic server)
//-------------------------------
package client;
public class UserInterface {
public static void main(String[] args) {
String CountryId = "";
String CountryName = "";
CountryName = "ENGLAND";
Countries co = new Countries();
co.getCountries();
for (int i = 0; i < co.countries.size(); i++) {
System.out.print(co.getCountries().get(i).getCountryId());
System.out.print(" - ");
System.out.println(co.getCountries().get(i).getCountryName());
}
System.out.println("-------------------------");
// Add some countries
co.countries.add(new Country("DE", "GERMANY"));
co.countries.add(new Country("EN", "ENGLAND"));
for (int i = 0; i < co.countries.size(); i++) {
System.out.print(co.getCountries().get(i).getCountryId());
System.out.print(" - ");
System.out.println(co.getCountries().get(i).getCountryName());
}
System.out.println("-------------------------");
// Remove some countries, this works but can't use this (index)
// co.countries.remove(0); <--- there should be some index instead of 0
// I need to set properties
CountryId = "DE";
CountryName = "";
// Then remove country
co.removeCountry(CountryId, CountryName);
CountryId = "";
CountryName = "ENGLAND";
// Then remove country
co.removeCountry(CountryId, CountryName);
// Is there any way to remove object directly? Parameters should be set by web service iterator.
// co.countries.remove(o);
// co.removeCountry(country)
for (int i = 0; i < co.countries.size(); i++) {
System.out.print(co.getCountries().get(i).getCountryId());
System.out.print(" - ");
System.out.println(co.getCountries().get(i).getCountryName());
}
}
}
//------------------------
I would like to avoid my own iterator as JDeveloper can generate automatically iterators for webservices, but if I can't get it that way, what would be better way to write above mentioned iterator in removeCountry method?
Is there any way to remove object directly with something like this:
co.countries.remove(o);
co.removeCountry(country)
using method
// This left unused
public boolean removeCountry(Country country) {
return countries.remove(country);
}
from class Countries?
Parameters should be set by web service iterator.
I did it this way, and within "Test Web Service" (with manual inputs of course) it works (I can get, add and remove countries, i.e. objects).
I added this into ConutriesProvider application - which provides web service) into Countries class.
Is there any better solution than this?
//---------------------
public boolean removeCountry(Country country) {
Iterator<Country> iterator = countries.iterator();
while (iterator.hasNext()) {
Country value = iterator.next();
if (country.CountryId.equals(value.CountryId) || country.CountryName.equals(value.CountryName)) {
iterator.remove();
return true;
}
}
return false;
}
//--------------------

Java List sort on object fields constant values

I have a enum representing severity level
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
}
Person one = new Person();
one.setSeverity(Severity.HIGH);
other fields ...
Person two = new Person();
two.setSeverity(Severity.LOW);
.....
Person three = new Person();
three.setSeverity(Severity.HIGH);
List<Person> persons = Lists.newArrayList();
persons.add(one);
persons.add(two);
persons.add(three);
I would like to sort persons list to sort by severity field (i.e HIGH,MEDIUM then LOW).
My expected results after sorting the persons list should be in the order of HIGH,HIGH,LOW ?
can i know how i can achieve this ?
note : I am making use of com.google.common.collect
Try below code
Create an ENUM
package com.rais;
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String value;
private Severity(String value) {
this.value = value;
}
}
Now Create Person class according to your requirement eg.
package com.rais;
public class Person {
private Severity severity;
private String name;
public Person(Severity severity, String name) {
super();
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Finally create a Test Client and apply below logic.
package com.rais;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestClient {
public static void main(String[] args) {
Person one = new Person(Severity.HIGH, "shayam");
Person two = new Person(Severity.MEDIUM, "mohan");
Person three = new Person(Severity.LOW, "radha");
Person four = new Person(Severity.HIGH, "rakesh");
Person five = new Person(Severity.MEDIUM, "kailash");
Person six = new Person(Severity.LOW, "rais");
Person seven = new Person(Severity.LOW, "abhishek");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
persons.add(four);
persons.add(five);
persons.add(six);
persons.add(seven);
Collections.sort(persons, new Comparator<Person>() {
#Override
public int compare(Person person1, Person person2) {
if(person1.getSeverity()==person2.getSeverity())
{
return person1.getName().compareTo(person2.getName());
}
else{
return person1.getSeverity().compareTo(person2.getSeverity());
}
}
});
for (Person person : persons) {
System.out.println(person.getName()+" "+ person.getSeverity());
}
}
}
I am sure you will get below output.
rakesh HIGH
shayam HIGH
kailash MEDIUM
mohan MEDIUM
abhishek LOW
radha LOW
rais LOW
Use Comparable or comparator and then apply
Collection.sort().
if using comparable interface you have to implement compareTo method and
Collection.sort(<list>)
and if using comparator then you have to override compareTo method and
Collection.sort(<list>, <comparator>)
and when to use comparatot or comparable read link:
http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html
If you are using Google Collections, upgrade to Google Guava. Use its ComparisonChain class. Are you sure you want HIGH, MEDIUM, LOW in that order? The reverse fits Java comparisons better.
How do Persons have a severity level? Perhaps your class deserves a better name.
I would make Person implement Comparable, which makes the sorting code very simple and brief.
Note that enums are implicitly Comparable:
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String code;
private Severity(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
public class Person implements Comparable<Person> {
private Severity severity;
private final String name;
public Person(Severity severity, String name) {
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
#Override
public int compareTo(Person person) {
return severity == person.severity ? name.compareTo(person.name)
: severity.compareTo(person.severity);
}
#Override
public String toString() {
return name + "(" + severity +")";
}
}
Now some test code:
Person one = new Person(Severity.HIGH, "one");
Person two = new Person(Severity.LOW, "two");
Person three = new Person(Severity.HIGH, "three");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
Collections.sort(persons);
System.out.println(persons);
Output:
[one(HIGH), three(HIGH), two(LOW)]

Categories