Spring Boot Patient Application - java

an image of code for some reason
I am trying to have a little API run. Everything runs fine but I have to make an addition and am confused. I have to have it so in the URL when I type "localhost:8080/api/v1/{illness}" it will display the names of the people with that illness...help. I have included the two classes that I have. I didn't include my patient class. It's just the constructors and getters/setters for name, gender, illness, and id. I also didn't include the main well because its not needed
package com.sw409.Patientdemo.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.sw409.Patientdemo.model.Patient;
import com.sw409.Patientdemo.service.PatientService;
#RestController
public class PatientController {
PatientService patService = new PatientService();
// CREATE
#PostMapping("api/v1/patients")
public Patient addPatient(#RequestBody Patient p) {
return patService.addPatient(p);
}
//GET ILLNESS (HELP!!!!!!!!!!!!!!!!!!!!!!!)
#PostMapping("api/v1/patients/{illness}")
public void patientIllness() {
return patService.patientIllness(name, illness)
}
// READ
#GetMapping("api/v1/patients")
public List<Patient> getPatient() {
return patService.getPatients();
}
// UPDATE
#PatchMapping("api/v1/patient/{patid}")
public void updatePatient(#PathVariable("patid") Integer id, #RequestBody Patient p) {
patService.updatePatient(id, p);
}
// DELETE
#DeleteMapping("api/v1/patient/{patid}")
public void deletePatient(#PathVariable("patid") Integer id) {
patService.deletePatient(id);
}
}
package com.sw409.Patientdemo.service;
import java.util.*;
import com.sw409.Patientdemo.model.Patient;
public class PatientService {
List<Patient> patientList = new ArrayList<>();
// Create
public Patient addPatient(Patient pat) {
patientList.add(pat);
return pat;
}
public List<Patient> getPatients() {
return patientList;
}
//(HELPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP)
public void patientIllness(String illness) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).equals(illness){
}
}
}
public void updatePatient(Integer id, Patient p) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getId().equals(id)) {
patientList.set(i, p);
}
}
}
public void deletePatient(Integer id) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getId().equals(id)) {
patientList.remove(i);
}
}
}
}
package com.sw409.Patientdemo.model;
public class Patient {
String name;
Integer id;
String gender;
String illness;
public Patient(String name, Integer id, String gender, String illness) {
super();
this.name = name;
this.id = id;
this.gender = gender;
this.illness = illness;
}
public Patient() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIllness() {
return illness;
}
public void setIllness(String illness) {
this.illness = illness;
}
}

Controller
In case you want to get the value of something you should use GET instead of POST because POST use for creating or saving something
Your code:
#PostMapping("api/v1/patients/{illness}")
public void patientIllness() {
return patService.patientIllness(name, illness)
}
The parameter is missing patientIllness() that's why it cannot pass the value to service
The return type is void so you still cannot get anything
Suggestion:
#GetMapping("api/v1/patients/{illness}")
public List<Patient> patientIllness(#PathVariable String illness) {
return patService.patientIllness(illness);
}
Add paramiter in patientIllness(String illness) and you use it with path param so it will be patientIllness(#PathVariable String illness)
The return type should be something that you want to know if you want to know the List of Patients, return should be List<Patient>
Service
Your code:
public void patientIllness(String illness) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).equals(illness){
}
}
}
The return type is void so you have change it if you want to return something to controller
It's worng in this code patientList.get(i).equals(illness) Type of patientList.get(i) is Patient and you compare it with String
Suggestion1:
public List<Patient> patientIllness(String illness) {
List<Patient> result = new ArrayList<>();
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getIllness().equals(illness)) {
result.add(patientList.get(i));
}
}
return result;
}
The return type will be List<Patient>
You should compare with the same type patientList.get(i).getIllness().equals(illness)
Suggestion2: you can change to for each
public List<Patient> patientIllness(String illness) {
List<Patient> result = new ArrayList<>();
for (Patient patient : patientList) {
if (patient.getIllness().equals(illness)) {
result.add(patient);
}
}
return result;
}
Suggestion3: You can change it to use steam, filter, and collect it to list
public List<Patient> patientIllness(String illness) {
return patientList.stream()
.filter(patient -> patient.getIllness().equals(illness))
.collect(Collectors.toList());
}

First of all you need to change your controller function to something like this:
#PostMapping("api/v1/patients/{illness}")
public List<Patient> patientIllness(#PathVariable String illness) {
return patService.patientIllness(illness)
}
I don't understand why you called your service function with two arguments, because it can accept only one. You also need to make this function return list of patients instead of void. And illness is just a path variable, you use it in different functions, so you should understand it. And in your patient service you just need to use filter function, so it will look similiar to this:
public List<Patient> patientIllness(String illness) {
return patientList.stream().filter(patient->patient.getIllness().equals(illness)).collect(Collectors.toList());
}

patientIllness in Controller needs a parameter illness to accept illness path variable from URL.
Also name variable is not initialised (which is provided to service layer, but not used in service layer). So the name parameter can be removed.
Request mapping should be GET to retrieve data - recommended.
patientIllness in Controller should return a List<Patient> as received from service layer.

Related

Java: Arraylist out of bounds when processing file [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act()
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage()
{
return mortgage;
}
public void setMortgage(String mortgage)
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH

How to return Value after ifPresent Check

I am trying to return empName if its present Or else Empty String
But i am unable to return .
After ifPresent its not allowing me to return value , please help need with the syntax .
This is my Structure
import java.util.List;
public class EmployeeData {
private List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
This is my Employee class
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Test Program
import java.util.Collections;
import java.util.Optional;
public class Test {
public static void main(String args[]) {
EmployeeData empData = new EmployeeData();
}
public String getEmpName(EmployeeData empData)
{
Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().findFirst().ifPresent(
return emp->emp.getName();
)).orElse{
return "";
}
}
}
If you want any name of one of the employees you need to map to their name, then use findFirst and orElse.
The ifPresent is to consume the data and only if their is a data : here you want to return and do something if not present
public String getEmpName(EmployeeData empData) {
return Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().filter(Objects::nonNull)
.map(Employee::getName).findFirst().orElse("");
}

How to get access to a HashMap of objects from the Objects in that HashMap. (Java)

I have a hash map of some POJO Objects of a Class named User: HashMap<ObjectId, User>
These objects (Users) are related to each other. (I need to search through other users to Update one's Parameters)
How can I have access to the HashMap within a user object?
import org.bson.types.ObjectId;
import org.bson.BsonDocument;
import java.util.ArrayList;
import java.util.List;
public class User {
private ObjectId _id;
private int grade;
private String region;
private ArrayList<ObjectId> _reg_by;
private ObjectId regBy;
public User(){
}
public ObjectId getId() {
return _id;
}
public void setId(final ObjectId id) {
this._id = id;
}
public int getGrade() {
return grade;
}
public void setGrade(final int grade) {
this.grade = grade;
}
public String getRegion() {
return region;
}
public void setRegion(final String region) {
this.region = region;
}
public ObjectId getRegBy() {
if(regBy == null) {
regBy = ((_reg_by.size() != 0) ? _reg_by.get(0) : null);
}
return regBy;
}
public void setRegBy(final ObjectId regBy) {
this.regBy = regBy;
}
public ArrayList<ObjectId> get_reg_by(){
return _reg_by;
}
public void set_reg_by(ArrayList<ObjectId> _reg_by){
this._reg_by = _reg_by;
}
private String updateRegion(){
if(getRegBy() == null)
return null;
//TODO search for the person who registered him and use the region!
// how to get access to others from here?!
}
}
This is the User class where in regionUpdate() function I want to have this access
I creat this HashMap in my Main function.
HashMap<ObjectId, User> users = mongoHandler.getUsers();
I solved my problem by defining my HashMap as Static.
public static HashMap<ObjectId, User> users
so I can easily have access to it from anywhere by using the following code:
HashMap<ObjectId, User> users = Main.users
or any method e.g. Main.users.getId();
Another solution could have been to create a property within your "User" class that contains a list of related users, and if you know that one user is related to another, added it to the each user as you build the list.
public class User {
...
private List<User> relatedUsers = new ArrayList<User>();
...
private void updateRelatedUsers() {
for(User relatedUser : relatedUsers) {
//do stuff to update the relatedUser object.
relatedUser.setSomething(someValue);
}
}
//Getter and setter
public List<User> getRelatedUsers() {
return relatedUsers;
}
public void setRelatedUsers(List<User> relatedUsers) {
this.relatedUsers = relatedUsers;
}
...
}
Add the users like so:
...
User myUser = creatUserHoweverYouDo();
User myRelatedUser = getMyRelatedUser(myUser);
myUser.getRelatedUsers().add(myRelatedUser);
...

Is it possible to change the JSON names for Spring Data pageable responses?

I'm trying the Page and Pageable interface from Spring Data. It returns JSON in the following format
{"content":
[... my objects ...],
"last":false,
"totalPages":7,
"totalElements":13,
"size":2,
"number":0,
"sort":null,
"first":true,
"numberOfElements":2}
The questions I have is how can I change the names of these JSON elements?
The company I work for has strict guidelines on service JSON naming conventions, so out of the box this wouldn't work for me, but if it's possible to change these names then I could use it.
Create a class, maybe called PageWrapper, which implements org.springframework.data.domain.Page and has a constructor, which gets another Page as an argument.
Delegate all method calls to the wrapped Page instance.
After that you can use #JsonProperty annotations to rename the fields in the serialized JSON.
Wrap the Page (in fact a PageImpl) instance with an instance of PageWrapper and change the return type of your resource methods to PageWrapper.
Try using:
#Entity
public class City {
#id
Long id;
String name;
#JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
#JsonProperty("value")
public Long getId() { return id; }
public void setName(Long id){ this.id = id; }
}
reference
As said in last answers the best to do is to use page wrapper.That means you have to build a page that will create a representation of the resource you want to expose.
It will help you to put the links to paginate between content and also to have the metadata ( total of pages, size, number of elements ect.. ) just as with the pageable interface.
Here is a short example. A full example is provided HERE
public class PagedResource<T> {
private List<T> content;
private final Map metadata;
public PagedResource(Page<T> page, String pageParam, String sizeParam, String sortParam, String sortField) {
super();
this.setContent(page.getContent());
this.metadata = new HashMap();
List<Link> links = new ArrayList<Link>();
if (page.hasPrevious()) {
String path = createBuilder().queryParam(pageParam, page.getNumber() - 1).queryParam(sizeParam, page.getSize()).queryParam(sortParam, sortField).build().toUriString();
Link previousPageLink = new Link(path, Link.REL_PREVIOUS);
links.add(previousPageLink);
}
if (page.hasNext()) {
String path = createBuilder().queryParam(pageParam, page.getNumber() + 1).queryParam(sizeParam, page.getSize()).queryParam(sortParam, sortField).build().toUriString();
Link nextPageLink = new Link(path, Link.REL_NEXT);
links.add(nextPageLink);
}
if (!page.isFirst()) {
Link firstPageLink = buildPageLink(pageParam, 0, sizeParam, page.getSize(), sortParam, sortField, Link.REL_FIRST);
links.add(firstPageLink);
}
if (!page.isLast()) {
int lastPage = page.getTotalPages() - 1;
Link lastPageLink = buildPageLink(pageParam, lastPage, sizeParam, page.getSize(), sortParam, sortField, Link.REL_LAST);
links.add(lastPageLink);
}
Link currentPagelink = buildPageLink(pageParam, page.getNumber(), sizeParam, page.getSize(), sortParam, sortField, Link.REL_SELF);
links.add(currentPagelink);
populateMetadata(page, links);
}
private void populateMetadata(Page<T> page, List<Link> links) {
int per_page = page.getSize();
int totalPages = page.getTotalPages();
int numberOfPageElements = page.getNumberOfElements();
metadata.put("numberOfPageElements", numberOfPageElements);
metadata.put("perPage", per_page);
metadata.put("totalPages", totalPages);
metadata.put("links", links);
}
private Link buildPageLink(String pageParam, int page, String sizeParam, int size, String sortParam, String sortAttribute, String rel) {
String path = createBuilder().queryParam(pageParam, page).queryParam(sizeParam, size).queryParam(sortParam, sortAttribute).toUriString();
Link link = new Link(path, rel);
return link;
}
private ServletUriComponentsBuilder createBuilder() {
return ServletUriComponentsBuilder.fromCurrentRequestUri();
}
public List<T> getContent() {
return content;
}
public void setContent(List<T> content) {
this.content = content;
}
public Map getMetadata() {
return metadata;
}
}
Hope it helps !
Use the #JsonProperty to rename. Sample below:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public class PageWrapper<T> implements Page<T> {
private final Page<T> delegate;
public PageWrapper(#JsonProperty("content") final List<T> content,
#JsonProperty("number") final int number,
#JsonProperty("size") final int size,
#JsonProperty("total_elements") final long totalElements) {
delegate = new PageImpl<>(content, PageRequest.of(number, size), totalElements);
}
public PageWrapper(final List<T> content,
final Pageable pageable,
final long total) {
delegate = new PageImpl<>(content, pageable, total);
}
#JsonProperty("total_pages")
#Override
public int getTotalPages() {
return delegate.getTotalPages();
}
#JsonProperty("total_elements")
#Override
public long getTotalElements() {
return delegate.getTotalElements();
}
#JsonProperty("number")
#Override
public int getNumber() {
return delegate.getNumber();
}
#JsonProperty("size")
#Override
public int getSize() {
return delegate.getSize();
}
#JsonProperty("number_of_elements")
#Override
public int getNumberOfElements() {
return delegate.getNumberOfElements();
}
#JsonProperty("content")
#Override
public List<T> getContent() {
return delegate.getContent();
}
#JsonProperty("has_content")
#Override
public boolean hasContent() {
return delegate.hasContent();
}
#JsonIgnore
#Override
public Sort getSort() {
return delegate.getSort();
}
#JsonProperty("is_first")
#Override
public boolean isFirst() {
return delegate.isFirst();
}
#JsonProperty("is_last")
#Override
public boolean isLast() {
return delegate.isLast();
}
#JsonIgnore
#Override
public boolean hasNext() {
return delegate.hasNext();
}
#JsonIgnore
#Override
public boolean hasPrevious() {
return delegate.hasPrevious();
}
#JsonIgnore
#Override
public Pageable nextPageable() {
return delegate.nextPageable();
}
#JsonIgnore
#Override
public Pageable previousPageable() {
return delegate.previousPageable();
}
#Override
public <U> Page<U> map(final Function<? super T, ? extends U> function) {
return delegate.map(function);
}
#JsonIgnore
#Override
public Iterator<T> iterator() {
return delegate.iterator();
}
}

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;
}
//--------------------

Categories