CSV file does not open correctly on Mac computers - java

I am using jackson-dataformat-csv library to generate a csv file but I am cannot open it correctly on Mac Computers. Here is the java code to generate csv, I do not know what I am doing wrong here:
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CsvDownload {
public static void main(String[] args) throws IOException {
User user1 = new User("Cow",25, "xxxxxx#gmail.com","1234567890",
"Street","Heights","7100",
"Male","Town");
User user2 = new User("John",26, "xxxxxxx#gmail.com","+1234567890",
"Street","Heights","7100",
"Male","Town");
List<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2);
// create mapper and schema
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(User.class).withHeader();
schema = schema.withColumnSeparator(',');
// output writer
ObjectWriter myObjectWriter = mapper.writer(schema);
File tempFile = new File("users.csv");
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(tempFileOutputStream, 1024);
OutputStreamWriter writerOutputStream = new
OutputStreamWriter(bufferedOutputStream, "UTF-8");
myObjectWriter.writeValue(writerOutputStream, users);
}
}
Model class:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder(value = {"name", "age", "email", "phone_number",
"physical_address", "postal_address", "postal_code",
"gender", "city"})
public class User {
#JsonProperty("Name")
private String name;
#JsonProperty("Age")
private int age;
#JsonProperty("Email Address")
private String email;
#JsonProperty("Phone Number")
private String phone_number;
#JsonProperty("Physical Address")
private String physical_address;
#JsonProperty("Postal Address")
private String postal_address;
#JsonProperty("Postal Code")
private String postal_code;
#JsonProperty("Gender")
private String gender;
#JsonProperty("City")
private String city;
public User(String name, int age, String email, String phone_number, String
physical_address, String postal_address, String postal_code, String gender,
String city) {
this.name = name;
this.age = age;
this.email = email;
this.phone_number = phone_number;
this.physical_address = physical_address;
this.postal_address = postal_address;
this.postal_code = postal_code;
this.gender = gender;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getPhysical_address() {
return physical_address;
}
public void setPhysical_address(String physical_address) {
this.physical_address = physical_address;
}
public String getPostal_address() {
return postal_address;
}
public void setPostal_address(String postal_address) {
this.postal_address = postal_address;
}
public String getPostal_code() {
return postal_code;
}
public void setPostal_code(String postal_code) {
this.postal_code = postal_code;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
This the code I am using to generate a csv file but does not open right on Mac computers, I do not have issues on windows.
Screen image

Related

Spring batch IllegalStateException for updates

I'm fairly new to Spring, and coding in general. I want to build an application from which a user can update existing records in a database from a CSV file. I'm using spring batch to do so, but when I execute the test, I get the famous:
java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove #Transactional annotations from client).
If I remove the #Transactional, I get this error instead:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.example.testApp.Models.Person p SET p.address = p.address, p.country = p.country, p.cellphone = p.cellphone, p.city = p.city, p.phone = p.cellphone, p.email = p.email, p.age = p.age WHERE p.pplId IN (:ids_0, :ids_1, :ids_2, :ids_3, :ids_4, :ids_5, :ids_6, :ids_7, :ids_8, :ids_9, :ids_10)]
I've looked around some other solutions here, but they don't seem to work for what I want to do. I'm aware that hibernate supports batch updates, but again, I'm not sure how to make it work with what I already have.
Here's my test class (obviously with just the method I've been having problems with):
#SpringBootTest
public class PersonTests {
#Autowired
private PeopleRepository peopleRepository;
#Autowired
JobLauncher jobLauncher;
#Autowired
Job peopleInsertJob; //Separate job for inserting from a CSV file
#Autowired
Job peopleUpdateJob;
#Order(4) //executes after the insert from CSV test, for obvious reasons.
#Test
public void updateRecordsFromCsvFile() throws Exception {
Map<String, JobParameter> maps = new HashMap<>();
maps.put("time", new JobParameter(System.currentTimeMillis()));
JobParameters parameters = new JobParameters(maps);
JobExecution jobExecution = jobLauncher.run(peopleUpdateJob, parameters);
assertEquals("COMPLETED", jobExecution.getStatus().name());
}
}
Here's my Batch configuration file for the update:
#Bean
public Job peopleUpdateJob(JobBuilderFactory jobBuilderFactory,
StepBuilderFactory stepBuilderFactory,
ItemReader<Person> itemReaderForUpdate,
ItemProcessor<Person, Person> itemProcessor,
#Qualifier("DBPeopleUpdater") ItemWriter<Person> itemUpdater)
{
Step step = stepBuilderFactory.get("ETL-file-load")
.<People, People>chunk(100)
.reader(itemReaderForUpdate)
.processor(itemProcessor)
.writer(itemUpdater)
.build();
return jobBuilderFactory.get("ETL-Load")
.incrementer(new RunIdIncrementer())
.start(step)
.build();
}
#Bean
public FlatFileItemReader itemReaderForUpdate() throws Exception
{
FlatFileItemReader<Person> flatFileItemReader = new FlatFileItemReader<>();
flatFileItemReader.setResource(new FileSystemResource("src/main/resources/CSV/TestFilePeople-UpdateBatch.csv"));
flatFileItemReader.setName("PeopleCSV-Update-Reader");
flatFileItemReader.setLinesToSkip(1);
flatFileItemReader.setLineMapper(lineMapper());
return flatFileItemReader;
}
#Bean
public LineMapper<Person> lineMapper()
{
DefaultLineMapper<Person> defaultLineMapper = new DefaultLineMapper<>();
DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
lineTokenizer.setDelimiter(",");
lineTokenizer.setStrict(false);
lineTokenizer.setNames("Id","lastname", "lastname2", "firstname",
"midname","phone", "cellphone", "email", "status", "address", "city", "region", "country");
BeanWrapperFieldSetMapper<Person> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
fieldSetMapper.setTargetType(Person.class);
defaultLineMapper.setLineTokenizer(lineTokenizer);
defaultLineMapper.setFieldSetMapper(fieldSetMapper);
return defaultLineMapper;
}
This is the ItemWriter I'm using for the update:
#Component
public class DBPeopleUpdater implements ItemWriter<Person> {
#Autowired
PeopleRepository peopleRepository;
#Override
public void write(List<? extends Person> list) throws Exception
{
List<String> pplIds = new ArrayList<>();
for(People p : list)
{
pplIds.add(p.getpplId());
}
peopleRepository.updatePersonsByIdIsIn(pplIds);
}
}
This is the method that I'm using from my PeopleRepository. It's the only method I have. My repository is extends CrudRepository:
#Modifying
#Query("UPDATE Person p SET p.address= p.address, p.country = p.country," +
"p.cellphone = p.cellphone, p.city = p.city, p.phone = p.cellphone," +
"p.email = p.email, p.status = p.status WHERE p.pplId IN :ids")
List<Person>updatePersonsByPplIdIsIn(List<String> ids);
I'm mapping my Person class as an entity that connects to a PostgreSQL database table. I don't have any local sql files in my project. I have no other tables in the database.
If it's not possible to solve this using spring batch, if you could guide me towards jpa/hibernate resources I could use to understand how to solve this problem, I would really appreciate it.
EDIT
Here's the code for the entity
#Entity
#Table(name = "people", schema = "example_schema")
public class Person {
#NonNull
#Id
#Column(name = "ppl_id")
private String pplId;
#Column(name = "ppl_last_name")
private String lastname;
#Column(name = "ppl_sec_last_name")
private String lastname2;
#Column(name = "ppl_first_name")
private String firstname;
#Column(name = "ppl_mid_name")
private String midname;
#Column(name = "ppl_phone_no")
private String phone;
#Column(name = "ppl_cell_no")
private String cellphone;
#Column(name = "ppl_corp_email")
private String email;
#Column(name="ppl_status")
private String status;
#Column(name="ppl_address")
private String address;
#Column(name="ppl_city")
private String city;
#Column(name="ppl_region")
private String region;
#Column(name="ppl_country")
private String country;
//Default constructor
public Person()
{
super();
}
public Person(#NonNull String pplId, String lastname, String lastname2, String firstname, String midname, String phone, String cellphone, String email, String status, String address, String city, String region, String country) {
this.pplId = pplId;
this.lastname = lastname;
this.lastname2 = lastname2;
this.firstname = firstname;
this.midname = midname;
this.phone = phone;
this.cellphone = cellphone;
this.email = email;
this.status = status;
this.address = address;
this.city = city;
this.region = region;
this.country = country;
}
public String getPplId() {
return pplId;
}
public void setWrkId(String pplId) {
this.pplId = pplId;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname2() {
return lastname2;
}
public void setLastname2(String lastname2) {
this.lastname2 = lastname2;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getMidname() {
return midname;
}
public void setMidname(String midname) {
this.midname = midname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

How do i override functions in a Vaadin 12 project? ValueProvider, SelectionListener and ComponentEventListener

This will be quite a bit of code as I don't know what will be important. I was trying to recreated the basic UI Alejandro made in my tutorial session with him a few months ago, substituting a table in my database for the one he used. The errors I'm getting all seem related to overriding Vaadin Flow functions. I know that replaces the behavior of the Super method. IntelliJ opens the relevant Super method when I click on the errors, which I'm assuming it wants me to edit to solve the problem, but I have no idea how to do that.
I was going to paste a link to the code but the forum told me to just place it here.
Customer.java
package com.dbproject.storeui;
import java.time.LocalDate;
public class Customer {
private Long id;
private String lastname;
private String firstname;
private String email;
private String password;
private String phone;
private String street;
private String city;
private String st;
private int zip;
private LocalDate dob;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSt() {
return st;
}
public void setSt(String st) {
this.st = st;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
}
CustomerRepository.java
package com.dbproject.storeui;
import org.apache.ibatis.annotations.*;
import java.util.List;
#Mapper
public interface CustomerMapper {
#Select("SELECT * FROM customer ORDER BY id")
List<Customer> findAll();
#Update("UPDATE customer" +
"SET lastname=#{lastname}, firstname=#{firstname}, email=#{email}, password=#{password}, phone=#{phone}, street=#{street}, city=#{city}, st=${st}, zip=#{zip}, dob=#{dob}" +
"WHERE id=#{id}")
void update(Customer customer);
#Insert("INSERT INTO customer(lastname, firstname, email, password, phone, street, city, st, zip, dob) VALUES(#{lastname}, #{firstname}, #{email}, #{password}, #{phone}, #{street}, #{city}, #{st}, #{zip}, #{dob})")
#Options(useGeneratedKeys = true, keyProperty = "id")
void create(Customer customer);
}
CustomerView.java (the UI class)
package com.dbproject.storeui;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
#Route("")
public class CustomerView extends Composite<VerticalLayout> {
private final CustomerMapper customerMapper;
private Grid<Customer> grid = new Grid<>();
private TextField lastname = new TextField("Last Name");
private TextField firstname = new TextField("First Name");
private Button save = new Button("Save", VaadinIcon.CHECK.create());
private Button create = new Button("New", VaadinIcon.PLUS.create());
private VerticalLayout form = new VerticalLayout(lastname, firstname, save);
private Binder<Customer> binder = new Binder<>(Customer.class);
private Customer customer;
public CustomerView(CustomerMapper customerMapper) {
this.customerMapper = customerMapper;
grid.addColumn(Customer::getLastname).setHeader("Last Name");
grid.addColumn(Customer::getFirstname).setHeader("First Name");
grid.addSelectionListener(event -> setCustomer(grid.asSingleSelect().getValue()));
updateGrid();
save.addClickListener(event -> saveClicked());
create.addClickListener(event -> createClicked());
getContent().add(grid, create, form);
binder.bindInstanceFields(this);
binder.setBean(null);
}
private void createClicked() {
grid.asSingleSelect().clear();
setCustomer(new Customer());
}
private void saveClicked() {
binder.readBean(customer);
if (customer.getId() == null) {
customerMapper.create(customer);
} else {
customerMapper.update(customer);
}
updateGrid();
Notification.show("Saved!");
}
private void setCustomer(Customer customer) {
this.customer = customer;
form.setEnabled(customer != null);
binder.setBean(customer);
}
private void updateGrid() {
grid.setItems(customerMapper.findAll());
}
}

Create list with unique id in Java and manipulate it

I want to create a programm that creates a list that looks like this
ID: 1
Name: Example
Surname: Example
email: example
//New list
ID: 2
Name: Example
Surname: Example
email: example
and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2
You should use a HashMap.
Create a class (let's class it YourClass) that contains ID, name, surname and email instance variables.
Then create a HashMap where the key is the identifier and the value is YourClass:
Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}
you can create class like this
public class Record{
private int id;
private String name;
private String Surname;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and then use it like this:
Record record1 = new Record();
record1.setId(1);
record1.setName("example");
record1.setSurname("example");
record1.setEmail("example");
Record record2 = new Record();
record2.setId(2);
record2.setName("example");
record2.setSurname("example");
record2.setEmail("example");
Map<Integer,Record> recordMap = new HashMap<Integer, Record>();
recordMap.put(record1.getId(),record1);
recordMap.put(record2.getId(),record2);]
recordMap.get(2).getName();//example
recordMap.get(2).setName("ebi");
recordMap.get(2).getName();//ebi
import java.util.ArrayList;
import java.util.List;
public class Person {
private int id;
private String name;
private String Surname;
private String email;
public Person(int id, String name, String surname, String email) {
super();
this.id = id;
this.name = name;
Surname = surname;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person(1, "example", "example", "example"));
list.add(new Person(2, "example", "example", "example"));
}
}

How to customise an XML export using JAXB

For testing purposes, I used used JAXB to generate an XML from an Object. This work fine. The code is below.
package com.mns.mnsutilities.jaxb.model;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlRootElement(name="Emp_MNS")
#XmlType(propOrder= {"name", "age", "role", "gender", "addressesList"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
private List<Address> addressesList;
public Employee() {}
public Employee(int id, String gender, int age, String name, String role,
String password) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
}
public Employee(int id, String gender, int age, String name, String role,
String password, List<Address> addressesList) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
this.addressesList = addressesList;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "gen")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// #XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
#XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlElement(name = "addresses")
public List<Address> getAddressesList() {
return addressesList;
}
public void setAddressesList(List<Address> addressesList) {
this.addressesList = addressesList;
}
#Override
public String toString() {
return "Employee [id=" + id + ", gender=" + gender + ", age=" + age
+ ", name=" + name + ", role=" + role + ", password="
+ password + ", addressesList=" + addressesList + "]";
}
}
And:
package com.mns.mnsutilities.jaxb.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(namespace="")
public class Address {
private String street;
private String city;
private String zipCode;
private String country;
public Address() {}
public Address(String street, String city, String zipCode, String country) {
super();
this.street = street;
this.city = city;
this.zipCode = zipCode;
this.country = country;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", zipCode="
+ zipCode + ", country=" + country + "]";
}
}
My main Class is :
package com.mns.mnsutilities.jaxb.batch;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.mns.mnsutilities.jaxb.model.Address;
import com.mns.mnsutilities.jaxb.model.Employee;
public class LaunchAction {
private static final String FILE_NAME = "output/CT3D_XML_SAMPLE_FINAL.xml";
public static void main(String[] args) {
Employee emp = new Employee();
emp.setId(1);
emp.setAge(25);
emp.setName("Yovan");
emp.setGender("Male");
emp.setRole("Developer");
emp.setPassword("sensitive");
List<Address> addressesList = new ArrayList<>();
Address address1 = new Address("Main Road", "Ebene", "11111", "Mauritius");
Address address2 = new Address("Royal Road", "Rose-Hill", "2222", "Mauritius");
addressesList.add(address1);
addressesList.add(address2);
emp.setAddressesList(addressesList);
jaxbObjectToXML(emp);
Employee empFromFile = jaxbXMLToObject();
System.out.println(empFromFile.toString());
}
private static Employee jaxbXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller un = context.createUnmarshaller();
Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
return emp;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
private static void jaxbObjectToXML(Employee emp) {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller m = context.createMarshaller();
//for pretty-print XML in JAXB
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out for debugging
m.marshal(emp, System.out);
// Write to File
m.marshal(emp, new File(FILE_NAME));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
The XML output is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp_MNS id="1">
<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">
</name>
<age>25</age>
<role>Developer</role>
<gen>Juggoo</gen>
<addresses>
<city>Ebene</city>
<country>Mauritius</country>
<street>Main Road</street>
<zipCode>11111</zipCode>
</addresses>
<addresses>
<city>Rose-Hill</city>
<country>Mauritius</country>
<street>Royal Road</street>
<zipCode>2222</zipCode>
</addresses>
</Emp_MNS>
What I really would like to have is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp_MNS id="1">
<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">
</name>
<age>25</age>
<role>Developer</role>
<gen>Juggoo</gen>
<addresses>
**<address>**
<city>Ebene</city>
<country>Mauritius</country>
<street>Main Road</street>
<zipCode>11111</zipCode>
**</address>**
**<address>**
<city>Rose-Hill</city>
<country>Mauritius</country>
<street>Royal Road</street>
<zipCode>2222</zipCode>
**</address>**
</addresses>
</Emp_MNS>
Could you please guide me on how to proceed?
You can do the following:
#XmlElementWrapper(name="addresses")
#XmlElement(name="address")
public List<Address> getAddressesList() {

JAXB - Prevent nillable attributes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"

Here is my problem: I need the name tag of by object to be present in the XML but without the nillable attributes : In short like <name/>. Here is the code for the object.
If name is null, I do get the tag <name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>, but the additional attributes may cause problem to the client.
As I have read, semantically it does make sense to represent the null values this way (using #XmlElement(nillable=true)).
package com.mns.mnsutilities.jaxb.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name="Emp_MNS")
#XmlType(propOrder= {"name", "age", "role", "gender", "addressesList"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
private List<Address> addressesList;
public Employee() {}
public Employee(int id, String gender, int age, String name, String role,
String password) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
}
public Employee(int id, String gender, int age, String name, String role,
String password, List<Address> addressesList) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
this.addressesList = addressesList;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "gen", nillable=true)
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlElementWrapper( name="addresses" )
#XmlElement(name = "address")
public List<Address> getAddressesList() {
if(addressesList == null){
addressesList = new ArrayList<>();
}
return addressesList;
}
public void setAddressesList(List<Address> addressesList) {
this.addressesList = addressesList;
}
#Override
public String toString() {
return "Employee [id=" + id + ", gender=" + gender + ", age=" + age
+ ", name=" + name + ", role=" + role + ", password="
+ password + ", addressesList=" + addressesList + "]";
}
}
Expanding on the comment made by Ian Roberts you could leverage field access and have the property treat a field value of "" as null.
#XmlRootElement(name="Emp_MNS")
#XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
private String name = "";
public String getName() {
if(name.length() == 0) {
return null;
}
return name;
}
public void setName(String name) {
if(null == name) {
this.name = "";
} else {
this.name = name;
}
}
i got the same problem,But my field is enum,It can't be emyty string;so I just use
myXml.replaceAll("xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"","")
in another solution,I add a empty string value to my enum,such as
#XmlEnum
#Getter
public enum MyEnum {
#XmlEnumValue("1") Apple("1"),
#XmlEnumValue("2") Banner("2"),
#XmlEnumValue("") NULL("3");
MyEnum(String value, String description) {
this.value = value;
this.description = description;
}
private String value;
private String description;
}
so that I can set MyEnum.NULL to filed;

Categories

Resources