List is not in order - java

I converted UUID to string (String id) and put the conversion inside a method.
I also declared other String variables such as FirstName etc and put in on an ArrayList:
Code
The code does work. But I'm confused why the string email was showing second on the list.
public class StudentController {
#Autowired
StudentService studentService = new StudentService();
#GetMapping
public List<Student> displayStudent(){
return studentService.getStudent();
}
}
public class StudentService {
Student student = new Student();
private List<Student> studentList = Arrays.asList(
new Student(student.genID(),"Elvis" , "Presley" ,"Elvis#gmail.com")
);
public List<Student> getStudent(){
return studentList;
}
}
public class Student {
UUID uuid = UUID.randomUUID();
private String id;
private String FirstName;
private String LastName;
private String email;
public Student() {}
//Method Converting UUID into string
public String genID(){
id = uuid.toString();
return id;
}
public Student(String id) {
this.id = id;
}
public Student(String id, String firstName, String lastName, String email) {
this.id = id;
FirstName = firstName;
LastName = lastName;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Expected
I expected data to be in this order
ID , FirstName , LastName , email
Actual Output JSON

JSON is an unordered collection, as specified on https://www.json.org/json-en.html , so you don't have to worry about it. It might depend on library though.

Specify the serialized order of properties
The order of properties during serialization can be defined in Jackson.
Either at class-level specifically using annotation #JsonPropertyOrder.
Or globally for your ObjectMapper using a feature:
objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
Example
In your case you can achieve expected order using the annotation on your class:
#JsonPropertyOrder({'id', 'firstName', 'lastName', 'email'})
public class Student {
// body of your class
}
Or separately with an index on your fields:
public class Student {
#JsonProperty(index=10)
private String id;
// not ordered specifically
private String firstName;
private String lastName;
#JsonProperty(index=20)
private String email;
// remainder of your class
}
See also
Jackson ObjectMapper - specify serialization order of object properties
Order of JSON objects using Jackson's ObjectMapper
Jackson JSON - Using #JsonPropertyOrder annotation to define serialized properties ordering

Related

How can I get a value from a map with a key?

I am trying to find a specific object. I'm using the following code, but it seem like get only sends back a Boolean that verifies that there is a key with this name, but not an array of Boolean values that I need to use in my program:
private Map<User, ArrayList<Boolean>> userDayOfVacationMap;
public ArrayList<Boolean> getUserVacationList(User key){
return this.userDayOfVacationMap.get(key);
}
Is there a method for this?
Here is the User object:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
#OneToMany(mappedBy="user", cascade = CascadeType.ALL)
public Set<Vacation> vacations;
public User(String firstName, String lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
public User(){}
public Set<Vacation> getVacations() {
return vacations;
}
public void setId(int id){
this.id = id;
}
public Integer getId(){
return this.id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
However, I can't add a variable in this function, because it would add non-useful information into my database.

Spring data elasticsearch sorting

I am trying to learn spring data elasticsearch, and created a sample project. Right now, I am trying to get familiar with the mechanics of sorting.
Simply put, I have a Person class, that has a firstName and lastName field. I am trying to sort on the lastNameField.
Here is my Person class:
#Document(indexName = "entities", type = "person", shards=1, replicas=0)
public class Person {
#Id
private String id;
#Field(type=FieldType.String, index=FieldIndex.not_analyzed)
private String firstName;
#Field(type=FieldType.String, index=FieldIndex.not_analyzed)
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is my DAO logic:
#Override
public Page<Person> getPeople(int pageNumber, int pageSize, Direction direction, String...sortFields) {
return personRepository.findAll(new PageRequest(pageNumber, pageSize, direction, sortFields));
}
The personRepository is an empty interface that extends PagingAndSortingRepository
And the actual call:
int pageSize = 1;
int currentPageNumber = -1;
boolean morePages = true;
while(morePages){
Page<Person> results = personDataHandler.getPeople(currentPageNumber+1, pageSize, Direction.DESC, "firstName");
List<Person> people = results.getContent();
if(!CollectionUtils.isEmpty(people)){
for(Person currentPerson: people){
System.out.println("[firstName: "+currentPerson.getFirstName()+", lastName: "+currentPerson.getLastName()+"]");
}
}
currentPageNumber++;
morePages = results.hasNext();
}
Could having a page size of 1 be the issue?

Spring MVC form validation does't work for nested complex types

I am implementing a sample Spring MVC Form with Form Validation. I have a complex type Address as bean property for Student form bean. And I have added form validation #NotEmpty for Address bean properties. But the same is not reflecting in the UI. But form validation works for other primitive types of Student form bean.
So, Validation works perfectly for Student form bean but not for nested complex types like Address within Student form bean.
I am trying understand the reason and a fix.
Spring version 4.0+.
Hibernate Validator api:5.2.4
Student POJO:
package com.xyz.form.beans;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.DateNotEmpty;
import com.xyz.validators.ListNotEmpty;
public class Student {
#Size(min = 2, max = 30)
private String firstName;
#Size(min = 2, max = 30)
private String lastName;
#NotEmpty
private String gender;
#DateNotEmpty
#Past
private Date DOB;
private String email;
private String mobileNumber;
#ListNotEmpty
private List<String> courses;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public List<String> getCourses() {
return courses;
}
public void setCourses(List<String> courses) {
this.courses = courses;
}
}
Address POJO:
package com.xyz.form.beans;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.LongNotEmpty;
public class Address {
#NotEmpty
private String houseNo;
#NotEmpty
private String street;
#NotEmpty
private String area;
#NotEmpty
private String city;
#LongNotEmpty
private Long pin;
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Long getPin() {
return pin;
}
public void setPin(Long pin) {
this.pin = pin;
}
}
Student Controller:
#RequestMapping(value = "/newStudentDetails.do", method = RequestMethod.POST)
public ModelAndView newStudentDetails(
#Valid #ModelAttribute("student") com.xyz.form.beans.Student studentFormBean,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ModelAndView("newStudentPage");
}
Student studentDto = new Student();
studentDto.setFirstName(studentFormBean.getFirstName());
studentDto.setLastName(studentFormBean.getLastName());
studentDto.setGender(studentFormBean.getGender());
studentDto.setDOB(new Date(studentFormBean.getDOB().getTime()));
studentDto.setEmail(studentFormBean.getEmail());
studentDto.setMobileNumber(studentFormBean.getMobileNumber());
StringBuilder sb = new StringBuilder();
sb.append(studentFormBean.getAddress().getHouseNo() + ", ");
sb.append(studentFormBean.getAddress().getStreet() + ", ");
sb.append(studentFormBean.getAddress().getArea() + ", ");
sb.append(studentFormBean.getAddress().getCity() + "-");
sb.append(studentFormBean.getAddress().getPin());
studentDto.setAddress(sb.toString());
studentDto.setCourses(studentFormBean.getCourses());
studentDao.createStudent(studentDto);
ModelAndView mav = new ModelAndView("newStudentSuccess");
return mav;
}
Thanks,
Viswanath
You need to annotate your complex types with #Valid.
This is the reference (which references here)
Hi lets try #ModelAttribute("student") #Valid com.xyz.form.beans.Student studentFormBean in place of #Valid #ModelAttribute("student")
For nested complex types, you have to activate the direct field access. Just like below:
#org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.initDirectFieldAccess();
}

How to Retrieve the subfields stored in MongoDB

The below data is stored in MongoDB. I am using Spring-Data and storing the data into mongoDB.
If I want to retrieve the fields ("id" or "Name") I can able to do, but if I want to retrieve the sub fields ("firstName" or "lastName")I can't.
(eg.)If I want to retrieve sub field "lastName" from the below data I can't.Can anyone help me in this regards.
Thanks in advance.
Data Stored in MongoDB:
{
"id":101,
"name": {"firstName":"Mark",
"lastName":"Antony"
}
}
The Code I am using is:
PersonService.java
public List<Audit> searchPerson(Audit audit)
{
List<NameDetails> name=audit.getName();
return mongoTemplate.find(new Query(Criteria.where("name.lastName").is(name.get(0))), Audit.class,COLLECTION_NAME);
}
PersonController.java
#RequestMapping(value = "/person/search", method = RequestMethod.GET)
public String search(#ModelAttribute Audit audit, ModelMap model) {
model.addAttribute("personList", personService.searchPerson(audit));
return "output";
}
Audit.java
#Document
public class Audit {
#Id
private String id;
private List<NameDetails> name;
public String getId() {
System.out.println("Person: getId");
return id;
}
public void setId(String id) {
System.out.println("Person: setId");
this.id = id;
}
public List<NameDetails> getName() {
System.out.println("Audit: getName");
return name;
}
public void setName(List<NameDetails> name) {
System.out.println("Audit: setName");
this.name = name;
}
}
NameDetails.java
package com.register.mongo.model;
public class NameDetails {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
System.out.println("NameDetails: setFirstName");
this.firstName = firstName;
}
public String getLastName() {
System.out.println("NameDetails: getLastName");
return lastName;
}
public void setLastName(String lastName) {
System.out.println("NameDetails: setLastName");
this.lastName = lastName;
}
}
(output.jsp)UI Page
<table border="2">
<c:forEach var="person" items="${personList}">
<tr>
<td>${person.id}</td>
</tr>
<tr>
<td>${person.lastName}</td>
</tr>
</c:forEach>
</table>
If i understand well, you should make an extra class and use it in the Audit class
public class NameDetails{
private String FirstName;
private String LastName;
public String getFirstName() {
return id;
}
public void seFirstName(String fisrtName) {
this.FirstName= fisrtName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
and use this class in the Audit.class
#Document
public class Audit {
#Id
private String id;
private List name<NameDetails>;
and then the setters and getters

Apache Camel - Json to POJO automatic data type conversion?

Can Camel be configured to automatically handle data type conversions from JSON to a POJO. For example...looking at Camels website we have the following JSON example:
{
"id" : 123,
"first_name" : "Donald"
"last_name" : "Duck"
}
and corresponding POJO
public class PersonPojo {
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
but does Camel have automatic data type converters where I could set the POJO up to have the ID field unmarshalled to a String object, rather than an int?
Yes, this can be achieved with TypeConverters http://camel.apache.org/type-converter.html
You can also perform this explicitly with the dataFormats element too http://camel.apache.org/data-format.html
Hope that helps :)

Categories

Resources