package org.adfemg.datacontrol.demo.servlet;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.adfemg.datacontrol.demo.persist.Department;
import org.adfemg.datacontrol.demo.persist.Employee;
import org.adfemg.datacontrol.demo.persist.Job;
import org.adfemg.datacontrol.demo.persist.Location;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ResetDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// delete all old data
ofy().delete().keys(ofy().load().type(Department.class).keys().list()).now();
ofy().delete().keys(ofy().load().type(Employee.class).keys().list()).now();
ofy().delete().keys(ofy().load().type(Job.class).keys().list()).now();
ofy().delete().keys(ofy().load().type(Location.class).keys().list()).now();
try {
// read data from XML and convert to persistent POJO's
List<Location> locs = locations(read(Location.class.getResourceAsStream("location.xml")));
ofy().save().entities(locs).now();
List<Job> jobs = jobs(read(Job.class.getResourceAsStream("job.xml")));
ofy().save().entities(jobs).now();
List<Map<String, String>> empData = read(Employee.class.getResourceAsStream("employee.xml"));
List<Employee> emps = employees(empData);
ofy().save().entities(emps).now();
List<Map<String, String>> deptData = read(Department.class.getResourceAsStream("department.xml"));
List<Department> depts = departments(deptData);
ofy().save().entities(depts).now();
// now add employees to departments
for (Map<String, String> row : empData) {
String empIdStr = row.get("EMPLOYEE_ID");
String deptIdStr = row.get("DEPARTMENT_ID");
if (deptIdStr.isEmpty()) {
continue;
}
long empId = Long.parseLong(empIdStr);
long deptId = Long.parseLong(deptIdStr);
Department dept = ofy().load().key(Key.create(Department.class, deptId)).now();
Employee emp = ofy().load().key(Key.create(Employee.class, empId)).now();
dept.addEmployee(emp);
}
ofy().save().entities(depts).now();
} catch (Exception e) {
throw new ServletException(e);
}
//Department d = new Department();
//d.setId(Long.valueOf(123));
//d.setName("MyDepartment");
//d.setLocation(location);
//d.setManager(manager);
//ofy().save().entity(d).now();
}
private List<Map<String, String>> read(InputStream stream) throws ParserConfigurationException, SAXException,
IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(stream);
List<Map<String, String>> retval = new ArrayList<Map<String, String>>();
Element results = doc.getDocumentElement();
NodeList rows = results.getChildNodes();
for (int iRow = 0 ; iRow < rows.getLength(); iRow++) {
Node row = rows.item(iRow);
if (row instanceof Element && "ROW".equals(row.getNodeName())) {
Map<String, String> r = new HashMap<String,String>();
NodeList columns = row.getChildNodes();
for (int iCol = 0 ; iCol < columns.getLength(); iCol++) {
Node column = columns.item(iCol);
if (column instanceof Element && "COLUMN".equals(column.getNodeName())) {
Element colElem = (Element)column;
r.put(colElem.getAttribute("NAME"), colElem.getTextContent());
}
}
retval.add(r);
}
}
return retval;
}
private List<Location> locations(List<Map<String, String>> values) {
List<Location> retval = new ArrayList<Location>(values.size());
for (Map<String,String> val : values) {
Location loc = new Location();
loc.setId(Long.valueOf(val.get("LOCATION_ID")));
loc.setStreetAddress(val.get("STREET_ADDRESS"));
loc.setPostalCode(val.get("POSTAL_CODE"));
loc.setCity(val.get("CITY"));
loc.setStateprovince(val.get("STATE_PROVINCE"));
loc.setCountry(val.get("COUNTRY_ID"));
retval.add(loc);
}
return retval;
}
private List<Job> jobs(List<Map<String, String>> values) {
List<Job> retval = new ArrayList<Job>(values.size());
for (Map<String,String> val : values) {
Job job = new Job();
job.setId(val.get("JOB_ID"));
job.setTitle(val.get("JOB_TITLE"));
job.setMinSalary(Double.parseDouble(val.get("MIN_SALARY")));
job.setMaxSalary(Double.parseDouble(val.get("MAX_SALARY")));
retval.add(job);
}
return retval;
}
private List<Employee> employees(List<Map<String, String>> values) throws ParseException {
List<Employee> retval = new ArrayList<Employee>(values.size());
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy");
for (Map<String,String> val : values) {
Employee emp = new Employee();
emp.setId(Long.valueOf(val.get("EMPLOYEE_ID")));
emp.setFirstName(val.get("FIRST_NAME"));
emp.setLastName(val.get("LAST_NAME"));
emp.setEmail(val.get("EMAIL"));
emp.setPhoneNumber(val.get("PHONE_NUMBER"));
emp.setHireDate(formatter.parse(val.get("HIRE_DATE")));
emp.setJob(ofy().load().key(Key.create(Job.class, val.get("JOB_ID"))).now());
emp.setSalary(Double.parseDouble(val.get("SALARY")));
String comm = val.get("COMMISSION_PCT").replace(",", ".");
emp.setCommissionPercentage(comm.isEmpty() ? null : Double.parseDouble(comm));
//emp.setManager(val.get("MANAGER_ID"));
//emp.setDepartment(val.get("DEPARTMENT_ID"));
retval.add(emp);
}
return retval;
}
private List<Department> departments(List<Map<String, String>> values) throws ParseException {
List<Department> retval = new ArrayList<Department>(values.size());
for (Map<String,String> val : values) {
Department dept = new Department();
dept.setId(Long.valueOf(val.get("DEPARTMENT_ID")));
dept.setName(val.get("DEPARTMENT_NAME"));
String mgr = val.get("MANAGER_ID");
dept.setManager(mgr.isEmpty() ? null : ofy().load().key(Key.create(Employee.class, Long.parseLong(val.get("MANAGER_ID")))).now());
dept.setLocation(ofy().load().key(Key.create(Location.class, Long.parseLong(val.get("LOCATION_ID")))).now());
retval.add(dept);
}
return retval;
}
static {
ObjectifyService.register(org.adfemg.datacontrol.demo.persist.Department.class);
ObjectifyService.register(org.adfemg.datacontrol.demo.persist.Employee.class);
ObjectifyService.register(org.adfemg.datacontrol.demo.persist.Job.class);
ObjectifyService.register(org.adfemg.datacontrol.demo.persist.Location.class);
}
}