Advertisement
Guest User

Untitled

a guest
May 26th, 2016
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package net.peopleway.invoicesystem.customer;
  2.  
  3. Customer
  4.  
  5. package net.peopleway.invoicesystem.customer;
  6.  
  7. import java.io.Serializable;
  8. import java.util.Date;
  9. import java.util.List;
  10.  
  11. import javax.persistence.CascadeType;
  12. import javax.persistence.Column;
  13. import javax.persistence.Entity;
  14. import javax.persistence.FetchType;
  15. import javax.persistence.GeneratedValue;
  16. import javax.persistence.Id;
  17. import javax.persistence.JoinColumn;
  18. import javax.persistence.ManyToOne;
  19. import javax.persistence.OneToMany;
  20. import javax.persistence.Table;
  21.  
  22. import net.peopleway.invoicesystem.subscription.Subscription;
  23. import net.peopleway.invoicesystem.user.User;
  24.  
  25. import org.hibernate.annotations.Fetch;
  26. import org.hibernate.annotations.LazyCollection;
  27. import org.hibernate.annotations.LazyCollectionOption;
  28.  
  29. @Entity
  30. @Table(name = "customer")
  31. public class Customer implements Serializable,Comparable<Customer>{
  32.     private static final long serialVersionUID = -1111803252737409312L;
  33.     private List<Subscription> subscriptions;
  34.     private User user;
  35.  
  36.     private Date creationDate;
  37.  
  38.     private String mailaddress, phonenumber, EANnumber, name, contactPerson,
  39.             currency, departmentName, addressCustomer, country, zipcode;
  40.  
  41.     private int customer_id, testserver;
  42.  
  43.     private boolean active;
  44.    
  45.    
  46.  
  47.     public Customer(int customer_id , User user,
  48.             Date creationDate, String mailaddress, String phonenumber,
  49.             String EANnumber, String name, String contactPerson,
  50.             String currency, String departmentName, String addressCustomer,
  51.             String country, String zipcode, boolean active) {
  52.         this.customer_id = customer_id;
  53.         this.user = user;
  54.         this.creationDate = creationDate;
  55.         this.mailaddress = mailaddress;
  56.         this.phonenumber = phonenumber;
  57.         this.EANnumber = EANnumber;
  58.         this.name = name;  
  59.         this.contactPerson = contactPerson;
  60.         this.currency = currency;
  61.         this.departmentName = departmentName;
  62.         this.addressCustomer = addressCustomer;
  63.         this.country = country;
  64.         this.zipcode = zipcode;
  65.         this.active = active;
  66.     }
  67.    
  68.     public Customer() {
  69.     }
  70.  
  71.     @Id
  72.     @GeneratedValue
  73.     @Column
  74.     public int getCustomer_id() {
  75.         return customer_id;
  76.     }
  77.  
  78.  
  79.  
  80.     public void setCustomer_id(int customer_id) {
  81.         this.customer_id = customer_id;
  82.     }
  83.  
  84.  
  85.     @LazyCollection(LazyCollectionOption.FALSE)
  86.     @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", orphanRemoval=true)
  87.     public List<Subscription> getSubscriptions() {
  88.         return subscriptions;
  89.     }
  90.  
  91.     public void setSubscriptions(List<Subscription> subscriptions) {
  92.         this.subscriptions = subscriptions;
  93.     }
  94.    
  95.     @LazyCollection(LazyCollectionOption.FALSE)
  96.     @ManyToOne(optional = false)
  97.     @JoinColumn(name = "user_id")
  98.     public User getUser() {
  99.         return user;
  100.     }
  101.  
  102.     public void setUser(User user) {
  103.         this.user = user;
  104.     }
  105.    
  106.     @Column
  107.     public Date getCreationDate() {
  108.         return creationDate;
  109.     }
  110.  
  111.     public void setCreationDate(Date creationDate) {
  112.         this.creationDate = creationDate;
  113.     }
  114.  
  115.     @Column
  116.     public String getMailaddress() {
  117.         return mailaddress;
  118.     }
  119.  
  120.     public void setMailaddress(String mailaddress) {
  121.         this.mailaddress = mailaddress;
  122.     }
  123.  
  124.     @Column
  125.     public String getPhonenumber() {
  126.         return phonenumber;
  127.     }
  128.  
  129.     public void setPhonenumber(String phoneNumber) {
  130.         this.phonenumber = phoneNumber;
  131.     }
  132.  
  133.     @Column
  134.     public String getEANnumber() {
  135.         return EANnumber;
  136.     }
  137.  
  138.     public void setEANnumber(String EANnumber) {
  139.         this.EANnumber = EANnumber;
  140.     }
  141.  
  142.     @Column
  143.     public String getName() {
  144.         return name;
  145.     }
  146.  
  147.     public void setName(String name) {
  148.         this.name = name;
  149.     }
  150.  
  151.     @Column
  152.     public String getContactPerson() {
  153.         return contactPerson;
  154.     }
  155.  
  156.     public void setContactPerson(String contactPerson) {
  157.         this.contactPerson = contactPerson;
  158.     }
  159.  
  160.     @Column
  161.     public String getCurrency() {
  162.         return currency;
  163.     }
  164.  
  165.     public void setCurrency(String currency) {
  166.         this.currency = currency;
  167.     }
  168.  
  169.     @Column
  170.     public String getDepartmentName() {
  171.         return departmentName;
  172.     }
  173.  
  174.     public void setDepartmentName(String departmentName) {
  175.         this.departmentName = departmentName;
  176.     }
  177.  
  178.     @Column
  179.     public String getAddressCustomer() {
  180.         return addressCustomer;
  181.     }
  182.  
  183.     public void setAddressCustomer(String addressCustomer) {
  184.         this.addressCustomer = addressCustomer;
  185.     }
  186.  
  187.     @Column
  188.     public String getCountry() {
  189.         return country;
  190.     }
  191.  
  192.     public void setCountry(String country) {
  193.         this.country = country;
  194.     }
  195.  
  196.     @Column
  197.     public String getZipcode() {
  198.         return zipcode;
  199.     }
  200.  
  201.     public void setZipcode(String zipcode) {
  202.         this.zipcode = zipcode;
  203.     }
  204.  
  205.     @Column
  206.     public boolean isActive() {
  207.         return active;
  208.     }
  209.  
  210.     public void setActive(boolean active) {
  211.         this.active = active;
  212.     }
  213.     public int compareTo(Customer c){
  214.         return this.name.compareTo(c.name);
  215.     }
  216.     @Override
  217.     public boolean equals(Object obj) {
  218.         if (this == obj)
  219.             return true;
  220.         if (obj == null)
  221.             return false;
  222.         if (getClass() != obj.getClass())
  223.             return false;
  224.         Customer other = (Customer) obj;
  225.         if (customer_id != other.customer_id)
  226.             return false;
  227.         return true;
  228.     }
  229.     @Override
  230.     public int hashCode() {
  231.         return super.hashCode();
  232.     }
  233.     @Override
  234.     public String toString() {
  235.         String str = name;
  236.         String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
  237.         return cap;
  238.     }
  239.  
  240.     @Column
  241.     public int getTestserver() {
  242.         return testserver;
  243.     }
  244.  
  245.     public void setTestserver(int testserver) {
  246.         this.testserver = testserver;
  247.     }
  248.    
  249.    
  250. }
  251.  
  252.  
  253. CustomerConverter
  254.  
  255. package net.peopleway.invoicesystem.customer;
  256.  
  257. import java.sql.SQLException;
  258.  
  259. import javax.enterprise.context.ApplicationScoped;
  260. import javax.faces.application.FacesMessage;
  261. import javax.faces.component.UIComponent;
  262. import javax.faces.context.FacesContext;
  263. import javax.faces.convert.Converter;
  264. import javax.faces.convert.ConverterException;
  265. import javax.inject.Inject;
  266. import javax.inject.Named;
  267.  
  268. import org.apache.commons.lang.StringUtils;
  269.  
  270. @Named
  271. @ApplicationScoped
  272. public class CustomerConverter implements Converter {
  273.  
  274.     @Inject
  275.     private CustomerService ss;
  276.  
  277.     @Override
  278.     public Object getAsObject(FacesContext context, UIComponent component, String value) {
  279.         if(StringUtils.isBlank(value)){
  280.             return null;
  281.         }
  282.         try {
  283.             int id = Integer.parseInt(value);
  284.             for (Customer c : ss.getCustomers()) {
  285.                 if (c.getCustomer_id() == id) {
  286.                     return c;
  287.                 }
  288.             }
  289.             return null;
  290.         } catch (NumberFormatException | ClassNotFoundException | SQLException e) {
  291.             throw new ConverterException(new FacesMessage("Could not convert to customer"));
  292.         }
  293.     }
  294.  
  295.     @Override
  296.     public String getAsString(FacesContext context, UIComponent component, Object value) {
  297.         if (value == null)
  298.             return "";
  299.  
  300.         return Integer.toString(((Customer) value).getCustomer_id());
  301.     }
  302.  
  303. }
  304.  
  305. CustomerDao
  306.  
  307. package net.peopleway.invoicesystem.customer;
  308.  
  309. import java.io.Serializable;
  310.  
  311. import java.sql.ResultSet;
  312. import java.sql.SQLException;
  313. import java.sql.Timestamp;
  314. import java.util.ArrayList;
  315. import java.util.Date;
  316. import java.util.List;
  317.  
  318. import javax.enterprise.context.ApplicationScoped;
  319. import javax.inject.Inject;
  320. import javax.inject.Named;
  321.  
  322. import org.hibernate.Criteria;
  323. import org.hibernate.Hibernate;
  324. import org.hibernate.Query;
  325. import org.hibernate.Session;
  326. import org.hibernate.Transaction;
  327. import org.hibernate.criterion.Restrictions;
  328.  
  329. import net.peopleway.invoicesystem.dbproperties.DatabaseConnectionPraktik2016;
  330. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  331. import net.peopleway.invoicesystem.invoice.InvoiceInterval;
  332. import net.peopleway.invoicesystem.product.Product;
  333. import net.peopleway.invoicesystem.subscription.State;
  334. import net.peopleway.invoicesystem.subscription.Subscription;
  335. import net.peopleway.invoicesystem.subscription.SubscriptionDao;
  336. import net.peopleway.invoicesystem.user.User;
  337. import net.peopleway.invoicesystem.user.UserDao;
  338. import net.peopleway.invoicesystem.user.UserService;
  339.  
  340.  
  341. @Named
  342. @ApplicationScoped
  343. public class CustomerDao implements Serializable {
  344.    
  345.     @Inject DatabaseConnectionPraktik2016 db = new DatabaseConnectionPraktik2016();
  346.     @Inject SubscriptionDao subdb;
  347.    
  348.     public void saveCustomer(Customer c){
  349.         Session session = DatabaseSessionFactory.getSession();
  350.         Transaction t = session.beginTransaction();
  351.         session.save(c);
  352.         t.commit();
  353.     }
  354.     public void updateCustomer(Customer c){
  355.         Session session = DatabaseSessionFactory.getSession();
  356.         Transaction t = session.beginTransaction();
  357.         session.update(c);
  358.         t.commit();
  359.     }
  360.    
  361.     public Customer getCustomerById(int id){
  362.         Session session = DatabaseSessionFactory.getSession();
  363.         Transaction t = session.getTransaction();
  364.         session.beginTransaction();
  365.         Criteria criteria = session.createCriteria(Customer.class);
  366.         criteria.add(Restrictions.eq("customer_id", id));
  367.         Customer s = (Customer) criteria.uniqueResult();
  368.         t.commit();
  369.         return s;
  370.     }
  371.    
  372.     public void createCustomer(User user,
  373.             Date creationDate, String mailAddress, String phoneNumber,
  374.             String eANNumber, String name, String contactPerson,
  375.             String currency, String departmentName, String address,
  376.             String country, int district) throws ClassNotFoundException, SQLException{
  377.        
  378.         if(eANNumber == null || eANNumber == ""){
  379.             eANNumber = "null";
  380.         }
  381.         Timestamp ts_now = new Timestamp(creationDate.getTime());
  382.         db.open();
  383.         db.executeUpdate("insert into Customer values(?,?,?,?,?,?,?,?,?,?,?,?,?)", ts_now+"",
  384.                 mailAddress, phoneNumber+"", eANNumber+"", "true", name, contactPerson, currency, departmentName, address,
  385.                 district+"", country, user.getUser_id()+"");
  386.        
  387.     }
  388.     public List<Customer> getCustomersUser(User u){
  389.         Session session = DatabaseSessionFactory.getSession();
  390.         Transaction t = session.beginTransaction();
  391.         Criteria c = session.createCriteria(User.class);
  392.         c.add(Restrictions.idEq(u.getUser_id()));
  393.         u = (User) c.uniqueResult();
  394.         Hibernate.initialize(u.getCustomers());
  395.         t.commit();
  396.         return u.getCustomers();
  397.     }
  398.    
  399.     public List<Customer> getCustomers() throws SQLException, ClassNotFoundException{
  400.         List<Customer> l = new ArrayList<Customer>();
  401.         ResultSet rs = null;
  402.         db.open();
  403.         db.prepare("select customer_id, creationdate, mailaddress, phonenumber, EANNumber, active, name, contactPerson, currency, departmentname, addresscustomer, zipcode, country, user_id from customer");
  404.         rs = db.execute();
  405.         while(rs.next()){
  406.             Customer c = new Customer(rs.getInt("customer_id") ,getUserById(rs.getInt("user_id")), rs.getDate("creationDate"), rs.getString("mailAddress"), rs.getString("phonenumber"), rs.getString("EANNumber"), rs.getString("name"), rs.getString("contactPerson"), rs.getString("currency"), rs.getString("departmentname"), rs.getString("addresscustomer"), rs.getString("country"), rs.getString("zipcode"), rs.getBoolean("active"));
  407.             l.add(c);
  408.         }
  409.         return l;
  410.     }
  411.     public void deleteById(Class<Customer> customer, Serializable id) {
  412.        
  413.         Session session = DatabaseSessionFactory.getSession();
  414.         Transaction t = session.beginTransaction();
  415.         Object persistentInstance = session.load(customer, id);
  416.         if (persistentInstance != null) {
  417.             session.delete(persistentInstance);
  418.         }
  419.         t.commit();
  420.     }
  421.    
  422.     public void deleteCustomer(Customer c){
  423.         Session session = DatabaseSessionFactory.getSession();
  424.         Transaction t = session.beginTransaction();
  425.         session.delete(c);
  426.         t.commit();
  427.     }
  428.     public void changeStateCustomer(Customer c){
  429.         Session session = DatabaseSessionFactory.getSession();
  430.         Transaction t = session.beginTransaction();
  431.         session.update(c);
  432.         t.commit();
  433.     }
  434.    
  435.     public  List<User> getUsers() throws SQLException, ClassNotFoundException{
  436.         List<User> l = new ArrayList<User>();
  437.         ResultSet rs = null;
  438.         db.open();
  439.         db.prepare("Select user_id, username, pass, name, administrator, accountant from Users");
  440.         rs = db.execute();
  441.         while(rs.next()){
  442.             User u = new User(rs.getString("username"), rs.getString("pass"), rs.getString("name"),
  443.                     rs.getInt("user_id"), rs.getBoolean("administrator"), rs.getBoolean("accountant"));
  444.             l.add(u);
  445.         }
  446.         return l;
  447.     }
  448.     public User getUserById(int j) throws ClassNotFoundException, SQLException{
  449.         for(int i = 0; i < getUsers().size(); i++){
  450.             if(getUsers().get(i).getUser_id() == j){
  451.                 return getUsers().get(i);
  452.             }
  453.         }
  454.         return null;
  455.     }
  456.     public void saveOrUpdateCustomer(Customer c){
  457.         Session session = DatabaseSessionFactory.getSession();
  458.         Transaction t = session.beginTransaction();
  459.         session.saveOrUpdate(c);
  460.         t.commit();
  461.     }
  462.    
  463.     public List<Subscription> getSubs(Customer c){
  464.         Session session = DatabaseSessionFactory.getSession();
  465.         Transaction t = session.beginTransaction();
  466.         Criteria u = session.createCriteria(Customer.class);
  467.         u.add(Restrictions.idEq(c.getCustomer_id()));
  468.         // The object we are interested in
  469.         c = (Customer) u.uniqueResult();
  470.         // Important to use to get the objects with hibernate
  471.         Hibernate.initialize(c.getSubscriptions());
  472.         // Any reference to another object in the subscriptions objects other than customer is a Hibernate references so if needed
  473.         // use Hibernate.initialize on them also.
  474.         t.commit();
  475.         return c.getSubscriptions();
  476.     }
  477. }
  478.  
  479. CustomerManagementBean
  480.  
  481. package net.peopleway.invoicesystem.customer;
  482.  
  483. import java.io.IOException;
  484. import java.io.Serializable;
  485. import java.sql.SQLException;
  486. import java.util.ArrayList;
  487. import java.util.Date;
  488. import java.util.List;
  489.  
  490. import javax.annotation.PostConstruct;
  491. import javax.enterprise.context.spi.CreationalContext;
  492. import javax.faces.application.FacesMessage;
  493. import javax.faces.context.FacesContext;
  494. import javax.faces.view.ViewScoped;
  495. import javax.inject.Inject;
  496. import javax.inject.Named;
  497.  
  498. import org.omnifaces.util.Faces;
  499.  
  500. import net.peopleway.invoicesystem.login.UserManager;
  501. import net.peopleway.invoicesystem.subscription.Subscription;
  502. import net.peopleway.invoicesystem.subscription.SubscriptionService;
  503. import net.peopleway.invoicesystem.user.UserService;
  504.  
  505.  
  506. @Named
  507. @ViewScoped
  508. public class CustomerManagementBean implements Serializable{
  509.  
  510.     private String name;
  511.     private String contactPerson;
  512.     private String mailAddress;
  513.     private String departmentName;
  514.     private String addressCustomer;
  515.     private String country;
  516.     private String zipcode;
  517.     private String EAN;
  518.     private String phonenumber;
  519.     private String currency;
  520.     private int testserver;
  521.     private Integer expectedParticipants;
  522.     private Integer employees;
  523.     private boolean active;
  524.     private boolean editing;
  525.     private Customer selectedCustomer;
  526.     private List<Customer> customers;
  527.     private Date creationDate;
  528.    
  529.     @Inject CustomerService cs;
  530.     @Inject UserManager userManager;
  531.     @Inject SubscriptionService ss;
  532.     @Inject UserService us;
  533.    
  534.     public void customerlistener(){
  535.         if(selectedCustomer != null){
  536.             addressCustomer = selectedCustomer.getAddressCustomer();
  537.             contactPerson = selectedCustomer.getContactPerson();
  538.             country = selectedCustomer.getCountry();
  539.             creationDate = selectedCustomer.getCreationDate();
  540.             departmentName = selectedCustomer.getDepartmentName();
  541.             mailAddress = selectedCustomer.getMailaddress();
  542.             EAN = selectedCustomer.getEANnumber();
  543.             name = selectedCustomer.getName();
  544.             phonenumber = selectedCustomer.getPhonenumber();
  545.             zipcode = selectedCustomer.getZipcode();
  546.             currency = selectedCustomer.getCurrency();
  547.             active = selectedCustomer.isActive();
  548.             editing = true;
  549.         }else{
  550.             editing = false;
  551.         }
  552.     }
  553.     public void back() throws IOException{
  554.         Faces.redirect("customers");
  555.     }
  556.    
  557.     public String createNewCustomer() throws Exception{
  558.         Customer c = null;
  559.         if(selectedCustomer != null){
  560.             c = selectedCustomer;
  561.         }else{
  562.             c = new Customer();
  563.         }
  564.         c.setAddressCustomer(addressCustomer);
  565.         c.setContactPerson(contactPerson);
  566.         c.setCountry(country);
  567.         c.setCreationDate(new Date());
  568.         c.setDepartmentName(departmentName);
  569.         c.setMailaddress(mailAddress);
  570.         c.setEANnumber(EAN);
  571.         c.setName(name);
  572.         c.setPhonenumber(phonenumber);
  573.         c.setSubscriptions(new ArrayList<Subscription>());
  574.         c.setZipcode(zipcode);
  575.         c.setCurrency("depends on country");
  576.         c.setActive(false);
  577.         c.setUser(us.getUserById(userManager.getUser().getUser_id()));
  578.         if(editing){
  579.             cs.updateCustomer(c);
  580.             return null;
  581.         }
  582.         else{
  583.             cs.saveCustomer(c);
  584.             return "customers.xhtml?faces-redirect=true";
  585.         }
  586.     }
  587.     public String deleteCustomer() throws ClassNotFoundException, SQLException{
  588.         try {
  589.             cs.deleteCustomer(selectedCustomer);
  590.             return "customers.xhtml?faces-redirect=true";
  591.         } catch (Exception e) {
  592.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  593.         }
  594.         return null;
  595.     }
  596.    
  597.     public int getExpectedParticipants() {
  598.         return expectedParticipants;
  599.     }
  600.     public void setExpectedParticipants(int expectedParticipants) {
  601.         this.expectedParticipants = expectedParticipants;
  602.     }
  603.     public int getEmployees() {
  604.         return employees;
  605.     }
  606.     public void setEmployees(int employees) {
  607.         this.employees = employees;
  608.     }
  609.     public String getCurrency() {
  610.         return currency;
  611.     }
  612.  
  613.     public void setCurrency(String currency) {
  614.         this.currency = currency;
  615.     }
  616.  
  617.     public boolean isActive() {
  618.         return active;
  619.     }
  620.  
  621.     public void setActive(boolean active) {
  622.         this.active = active;
  623.     }
  624.  
  625.     public Date getCreationDate() {
  626.         return creationDate;
  627.     }
  628.  
  629.     public void setCreationDate(Date creationDate) {
  630.         this.creationDate = creationDate;
  631.     }
  632.  
  633.     public Customer getSelectedCustomer() {
  634.         return selectedCustomer;
  635.     }
  636.     public void setSelectedCustomer(Customer selectedCustomer) {
  637.         this.selectedCustomer = selectedCustomer;
  638.     }
  639.     public List<Customer> getCustomers() {
  640.         return customers;
  641.     }
  642.     public void setCustomers(List<Customer> customers) {
  643.         this.customers = customers;
  644.     }
  645.     public String getName() {
  646.         return name;
  647.     }
  648.     public void setName(String name) {
  649.         this.name = name;
  650.     }
  651.     public String getContactPerson() {
  652.         return contactPerson;
  653.     }
  654.     public void setContactPerson(String contactPerson) {
  655.         this.contactPerson = contactPerson;
  656.     }
  657.     public String getMailAddress() {
  658.         return mailAddress;
  659.     }
  660.     public void setMailAddress(String mailAddress) {
  661.         this.mailAddress = mailAddress;
  662.     }
  663.     public String getDepartmentName() {
  664.         return departmentName;
  665.     }
  666.     public void setDepartmentName(String departmentName) {
  667.         this.departmentName = departmentName;
  668.     }
  669.     public String getAddressCustomer() {
  670.         return addressCustomer;
  671.     }
  672.     public void setAddressCustomer(String addressCustomer) {
  673.         this.addressCustomer = addressCustomer;
  674.     }
  675.     public String getCountry() {
  676.         return country;
  677.     }
  678.     public void setCountry(String country) {
  679.         this.country = country;
  680.     }
  681.     public String getZipcode() {
  682.         return zipcode;
  683.     }
  684.     public void setZipcode(String zipcode) {
  685.         this.zipcode = zipcode;
  686.     }
  687.     public String getEAN() {
  688.         return EAN;
  689.     }
  690.     public void setEAN(String eAN) {
  691.         EAN = eAN;
  692.     }
  693.     public String getPhonenumber() {
  694.         return phonenumber;
  695.     }
  696.     public void setPhonenumber(String phonenumber) {
  697.         this.phonenumber = phonenumber;
  698.     }
  699.     public boolean isEditing() {
  700.         return editing;
  701.     }
  702.     public void setEditing(boolean editing) {
  703.         this.editing = editing;
  704.     }
  705. }
  706.  
  707. CustomerBean
  708.  
  709. package net.peopleway.invoicesystem.customer;
  710.  
  711. import java.io.Serializable;
  712. import java.util.List;
  713.  
  714. import javax.annotation.PostConstruct;
  715. import javax.faces.application.FacesMessage;
  716. import javax.faces.context.FacesContext;
  717. import javax.faces.view.ViewScoped;
  718. import javax.inject.Inject;
  719. import javax.inject.Named;
  720.  
  721. import com.sun.faces.config.processor.FacesConfigExtensionProcessor;
  722.  
  723. import net.peopleway.invoicesystem.login.UserManager;
  724. import net.peopleway.invoicesystem.subscription.Subscription;
  725. import net.peopleway.invoicesystem.subscription.SubscriptionService;
  726. import net.peopleway.invoicesystem.user.UserService;
  727.  
  728.  
  729. @Named
  730. @ViewScoped
  731. public class CustomersBean implements Serializable{
  732.  
  733.     private static final long serialVersionUID = -5892408888372620597L;
  734.     @Inject private UserManager userManager;
  735.     @Inject private SubscriptionService ss;
  736.     @Inject private CustomerService cs;
  737.     @Inject private UserService us;
  738.     private List<Customer> customers;
  739.     private List<Subscription> subscriptions;
  740.     private List<Subscription> activeSubscription;
  741.     private Customer selectedCustomer;
  742.     private int subId;
  743.     private int subToStart;
  744.     private int subToEnd;
  745.    
  746.     public String edit(){
  747.         try{
  748.             if(selectedCustomer == null){
  749.                 throw new Exception("You have no customers");
  750.             }
  751.             return "customer.xhtml?faces-redirect=true&id=" + selectedCustomer.getCustomer_id();
  752.         }catch(Exception e){
  753.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  754.         }
  755.         return null;
  756.     }
  757.    
  758.     public String newSub(){
  759.         try{
  760.             if(selectedCustomer == null){
  761.                 throw new Exception("You have no customers");
  762.             }
  763.             return "subscription.xhtml?faces-redirect=true&customerId=" + selectedCustomer.getCustomer_id();
  764.         }catch(Exception e){
  765.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  766.         }
  767.         return null;
  768.     }
  769.    
  770.     public void updateSubList(){
  771.         subscriptions = ss.getCustSubs(selectedCustomer);
  772.     }
  773.     public void deleteSub(){
  774.         try{
  775.             ss.deleteSubscription(ss.getSubscriptionById(subId));
  776.         }catch(Exception e){
  777.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  778.         }
  779.         subscriptions = ss.getCustSubs(selectedCustomer);
  780.     }
  781.     public void startSub() throws Exception{
  782.         try{
  783.             ss.startSub(ss.getSubscriptionById(subToStart));
  784.             updateSubList();
  785.         }catch(Exception e){
  786.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  787.         }
  788.     }
  789.     public void endSub(){
  790.         try{
  791.             ss.stopSub(ss.getSubscriptionById(subToEnd));
  792.             updateSubList();
  793.         }
  794.         catch(Exception e){
  795.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  796.         }
  797.     }
  798.  
  799.     public int getSubToEnd() {
  800.         return subToEnd;
  801.     }
  802.  
  803.     public void setSubToEnd(int subToEnd) {
  804.         this.subToEnd = subToEnd;
  805.     }
  806.  
  807.     public int getSubToStart() {
  808.         return subToStart;
  809.     }
  810.  
  811.     public void setSubToStart(int subToStart) {
  812.         this.subToStart = subToStart;
  813.     }
  814.  
  815.     public int getSubId() {
  816.         return subId;
  817.     }
  818.     public void setSubId(int subId) {
  819.         this.subId = subId;
  820.     }
  821.     public Customer getSelectedCustomer() {
  822.         return selectedCustomer;
  823.     }
  824.  
  825.     public void setSelectedCustomer(Customer selectedCustomer) {
  826.         this.selectedCustomer = selectedCustomer;
  827.     }
  828.  
  829.     public List<Customer> getCustomers() {
  830.         return customers;
  831.     }
  832.     public void setCustomers(List<Customer> customers) {
  833.         this.customers = customers;
  834.     }
  835.     public List<Subscription> getSubscriptions() {
  836.         return subscriptions;
  837.     }
  838.     public void setSubscriptions(List<Subscription> subscriptions) {
  839.         this.subscriptions = subscriptions;
  840.     }
  841.     public List<Subscription> getActiveSubscription() {
  842.         return activeSubscription;
  843.     }
  844.     public void setActiveSubscription(List<Subscription> activeSubscription) {
  845.         this.activeSubscription = activeSubscription;
  846.     }
  847.    
  848.     @PostConstruct
  849.     public void initialize(){
  850.         customers = cs.getCustomersUser(userManager.getUser());
  851.         if(customers.size()>0){
  852.             selectedCustomer = customers.get(0);
  853.             subscriptions = ss.getCustSubs(selectedCustomer);
  854.         }
  855.     }
  856.    
  857.    
  858. }
  859.    
  860. CustomerService
  861.  
  862. package net.peopleway.invoicesystem.customer;
  863.  
  864. import java.io.Serializable;
  865. import java.sql.SQLException;
  866. import java.util.Date;
  867. import java.util.List;
  868.  
  869. import javax.enterprise.context.ApplicationScoped;
  870. import javax.inject.Inject;
  871. import javax.inject.Named;
  872.  
  873. import net.peopleway.invoicesystem.subscription.Subscription;
  874. import net.peopleway.invoicesystem.user.User;
  875.  
  876. @Named
  877. @ApplicationScoped
  878. public class CustomerService implements Serializable {
  879.  
  880.     @Inject
  881.     static CustomerDao db = new CustomerDao();
  882.    
  883.     public Customer getCustomerById(int id){
  884.         return db.getCustomerById(id);
  885.     }
  886.     public void saveorUpdateCustomer(Customer c){
  887.         db.saveOrUpdateCustomer(c);
  888.     }
  889.     public void saveCustomer(Customer c) throws Exception{
  890.         try{
  891.             if(c.getName().isEmpty() || c.getAddressCustomer().isEmpty() || c.getContactPerson().isEmpty() || c.getCountry().isEmpty() || c.getCurrency().isEmpty() || c.getDepartmentName().isEmpty() || c.getPhonenumber().isEmpty() || c.getZipcode().isEmpty()){
  892.                 throw new Exception();
  893.             }else{
  894.                 db.saveCustomer(c);
  895.             }
  896.         }catch(Exception e){
  897.             throw new Exception("Name, Address, Contact person, Country, Currency, Department, Phone number and Zipcode must be filled");
  898.         }
  899.        
  900.     }
  901.     public void updateCustomer(Customer c) throws Exception{
  902.         try{
  903.             if(c.getName().isEmpty() || c.getAddressCustomer().isEmpty() || c.getContactPerson().isEmpty() || c.getCountry().isEmpty() || c.getCurrency().isEmpty() || c.getDepartmentName().isEmpty() || c.getPhonenumber().isEmpty() || c.getZipcode().isEmpty()){
  904.                 throw new Exception();
  905.             }
  906.             else{
  907.                 db.updateCustomer(c);
  908.             }
  909.         }catch(Exception e){
  910.             throw new Exception("Name, Address, Contact person, Country, Currency, Department, Phone number and Zipcode must be filled");
  911.         }
  912.     }
  913.    
  914.     public void changeStateCustomer(Customer c){
  915.         db.changeStateCustomer(c);
  916.     }
  917.     public void deletebyid(Class<Customer> customer, Serializable id){
  918.         db.deleteById(customer, id);
  919.     }
  920.     public void createCustomer(User user,
  921.             Date creationDate, String mailAddress, String phoneNumber,
  922.             String eANNumber, String name, String contactPerson,
  923.             String currency, String departmentName, String address,
  924.             String country, int district) throws ClassNotFoundException, SQLException{
  925.        
  926.         db.createCustomer(user, creationDate, mailAddress, phoneNumber, eANNumber, name, contactPerson, currency, departmentName, address, country, district);
  927.     }
  928.    
  929.     public List<Customer> getCustomersUser(User u){
  930.         return db.getCustomersUser(u);
  931.     }
  932.    
  933.     public void deleteCustomer(Customer c) throws Exception{
  934.         try{
  935.             if(c.isActive()){
  936.                 throw new Exception();
  937.             }else{
  938.                 db.deleteCustomer(c);
  939.             }
  940.         }catch(Exception e){
  941.             throw new Exception("Cannot delete a customer with subscriptions not in progress");
  942.         }
  943.     }
  944.    
  945.     public List<Subscription> getSubscriptions(Customer c) throws ClassNotFoundException, SQLException{
  946.         return db.getSubs(c);
  947.     }
  948.    
  949.    
  950.     public List<Customer> getCustomers() throws ClassNotFoundException, SQLException{
  951.         return db.getCustomers();
  952.     }
  953.    
  954. }
  955.  
  956. package net.peopleway.invoicesystem.dbproperties;
  957.  
  958. DatabaseConnection
  959.  
  960. package net.peopleway.invoicesystem.dbproperties;
  961.  
  962. import java.sql.Connection;
  963. import java.sql.DriverManager;
  964. import java.sql.PreparedStatement;
  965. import java.sql.ResultSet;
  966. import java.sql.ResultSetMetaData;
  967. import java.sql.SQLException;
  968. import java.sql.Statement;
  969. import java.sql.Timestamp;
  970. import java.util.ArrayList;
  971. import java.util.Date;
  972. import java.util.List;
  973.  
  974. import javax.enterprise.context.ApplicationScoped;
  975. import javax.inject.Named;
  976. import javax.transaction.Transaction;
  977.  
  978.  
  979. @Named
  980. @ApplicationScoped
  981. public class DatabaseConnection {
  982.  
  983.     private Connection connection;
  984.     private PreparedStatement prepared;
  985.     private ThreadLocal<Transaction> currentTransaction;
  986.  
  987.     public Connection getConnection() {
  988.         return connection;
  989.     }
  990.  
  991.     public Connection open() throws SQLException {
  992.        
  993.         if (connection == null || connection.isClosed()) {
  994.             connection = DriverManager.getConnection(DatabaseProperties.getConnectionString());
  995.             connection.setAutoCommit(true);
  996.         }
  997.  
  998.         return connection;
  999.     }
  1000.    
  1001.     public PreparedStatement prepare(String sql, String... params) throws SQLException {
  1002.         prepared = connection.prepareStatement(sql);
  1003.         for(int i = 0; i < params.length; i++) {
  1004.             prepared.setString(i + 1, params[i]);
  1005.         }
  1006.        
  1007.         return prepared;
  1008.     }
  1009.    
  1010.     public ResultSet execute() throws SQLException {
  1011.         return prepared.executeQuery();
  1012.     }
  1013.    
  1014.     public void update() throws SQLException {
  1015.         prepared.executeUpdate();
  1016.     }
  1017.  
  1018.     public void close() throws SQLException {
  1019.         if (connection != null) {
  1020.             connection.close();
  1021.         }
  1022.     }
  1023.  
  1024.     public Integer executeUpdate(String sql, Object... parameters) {
  1025.         return executeUpdate(sql, toParameterList(parameters));
  1026.     }
  1027.  
  1028.     public Integer executeUpdate(String sql, List<Object> parameters) {
  1029.         Integer key = null;
  1030.         try {
  1031.             open();
  1032.             PreparedStatement statement = connection.prepareStatement(sql);
  1033.             setParameters(statement, parameters);
  1034.             statement.executeUpdate();
  1035.             statement.close();
  1036.             if (sql.trim().toUpperCase().startsWith("INSERT")) {
  1037.                 Statement keyStatement = connection.createStatement();
  1038.                 ResultSet generatedKeys = keyStatement.executeQuery("SELECT last_insert_rowid()");
  1039.                 if (generatedKeys.next()) {
  1040.                     key = generatedKeys.getInt(1);
  1041.                 }
  1042.             }
  1043.             close();
  1044.         }
  1045.  
  1046.         catch (SQLException ex) {
  1047.             ex.printStackTrace();
  1048.         }
  1049.  
  1050.         return key;
  1051.     }
  1052.  
  1053.     public List<Object[]> query(String sql, Object... parameters) {
  1054.         return query(sql, toParameterList(parameters));
  1055.     }
  1056.  
  1057.     private List<Object> toParameterList(Object[] parameters) {
  1058.         List<Object> parameterList = new ArrayList<>();
  1059.         if (parameters != null && parameters.length > 0) {
  1060.             for (int i = 0; i < parameters.length; i++) {
  1061.                 parameterList.add(parameters[i]);
  1062.             }
  1063.         }
  1064.  
  1065.         return parameterList;
  1066.     }
  1067.  
  1068.     public List<Object[]> query(String sql, List<Object> parameters) {
  1069.         List<Object[]> listResult = new ArrayList<>();
  1070.         try {
  1071.             open();
  1072.             PreparedStatement statement = connection.prepareStatement(sql);
  1073.             setParameters(statement, parameters);
  1074.             ResultSet result = statement.executeQuery();
  1075.             listResult = transform(result);
  1076.             result.close();
  1077.             statement.close();
  1078.             close();
  1079.         }
  1080.  
  1081.         catch (SQLException ex) {
  1082.             ex.printStackTrace();
  1083.         }
  1084.  
  1085.         return listResult;
  1086.     }
  1087.  
  1088.     private void setParameters(PreparedStatement statement, List<Object> parameters) throws SQLException {
  1089.         if (parameters != null && !parameters.isEmpty()) {
  1090.             int i = 1;
  1091.             for (Object parameter : parameters) {
  1092.                 if (parameter instanceof Integer) {
  1093.                     statement.setInt(i++, (Integer) parameter);
  1094.                 }
  1095.                 else if (parameter instanceof Long) {
  1096.                     statement.setLong(i++, (Long) parameter);
  1097.                 }
  1098.                 else if (parameter instanceof Double) {
  1099.                     statement.setDouble(i++, (Double) parameter);
  1100.                 }
  1101.                 else if (parameter instanceof Float) {
  1102.                     statement.setFloat(i++, (Float) parameter);
  1103.                 }
  1104.                 else if (parameter instanceof Date) {
  1105.                     statement.setTimestamp(i++, new Timestamp(((Date) parameter).getTime()));
  1106.                 }
  1107.                 else {
  1108.                     statement.setString(i++, (String) parameter);
  1109.                 }
  1110.             }
  1111.         }
  1112.     }
  1113.  
  1114.     private List<Object[]> transform(ResultSet result) throws SQLException {
  1115.         List<Object[]> listResult = new ArrayList<>();
  1116.         ResultSetMetaData meta = result.getMetaData();
  1117.         int columnCount = meta.getColumnCount();
  1118.         while (result.next()) {
  1119.             Object[] data = new Object[columnCount];
  1120.             for (int i = 0; i < columnCount; i++) {
  1121.                 data[i] = result.getObject(i + 1);
  1122.             }
  1123.             listResult.add(data);
  1124.         }
  1125.  
  1126.         return listResult;
  1127.     }
  1128. }
  1129.  
  1130. DatabaseConnectionPraktik2016
  1131.  
  1132. package net.peopleway.invoicesystem.dbproperties;
  1133.  
  1134. import java.sql.Connection;
  1135. import java.sql.DriverManager;
  1136. import java.sql.PreparedStatement;
  1137. import java.sql.ResultSet;
  1138. import java.sql.ResultSetMetaData;
  1139. import java.sql.SQLException;
  1140. import java.sql.Statement;
  1141. import java.sql.Timestamp;
  1142. import java.util.ArrayList;
  1143. import java.util.Date;
  1144. import java.util.List;
  1145.  
  1146. import javax.enterprise.context.ApplicationScoped;
  1147. import javax.inject.Named;
  1148. import javax.transaction.Transaction;
  1149.  
  1150.  
  1151. @Named
  1152. @ApplicationScoped
  1153. public class DatabaseConnectionPraktik2016 {
  1154.  
  1155.     private Connection connection;
  1156.     private PreparedStatement prepared;
  1157.     private ThreadLocal<Transaction> currentTransaction;
  1158.  
  1159.     public Connection getConnection() {
  1160.         return connection;
  1161.     }
  1162.  
  1163.     public Connection open() throws SQLException, ClassNotFoundException {
  1164.         Class.forName("net.sourceforge.jtds.jdbc.Driver");
  1165.         if (connection == null || connection.isClosed()) {
  1166.             connection = DriverManager.getConnection(DatabasePropertiesPraktik2016.getConnectionString());
  1167.             connection.setAutoCommit(true);
  1168.         }
  1169.  
  1170.         return connection;
  1171.     }
  1172.    
  1173.     public PreparedStatement prepare(String sql, String... params) throws SQLException {
  1174.         prepared = connection.prepareStatement(sql);
  1175.        
  1176.         for(int i = 0; i < params.length; i++) {
  1177.             prepared.setString(i + 1, params[i]);
  1178.         }
  1179.        
  1180.         return prepared;
  1181.     }
  1182.    
  1183.     public ResultSet execute() throws SQLException {
  1184.         return prepared.executeQuery();
  1185.     }
  1186.    
  1187.     public void update() throws SQLException {
  1188.         prepared.executeUpdate();
  1189.     }
  1190.  
  1191.     public void close() throws SQLException {
  1192.         if (connection != null) {
  1193.             connection.close();
  1194.         }
  1195.     }
  1196.  
  1197.     public Integer executeUpdate(String sql, Object... parameters) throws ClassNotFoundException {
  1198.         return executeUpdate(sql, toParameterList(parameters));
  1199.     }
  1200.  
  1201.     public Integer executeUpdate(String sql, List<Object> parameters) throws ClassNotFoundException {
  1202.         Integer key = null;
  1203.         try {
  1204.             open();
  1205.             PreparedStatement statement = connection.prepareStatement(sql);
  1206.             setParameters(statement, parameters);
  1207.             statement.executeUpdate();
  1208.             statement.close();
  1209.             if (sql.trim().toUpperCase().startsWith("INSERT")) {
  1210.                 Statement keyStatement = connection.createStatement();
  1211.                 ResultSet generatedKeys = keyStatement.executeQuery("Select scope_identity()");
  1212.                 if (generatedKeys.next()) {
  1213.                     key = generatedKeys.getInt(1);
  1214.                 }
  1215.             }
  1216.             close();
  1217.         }
  1218.  
  1219.         catch (SQLException ex) {
  1220.             ex.printStackTrace();
  1221.         }
  1222.  
  1223.         return key;
  1224.     }
  1225.  
  1226.     public List<Object[]> query(String sql, Object... parameters) throws ClassNotFoundException {
  1227.         return query(sql, toParameterList(parameters));
  1228.     }
  1229.  
  1230.     private List<Object> toParameterList(Object[] parameters) {
  1231.         List<Object> parameterList = new ArrayList<>();
  1232.         if (parameters != null && parameters.length > 0) {
  1233.             for (int i = 0; i < parameters.length; i++) {
  1234.                 parameterList.add(parameters[i]);
  1235.             }
  1236.         }
  1237.  
  1238.         return parameterList;
  1239.     }
  1240.  
  1241.     public List<Object[]> query(String sql, List<Object> parameters) throws ClassNotFoundException {
  1242.         List<Object[]> listResult = new ArrayList<>();
  1243.         try {
  1244.             open();
  1245.             PreparedStatement statement = connection.prepareStatement(sql);
  1246.             setParameters(statement, parameters);
  1247.             ResultSet result = statement.executeQuery();
  1248.             listResult = transform(result);
  1249.             result.close();
  1250.             statement.close();
  1251.             close();
  1252.         }
  1253.  
  1254.         catch (SQLException ex) {
  1255.             ex.printStackTrace();
  1256.         }
  1257.  
  1258.         return listResult;
  1259.     }
  1260.  
  1261.     private void setParameters(PreparedStatement statement, List<Object> parameters) throws SQLException {
  1262.         if (parameters != null && !parameters.isEmpty()) {
  1263.             int i = 1;
  1264.             for (Object parameter : parameters) {
  1265.                 if (parameter instanceof Integer) {
  1266.                     statement.setInt(i++, (Integer) parameter);
  1267.                 }
  1268.                 else if (parameter instanceof Long) {
  1269.                     statement.setLong(i++, (Long) parameter);
  1270.                 }
  1271.                 else if (parameter instanceof Double) {
  1272.                     statement.setDouble(i++, (Double) parameter);
  1273.                 }
  1274.                 else if (parameter instanceof Float) {
  1275.                     statement.setFloat(i++, (Float) parameter);
  1276.                 }
  1277.                 else if (parameter instanceof Date) {
  1278.                     statement.setTimestamp(i++, new Timestamp(((Date) parameter).getTime()));
  1279.                 }
  1280.                 else {
  1281.                     statement.setString(i++, (String) parameter);
  1282.                 }
  1283.             }
  1284.         }
  1285.     }
  1286.  
  1287.     private List<Object[]> transform(ResultSet result) throws SQLException {
  1288.         List<Object[]> listResult = new ArrayList<>();
  1289.         ResultSetMetaData meta = result.getMetaData();
  1290.         int columnCount = meta.getColumnCount();
  1291.         while (result.next()) {
  1292.             Object[] data = new Object[columnCount];
  1293.             for (int i = 0; i < columnCount; i++) {
  1294.                 data[i] = result.getObject(i + 1);
  1295.             }
  1296.             listResult.add(data);
  1297.         }
  1298.  
  1299.         return listResult;
  1300.     }
  1301. }
  1302.  
  1303. DatabaseProperties
  1304.  
  1305. package net.peopleway.invoicesystem.dbproperties;
  1306.  
  1307. public class DatabaseProperties {
  1308.  
  1309.     public static final String driver = "net.sourceforge.jtds.jdbc.Driver";
  1310.     public static final String database = "DWBI";
  1311.     public static final String ip = "152.115.57.214";
  1312.     public static final Integer port = 1433;
  1313.     public static final String user = "biuser";
  1314.     public static final String password = "EaseData2015!";
  1315.    
  1316.     public static String getConnectionString() {
  1317.         return "jdbc:jtds:sqlserver://" + ip + ":" + port + ";databaseName=" + database + ";user=" + user + ";password=" + password;
  1318.     }
  1319.    
  1320. }
  1321.  
  1322. DatabasePropertiesPraktik2016
  1323.  
  1324. package net.peopleway.invoicesystem.dbproperties;
  1325.  
  1326. public class DatabasePropertiesPraktik2016 {
  1327.  
  1328.     public static final String driver = "net.sourceforge.jtds.jdbc.Driver";
  1329.     public static final String database = "Praktik_2016_invoice";
  1330.     public static final String ip = "10.0.88.145";
  1331.     public static final Integer port = 1433;
  1332.     public static final String user = "sa";
  1333.     public static final String password = "needFORspeed!";
  1334.    
  1335.     public static String getConnectionString() {
  1336.         return "jdbc:jtds:sqlserver://" + ip + ":" + port + ";databaseName=" + database + ";user=" + user + ";password=" + password;
  1337.     }
  1338.    
  1339. }
  1340.  
  1341. package net.peopleway.invoicesystem.extra;
  1342.  
  1343. Extra
  1344.  
  1345. package net.peopleway.invoicesystem.extra;
  1346.  
  1347. import java.io.Serializable;
  1348.  
  1349. import javax.persistence.Column;
  1350. import javax.persistence.Entity;
  1351. import javax.persistence.GeneratedValue;
  1352. import javax.persistence.Id;
  1353. import javax.persistence.Table;
  1354.  
  1355. @Entity
  1356. @Table(name="extra")
  1357. public class Extra implements Serializable{
  1358.     private int extra_id;
  1359.     private String title;
  1360.     private Double price;
  1361.    
  1362.     @Id
  1363.     @GeneratedValue
  1364.     @Column
  1365.     public int getExtra_id() {
  1366.         return extra_id;
  1367.     }
  1368.     public void setExtra_id(int extra_id) {
  1369.         this.extra_id = extra_id;
  1370.     }
  1371.    
  1372.     @Column
  1373.     public String getTitle() {
  1374.         return title;
  1375.     }
  1376.     public void setTitle(String title) {
  1377.         this.title = title;
  1378.     }
  1379.    
  1380.     @Column
  1381.     public Double getPrice() {
  1382.         return price;
  1383.     }
  1384.     public void setPrice(Double price) {
  1385.         this.price = price;
  1386.     }
  1387.     @Override
  1388.     public String toString() {
  1389.         return title;
  1390.     }
  1391.     @Override
  1392.     public int hashCode() {
  1393.         final int prime = 31;
  1394.         int result = 1;
  1395.         result = prime * result + extra_id;
  1396.         return result;
  1397.     }
  1398.     @Override
  1399.     public boolean equals(Object obj) {
  1400.         if (this == obj)
  1401.             return true;
  1402.         if (obj == null)
  1403.             return false;
  1404.         if (getClass() != obj.getClass())
  1405.             return false;
  1406.         Extra other = (Extra) obj;
  1407.         if (extra_id != other.extra_id)
  1408.             return false;
  1409.         return true;
  1410.     }
  1411.  
  1412.    
  1413. }
  1414.  
  1415.  
  1416. ExtraBean
  1417.  
  1418. package net.peopleway.invoicesystem.extra;
  1419.  
  1420. import java.io.IOException;
  1421. import java.io.Serializable;
  1422.  
  1423. import javax.annotation.PostConstruct;
  1424. import javax.faces.application.FacesMessage;
  1425. import javax.faces.context.FacesContext;
  1426. import javax.faces.view.ViewScoped;
  1427. import javax.inject.Inject;
  1428. import javax.inject.Named;
  1429.  
  1430. import net.peopleway.invoicesystem.license.License;
  1431. import net.peopleway.invoicesystem.login.UserManager;
  1432.  
  1433. @Named
  1434. @ViewScoped
  1435. public class ExtraBean implements Serializable {
  1436.     private static final long serialVersionUID = 5633130014334164042L;
  1437.     @Inject
  1438.     private UserManager userManager;
  1439.     @Inject
  1440.     private ExtraService service;
  1441.     private Extra newExtra;
  1442.  
  1443.     @PostConstruct
  1444.     public void test() throws IOException {
  1445.         System.out.println("Init");
  1446.         if(!userManager.getUser().isAdministrator()){
  1447.             FacesContext.getCurrentInstance().getExternalContext().redirect("/invoicesystem/customers");
  1448.         }
  1449.         newExtra = new Extra();
  1450.     }
  1451.  
  1452.     public void saveExtra() {
  1453.         try{
  1454.             service.saveExtra(newExtra);
  1455.             newExtra = new Extra();
  1456.         }
  1457.         catch(Exception e){
  1458.             FacesContext.getCurrentInstance().addMessage(null,
  1459.                     new FacesMessage(e.getMessage()));
  1460.         }
  1461.     }
  1462.    
  1463.     public Extra getNewExtra() {
  1464.         return newExtra;
  1465.     }
  1466.  
  1467.     public void setNewExtra(Extra newExtra) {
  1468.         this.newExtra = newExtra;
  1469.     }
  1470.  
  1471. }
  1472.  
  1473. ExtraConverter
  1474.  
  1475. package net.peopleway.invoicesystem.extra;
  1476.  
  1477. import javax.enterprise.context.ApplicationScoped;
  1478. import javax.faces.component.UIComponent;
  1479. import javax.faces.context.FacesContext;
  1480. import javax.faces.convert.Converter;
  1481. import javax.inject.Inject;
  1482. import javax.inject.Named;
  1483.  
  1484. @Named
  1485. @ApplicationScoped
  1486. public class ExtraConverter implements Converter{
  1487.     @Inject
  1488.     private ExtraService ss;
  1489.  
  1490.     @Override
  1491.     public Object getAsObject(FacesContext context, UIComponent component, String value) {
  1492.         if (value == null) {
  1493.             return null;
  1494.         }
  1495.        
  1496.             for (Extra c : ss.getExtras()) {
  1497.                 if (c.getExtra_id() == Integer.parseInt(value)) {
  1498.                     return c;
  1499.                 }
  1500.             }
  1501.        
  1502.         return null;
  1503.     }
  1504.  
  1505.     @Override
  1506.     public String getAsString(FacesContext context, UIComponent component, Object value) {
  1507.         if (value == null)
  1508.             return "";
  1509.  
  1510.         return Integer.toString(((Extra) value).getExtra_id());
  1511.     }
  1512. }
  1513.  
  1514. ExtraDao
  1515.  
  1516. package net.peopleway.invoicesystem.extra;
  1517.  
  1518. import java.io.Serializable;
  1519. import java.util.List;
  1520.  
  1521. import javax.enterprise.context.ApplicationScoped;
  1522. import javax.faces.view.ViewScoped;
  1523. import javax.inject.Named;
  1524.  
  1525. import org.hibernate.Criteria;
  1526. import org.hibernate.Session;
  1527. import org.hibernate.Transaction;
  1528. import org.hibernate.criterion.Restrictions;
  1529.  
  1530. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  1531. import net.peopleway.invoicesystem.license.License;
  1532.  
  1533. @Named
  1534. @ApplicationScoped
  1535. public class ExtraDao implements Serializable {
  1536.  
  1537.     public boolean saveExtra(Extra newExtra) {
  1538.         Session session = (Session) DatabaseSessionFactory.getSession();
  1539.         Transaction t = session.beginTransaction();
  1540.             session.save(newExtra);
  1541.         t.commit();
  1542.         return true;
  1543.     }
  1544.    
  1545.     public List<Extra> getExtras(){
  1546.         Session session = DatabaseSessionFactory.getSession();
  1547.         Transaction t = session.beginTransaction();
  1548.         Criteria c = session.createCriteria(Extra.class);
  1549.         List<Extra> pl = c.list();
  1550.         t.commit();
  1551.         return pl;
  1552.     }
  1553. }
  1554.  
  1555. ExtraService
  1556.  
  1557. package net.peopleway.invoicesystem.extra;
  1558.  
  1559. import java.io.Serializable;
  1560. import java.util.List;
  1561.  
  1562. import javax.enterprise.context.ApplicationScoped;
  1563. import javax.inject.Inject;
  1564. import javax.inject.Named;
  1565.  
  1566. @Named
  1567. @ApplicationScoped
  1568. public class ExtraService implements Serializable{
  1569.     @Inject
  1570.     private ExtraDao dao;
  1571.    
  1572.     public List<Extra> getExtras(){
  1573.         return dao.getExtras();
  1574.     }
  1575.    
  1576.     public void saveExtra(Extra newExtra) throws Exception {
  1577.         if(newExtra == null){
  1578.             throw new Exception("No Extra is present");
  1579.         }
  1580.         if(newExtra.getTitle() == null || newExtra.getTitle().trim().length()== 0){
  1581.             throw new Exception("Does not contain a title");
  1582.         }
  1583.         if(newExtra.getPrice() == null ){
  1584.             throw new Exception("Price is required");
  1585.         }
  1586.         if(newExtra.getPrice() < 1){
  1587.             throw new Exception("Price must be higher or equal to 1");
  1588.         }
  1589.         if(!dao.saveExtra(newExtra)){
  1590.             throw new Exception("The title "+newExtra.getTitle() + " already exists");
  1591.         }
  1592.     }
  1593. }
  1594.  
  1595. DatabaseSessionFactory
  1596.  
  1597. package net.peopleway.invoicesystem.hibernate;
  1598.  
  1599. import org.hibernate.Session;
  1600. import org.hibernate.SessionFactory;
  1601. import org.hibernate.cfg.Configuration;
  1602.  
  1603. public class DatabaseSessionFactory {
  1604.     private static SessionFactory factory;
  1605.  
  1606.     public static SessionFactory getFactory() {
  1607.         return factory;
  1608.     }
  1609.  
  1610.     public static void configure(){
  1611.         Configuration config = new Configuration();
  1612.         config.configure("hibernate.cfg.xml"); 
  1613.         factory = config.buildSessionFactory();
  1614.     }
  1615.    
  1616.     public static Session getSession(){
  1617.         return factory.getCurrentSession();
  1618.     }
  1619.    
  1620.    
  1621. }
  1622.  
  1623. DatabaseStartupListener
  1624.  
  1625. package net.peopleway.invoicesystem.hibernate;
  1626.  
  1627. import javax.servlet.ServletContextEvent;
  1628. import javax.servlet.ServletContextListener;
  1629.  
  1630.  
  1631. public class DatabaseStartupListener implements ServletContextListener{
  1632.    
  1633.  
  1634.     @Override
  1635.     public void contextDestroyed(ServletContextEvent arg0) {
  1636.        
  1637.     }
  1638.  
  1639.     @Override
  1640.     public void contextInitialized(ServletContextEvent arg0) {
  1641.         DatabaseSessionFactory.configure();
  1642.     }
  1643.  
  1644.    
  1645.    
  1646. }
  1647.  
  1648.  
  1649. package net.peopleway.invoicesystem.index;
  1650.  
  1651. IndexBean
  1652.  
  1653. package net.peopleway.invoicesystem.index;
  1654.  
  1655. import java.io.Serializable;
  1656. import java.util.Date;
  1657.  
  1658. import javax.annotation.PostConstruct;
  1659. import javax.faces.application.FacesMessage;
  1660. import javax.faces.context.FacesContext;
  1661. import javax.faces.view.ViewScoped;
  1662. import javax.inject.Inject;
  1663. import javax.inject.Named;
  1664.  
  1665. @Named
  1666. @ViewScoped
  1667. public class IndexBean implements Serializable {
  1668.  
  1669.     private static final long serialVersionUID = 4995482822989124736L;
  1670.    
  1671.     @Inject
  1672.     private IndexService service;
  1673.    
  1674.     private Date startdate;
  1675.     private Double amount;
  1676.     private String start;
  1677.  
  1678.     @PostConstruct
  1679.     public void test() {
  1680.     }
  1681.    
  1682.     public void updatePrices() {
  1683.         try {
  1684.             service.updatePrices(service.createUpdatePrices(startdate, amount));
  1685.         } catch (Exception e) {
  1686.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  1687.         }
  1688.     }
  1689.  
  1690.     public Date getStartdate() {
  1691.         return startdate;
  1692.     }
  1693.  
  1694.     public void setStartdate(Date startdate) {
  1695.         this.startdate = startdate;
  1696.     }
  1697.  
  1698.     public Double getAmount() {
  1699.         return amount;
  1700.     }
  1701.  
  1702.     public void setAmount(Double amount) {
  1703.         this.amount = amount;
  1704.     }
  1705.  
  1706.     public String getStart() {
  1707.         return start;
  1708.     }
  1709.  
  1710.     public void setStart(String start) {
  1711.         this.start = start;
  1712.     }
  1713.    
  1714.    
  1715.    
  1716. }
  1717.  
  1718. IndexDao
  1719.  
  1720. package net.peopleway.invoicesystem.index;
  1721.  
  1722. import java.io.Serializable;
  1723. import java.util.ArrayList;
  1724. import java.util.Date;
  1725. import java.util.List;
  1726. import java.util.TreeMap;
  1727.  
  1728. import javax.enterprise.context.ApplicationScoped;
  1729. import javax.inject.Named;
  1730.  
  1731. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  1732. import net.peopleway.invoicesystem.license.License;
  1733. import net.peopleway.invoicesystem.pricelist.Interval;
  1734. import net.peopleway.invoicesystem.pricelist.Pricelist;
  1735.  
  1736. import org.hibernate.Criteria;
  1737. import org.hibernate.Session;
  1738. import org.hibernate.Transaction;
  1739. import org.hibernate.criterion.Restrictions;
  1740.  
  1741. @Named
  1742. @ApplicationScoped
  1743. public class IndexDao implements Serializable {
  1744.  
  1745.     public List<Pricelist> getStartLicenses() {
  1746.         Session session = (Session) DatabaseSessionFactory.getSession();
  1747.         Transaction t = session.beginTransaction();
  1748.         Criteria c = session.createCriteria(Pricelist.class);
  1749.         c.add(Restrictions.isNull("enddate"));
  1750.         List<Pricelist> pricelists = c.list();
  1751.         TreeMap<License, Pricelist> mapping = new TreeMap<License, Pricelist>();
  1752.         for (Pricelist p : pricelists) {
  1753.             if (p.getStartdate().compareTo(new Date()) < 0) {
  1754.                 if (!mapping.containsKey(p.getLicense())) {    
  1755.                         mapping.put(p.getLicense(), p);
  1756.                 }
  1757.             }
  1758.         }
  1759.         List<Pricelist> plist = new ArrayList<Pricelist>();
  1760.         for (Pricelist p : mapping.values()) {
  1761.             plist.add(p);
  1762.         }
  1763.         t.commit();
  1764.         return plist;
  1765.     }
  1766.  
  1767.     public List<Pricelist> getCurrentLicenses() {
  1768.         Session session = (Session) DatabaseSessionFactory.getSession();
  1769.         Transaction t = session.beginTransaction();
  1770.         Criteria c = session.createCriteria(Pricelist.class);
  1771.         c.add(Restrictions.isNull("enddate"));
  1772.         List<Pricelist> pricelists = c.list();
  1773.         TreeMap<License, Pricelist> mapping = new TreeMap<License, Pricelist>();
  1774.         for (Pricelist p : pricelists) {
  1775.             if (p.getStartdate().compareTo(new Date()) < 0) {
  1776.                 if (!mapping.containsKey(p.getLicense())) {    
  1777.                         mapping.put(p.getLicense(), p);
  1778.                 }
  1779.                 else{
  1780.                     Pricelist pValue = mapping.get(p.getLicense());
  1781.                     if(p.getStartdate().compareTo(pValue.getStartdate()) > 0){
  1782.                         mapping.put(p.getLicense(), p);
  1783.                     }
  1784.                 }
  1785.             }
  1786.         }
  1787.         List<Pricelist> plist = new ArrayList<Pricelist>();
  1788.         for (Pricelist p : mapping.values()) {
  1789.             plist.add(p);
  1790.         }
  1791.         t.commit();
  1792.         return plist;
  1793.     }
  1794.    
  1795.     public boolean priceExistForThatDate(Date startdate) {
  1796.         Session session = (Session) DatabaseSessionFactory.getSession();
  1797.         Transaction t = session.beginTransaction();
  1798.         Criteria c = session.createCriteria(Pricelist.class);
  1799.         c.add(Restrictions.eq("startdate", startdate));
  1800.         List<Pricelist> pricelists = c.list();
  1801.         t.commit();
  1802.         return pricelists.size() != 0;
  1803.     }
  1804.  
  1805.     public void updatePrices(List<Pricelist> licenses) {
  1806.         Session session = (Session) DatabaseSessionFactory.getSession();
  1807.         Transaction t = session.beginTransaction();
  1808.         for (Pricelist p : licenses) {
  1809.             for (Interval i : p.getIntervals()) {
  1810.                 session.save(i);
  1811.             }
  1812.             session.save(p);
  1813.         }
  1814.         t.commit();
  1815.     }
  1816. }
  1817.  
  1818. IndexService
  1819.  
  1820. package net.peopleway.invoicesystem.index;
  1821.  
  1822. import java.io.Serializable;
  1823. import java.util.ArrayList;
  1824. import java.util.Calendar;
  1825. import java.util.Date;
  1826. import java.util.List;
  1827.  
  1828. import javax.enterprise.context.ApplicationScoped;
  1829. import javax.inject.Inject;
  1830. import javax.inject.Named;
  1831.  
  1832. import net.peopleway.invoicesystem.pricelist.Interval;
  1833. import net.peopleway.invoicesystem.pricelist.Pricelist;
  1834.  
  1835. @Named
  1836. @ApplicationScoped
  1837. public class IndexService implements Serializable {
  1838.     @Inject
  1839.     IndexDao dao;
  1840.  
  1841.     public List<Pricelist> getCurrentLicenses(){
  1842.         return dao.getCurrentLicenses();
  1843.     }
  1844.    
  1845.     public List<Pricelist> createUpdatePrices(Date startdate, Double amount)
  1846.             throws Exception {
  1847.         if (dao == null) {
  1848.             dao = new IndexDao();
  1849.         }
  1850.         if (startdate == null) {
  1851.             throw new Exception(
  1852.                     "A start date is required for making an update to all prices");
  1853.         }
  1854.         Calendar c = Calendar.getInstance();
  1855.         c.setTime(new Date());
  1856.         c.set(Calendar.HOUR_OF_DAY, 0);
  1857.         c.set(Calendar.MINUTE, 0);
  1858.         c.set(Calendar.SECOND, 0);
  1859.         c.set(Calendar.MILLISECOND, 0);
  1860.         c.add(Calendar.DAY_OF_YEAR, 1);
  1861.         if (startdate.compareTo(c.getTime()) < 0) {
  1862.             throw new Exception("The startdate must be minimum tomorrow");
  1863.         }
  1864.         if (dao.priceExistForThatDate(startdate)) {
  1865.             throw new Exception("Update prices exists at the specified date");
  1866.         }
  1867.         if (amount == null) {
  1868.             throw new Exception(
  1869.                     "A index value is required to update all prices");
  1870.         } else if (amount <= 0) {
  1871.             throw new Exception("The index value must be higher than 0");
  1872.         }
  1873.  
  1874.         List<Pricelist> licenses = dao.getStartLicenses();
  1875.         List<Pricelist> licensesNew = new ArrayList<Pricelist>();
  1876.         for (Pricelist p : licenses) {
  1877.             Pricelist pCopy = new Pricelist();
  1878.             pCopy.setLicense(p.getLicense());
  1879.             ;
  1880.             pCopy.setStartdate(startdate);
  1881.             pCopy.setEnddate(p.getEnddate());
  1882.             pCopy.setTitle(p.getTitle());
  1883.             pCopy.setIntervals(new ArrayList<Interval>());
  1884.             for (Interval i : p.getIntervals()) {
  1885.                 Interval iCopy = new Interval();
  1886.                 iCopy.setPrice(i.getPrice() * amount);
  1887.                 iCopy.setFromInterval(i.getFromInterval());
  1888.                 iCopy.setToInterval(i.getToInterval());
  1889.                 pCopy.getIntervals().add(iCopy);
  1890.             }
  1891.             licensesNew.add(pCopy);
  1892.         }
  1893.         return licensesNew;
  1894.     }
  1895.  
  1896.     public void updatePrices(List<Pricelist> pricelists) throws Exception {
  1897.         if (dao == null) {
  1898.             dao = new IndexDao();
  1899.         }
  1900.         dao.updatePrices(pricelists);
  1901.     }
  1902.  
  1903.     public IndexDao getDao() {
  1904.         return dao;
  1905.     }
  1906.  
  1907.     public void setDao(IndexDao dao) {
  1908.         this.dao = dao;
  1909.     }
  1910.    
  1911. }
  1912.  
  1913. package net.peopleway.invoicesystem.invoice;
  1914.  
  1915. Invoice
  1916.  
  1917. package net.peopleway.invoicesystem.invoice;
  1918.  
  1919. import java.io.File;
  1920.  
  1921.  
  1922.  
  1923. import java.util.Date;
  1924.  
  1925. import javax.persistence.Column;
  1926. import javax.persistence.Entity;
  1927. import javax.persistence.EnumType;
  1928. import javax.persistence.Enumerated;
  1929. import javax.persistence.FetchType;
  1930. import javax.persistence.GeneratedValue;
  1931. import javax.persistence.Id;
  1932. import javax.persistence.JoinColumn;
  1933. import javax.persistence.ManyToOne;
  1934. import javax.persistence.Table;
  1935.  
  1936. import net.peopleway.invoicesystem.subscription.Subscription;
  1937.  
  1938. @Entity
  1939. @Table(name="invoice")
  1940. public class Invoice {
  1941.     private Subscription subscription;
  1942.     private Date creationDate, invoicesent, payday;
  1943.    
  1944.     private String invoiceNr, currency;
  1945.    
  1946.     private Double total;
  1947.    
  1948.     private int poNr, invoice_id;
  1949.    
  1950.     private InvoiceState invoicestate;
  1951.    
  1952.     // PDFs // Ignore
  1953.     private File finalPDF, originalPDF;
  1954.  
  1955.     public Invoice() {
  1956.         // TODO Auto-generated constructor stub
  1957.     }
  1958.  
  1959.     @ManyToOne(optional = true, fetch = FetchType.LAZY)
  1960.     @JoinColumn(name = "subscription_id")
  1961.     public Subscription getSubscription() {
  1962.         return subscription;
  1963.     }
  1964.  
  1965.     public void setSubscription(Subscription subscription) {
  1966.         this.subscription = subscription;
  1967.     }
  1968.  
  1969.     @Column
  1970.     public Date getCreationDate() {
  1971.         return creationDate;
  1972.     }
  1973.  
  1974.     public void setCreationDate(Date creationDate) {
  1975.         this.creationDate = creationDate;
  1976.     }
  1977.  
  1978.     @Column
  1979.     public Date getInvoicesent() {
  1980.         return invoicesent;
  1981.     }
  1982.  
  1983.     public void setInvoicesent(Date invoicesent) {
  1984.         this.invoicesent = invoicesent;
  1985.     }
  1986.  
  1987.     @Column
  1988.     public Date getPayday() {
  1989.         return payday;
  1990.     }
  1991.  
  1992.     public void setPayday(Date payday) {
  1993.         this.payday = payday;
  1994.     }
  1995.  
  1996.     @Column
  1997.     public String getInvoiceNr() {
  1998.         return invoiceNr;
  1999.     }
  2000.  
  2001.     public void setInvoiceNr(String invoiceNr) {
  2002.         this.invoiceNr = invoiceNr;
  2003.     }
  2004.  
  2005.     @Column
  2006.     public String getCurrency() {
  2007.         return currency;
  2008.     }
  2009.  
  2010.     public void setCurrency(String currency) {
  2011.         this.currency = currency;
  2012.     }
  2013.  
  2014.     @Column
  2015.     public Double getTotal() {
  2016.         return total;
  2017.     }
  2018.  
  2019.     public void setTotal(Double total) {
  2020.         this.total = total;
  2021.     }
  2022.  
  2023.     @Column
  2024.     public int getPoNr() {
  2025.         return poNr;
  2026.     }
  2027.  
  2028.     public void setPoNr(int poNr) {
  2029.         this.poNr = poNr;
  2030.     }
  2031.  
  2032.     @Enumerated(EnumType.STRING)
  2033.     public InvoiceState getInvoicestate() {
  2034.         return invoicestate;
  2035.     }
  2036.  
  2037.     public void setInvoicestate(InvoiceState invoicestate) {
  2038.         this.invoicestate = invoicestate;
  2039.     }
  2040.  
  2041.     @Id
  2042.     @GeneratedValue
  2043.     @Column
  2044.     public int getInvoice_id() {
  2045.         return invoice_id;
  2046.     }
  2047.  
  2048.     public void setInvoice_id(int invoice_id) {
  2049.         this.invoice_id = invoice_id;
  2050.     }
  2051.    
  2052.  
  2053. }
  2054.  
  2055. InvoiceInterval
  2056.  
  2057. package net.peopleway.invoicesystem.invoice;
  2058.  
  2059. import javax.persistence.EnumType;
  2060. import javax.persistence.Enumerated;
  2061.  
  2062. public enum InvoiceInterval {
  2063.     Daily, Weekly, Monthly, Quarterly, Yearly
  2064. }
  2065.  
  2066.  
  2067. InvoiceState
  2068.  
  2069. package net.peopleway.invoicesystem.invoice;
  2070.  
  2071. public enum InvoiceState {
  2072. Paid, InProgress, ApprovedAndSent, PastDeadline, PastDeadlineDelay, Draft
  2073. }
  2074.  
  2075. package net.peopleway.invoicesystem.junit.index;
  2076.  
  2077. IndexJUnit
  2078.  
  2079. package net.peopleway.invoicesystem.junit.index;
  2080.  
  2081. import static org.junit.Assert.assertEquals;
  2082.  
  2083. import java.util.Calendar;
  2084. import java.util.List;
  2085.  
  2086. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  2087. import net.peopleway.invoicesystem.index.IndexDao;
  2088. import net.peopleway.invoicesystem.index.IndexService;
  2089. import net.peopleway.invoicesystem.pricelist.Interval;
  2090. import net.peopleway.invoicesystem.pricelist.Pricelist;
  2091.  
  2092. import org.junit.After;
  2093. import org.junit.Before;
  2094. import org.junit.Test;
  2095.  
  2096. public class IndexJUnit {
  2097.     private IndexService service;
  2098.  
  2099.     @Before
  2100.     public void setUp() throws Exception {
  2101.         service = new IndexService();
  2102.         DatabaseSessionFactory.configure();
  2103.     }
  2104.    
  2105.     @After
  2106.     public void destroy(){
  2107.     }
  2108.  
  2109.     @Test
  2110.     public void updatePrices() throws Exception{
  2111.         Double amount = 2.0;
  2112.         Calendar c = Calendar.getInstance();
  2113.         c.add(Calendar.YEAR, 1);
  2114.         List<Pricelist> currentPricelist = new IndexDao().getStartLicenses();
  2115.         List<Pricelist> nextPricelist = service.createUpdatePrices(c.getTime(), amount);
  2116.         for(int i = 0; i < currentPricelist.size(); i++){
  2117.             Pricelist p = currentPricelist.get(i);
  2118.             Pricelist pNew = nextPricelist.get(i);
  2119.             for(int j = 0; j < p.getIntervals().size(); j++){
  2120.                 Interval interval = p.getIntervals().get(j);
  2121.                 Interval intervalNew = pNew.getIntervals().get(j);
  2122.                 interval.setPrice(interval.getPrice()*amount);
  2123.                 assertEquals(interval.getPrice(), intervalNew.getPrice());
  2124.             }
  2125.         }
  2126.     }
  2127. }
  2128.  
  2129.  
  2130. package net.peopleway.invoicesystem.junit.login;
  2131.  
  2132. LoginJUnit
  2133.  
  2134. package net.peopleway.invoicesystem.junit.login;
  2135.  
  2136. import static org.junit.Assert.*;
  2137.  
  2138. import java.sql.SQLException;
  2139.  
  2140. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  2141. import net.peopleway.invoicesystem.login.LoginService;
  2142. import net.peopleway.invoicesystem.user.User;
  2143.  
  2144. import org.junit.After;
  2145. import org.junit.Before;
  2146. import org.junit.Test;
  2147.  
  2148. public class LoginJUnit {
  2149.     private LoginService service;
  2150.     private User user;
  2151.  
  2152.     @Before
  2153.     public void setUp() throws Exception {
  2154.         user = new User();
  2155.         service = new LoginService();
  2156.         DatabaseSessionFactory.configure();
  2157.     }
  2158.  
  2159.     @After
  2160.     public void destroy(){
  2161.         service.destroyUserToken(user);
  2162.     }
  2163.    
  2164.     @Test
  2165.     public void loginAttempt() throws ClassNotFoundException, SQLException {
  2166.         user.setUsername("Lars");
  2167.         user.setPass("123");
  2168.         assertNotNull(service.validate(user.getUsername(), user.getPass()));
  2169.     }
  2170.  
  2171. }
  2172.  
  2173. package net.peopleway.invoicesystem.junit.subscription;
  2174.  
  2175. SubscriptionJUnit
  2176.  
  2177. package net.peopleway.invoicesystem.junit.subscription;
  2178.  
  2179.  
  2180.  
  2181. import static org.junit.Assert.assertEquals;
  2182. import static org.junit.Assert.assertNull;
  2183.  
  2184. import java.util.Date;
  2185. import java.util.List;
  2186.  
  2187. import net.peopleway.invoicesystem.customer.Customer;
  2188. import net.peopleway.invoicesystem.extra.Extra;
  2189. import net.peopleway.invoicesystem.extra.ExtraService;
  2190. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  2191. import net.peopleway.invoicesystem.index.IndexService;
  2192. import net.peopleway.invoicesystem.license.License;
  2193. import net.peopleway.invoicesystem.license.LicenseService;
  2194. import net.peopleway.invoicesystem.pricelist.Pricelist;
  2195. import net.peopleway.invoicesystem.pricelist.PricelistService;
  2196. import net.peopleway.invoicesystem.subscription.Subscription;
  2197. import net.peopleway.invoicesystem.subscription.SubscriptionDao;
  2198. import net.peopleway.invoicesystem.subscription.SubscriptionService;
  2199. import net.peopleway.invoicesystem.user.User;
  2200. import net.peopleway.invoicesystem.user.UserService;
  2201.  
  2202. import org.junit.After;
  2203. import org.junit.Before;
  2204. import org.junit.Test;
  2205.  
  2206. public class SubscriptionJUnit {
  2207.     private SubscriptionService service;
  2208.     private User user;
  2209.     private Customer c;
  2210.     private Subscription s;
  2211.  
  2212.     @Before
  2213.     public void setUp() throws Exception {
  2214.         user = new User();
  2215.         service = new SubscriptionService();
  2216.         DatabaseSessionFactory.configure();
  2217.     }
  2218.    
  2219.     @After
  2220.     public void destroy(){
  2221.     }
  2222.  
  2223.     @Test
  2224.     public void createUpdateRemoveUser() throws Exception {
  2225.         user.setUsername("Test12345");
  2226.         user.setPass("521");
  2227.         user.setName("Test");
  2228.         UserService uS = new UserService();
  2229.         uS.createUser(user);
  2230.         uS.getUserById(uS.getUsers().size()-1);
  2231.        
  2232.         Customer customer = new Customer();
  2233.         customer.setActive(false);
  2234.         customer.setAddressCustomer("Testing Ville");
  2235.         customer.setContactPerson("Børge Buller");
  2236.         customer.setCountry("Urgana");
  2237.         customer.setCreationDate(new Date());
  2238.         customer.setCurrency("DKK");
  2239.         customer.setDepartmentName("Danish Testers");
  2240.         customer.setEANnumber("Testing");
  2241.         customer.setMailaddress("Testing@Testing.net");
  2242.         customer.setName("Anne Jørgensen");
  2243.         customer.setPhonenumber("124254252");
  2244.         customer.setTestserver(0);
  2245.         customer.setZipcode("1234");
  2246.         user.getCustomers().add(customer);
  2247.         Subscription s = new Subscription();
  2248.         s.setCustomer(customer);
  2249.         new SubscriptionDao().createSub(s);
  2250.         assertEquals(s, new SubscriptionService().getCustSubs(c).get(new SubscriptionService().getCustSubs(c).size()-1));
  2251.         new SubscriptionService().deleteSubscription(s);
  2252.     }
  2253. }
  2254.  
  2255. package net.peopleway.invoicesystem.junit.user;
  2256.  
  2257. UserJUnit
  2258.  
  2259. package net.peopleway.invoicesystem.junit.user;
  2260.  
  2261.  
  2262.  
  2263. import static org.junit.Assert.assertEquals;
  2264.  
  2265. import static org.junit.Assert.assertNotEquals;
  2266. import static org.junit.Assert.assertNull;
  2267.  
  2268.  
  2269. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  2270. import net.peopleway.invoicesystem.user.User;
  2271. import net.peopleway.invoicesystem.user.UserService;
  2272.  
  2273. import org.junit.After;
  2274. import org.junit.Before;
  2275. import org.junit.Test;
  2276.  
  2277. public class UserJUnit {
  2278.     private UserService service;
  2279.     private User user;
  2280.  
  2281.     @Before
  2282.     public void setUp() throws Exception {
  2283.         user = new User();
  2284.         service = new UserService();
  2285.         DatabaseSessionFactory.configure();
  2286.     }
  2287.    
  2288.     @After
  2289.     public void destroy(){
  2290.     }
  2291.  
  2292.     @Test
  2293.     public void createUpdateRemoveUser() throws Exception {
  2294.         user.setUsername("Test12345");
  2295.         user.setPass("521");
  2296.         user.setName("Test");
  2297.         service.createUser(user);
  2298.         assertNotEquals(0, user.getUser_id());
  2299.         String name = "Test12345";
  2300.         user.setName(name);
  2301.         service.updateUser(user);
  2302.         assertEquals(name,service.getUserById(user.getUser_id()).getName());
  2303.         service.removeUser(user);
  2304.         assertNull(service.getUserById(user.getUser_id()));
  2305.     }
  2306. }
  2307.  
  2308. package net.peopleway.invoicesystem.license;
  2309.  
  2310. License
  2311.  
  2312. package net.peopleway.invoicesystem.license;
  2313.  
  2314. import java.io.Serializable;
  2315. import java.util.List;
  2316.  
  2317. import javax.persistence.CascadeType;
  2318. import javax.persistence.Column;
  2319. import javax.persistence.Entity;
  2320. import javax.persistence.GeneratedValue;
  2321. import javax.persistence.Id;
  2322. import javax.persistence.OneToMany;
  2323. import javax.persistence.Table;
  2324.  
  2325. import net.peopleway.invoicesystem.pricelist.Pricelist;
  2326.  
  2327. import org.hibernate.annotations.LazyCollection;
  2328. import org.hibernate.annotations.LazyCollectionOption;
  2329.  
  2330. @Entity
  2331. @Table(name = "license")
  2332. public class License implements Serializable, Comparable<License>{
  2333.     private int license_id;
  2334.     private String title;
  2335.     private String licensestate;
  2336.     private List<Pricelist> pricelists;
  2337.     private Double price;
  2338.  
  2339.     @Id
  2340.     @GeneratedValue
  2341.     @Column
  2342.     public int getLicense_id() {
  2343.         return license_id;
  2344.     }
  2345.  
  2346.     public void setLicense_id(int license_id) {
  2347.         this.license_id = license_id;
  2348.     }  
  2349.     @Column
  2350.     public String getTitle() {
  2351.         return title;
  2352.     }
  2353.  
  2354.     public void setTitle(String title) {
  2355.         this.title = title;
  2356.     }
  2357.  
  2358.    
  2359.     @LazyCollection(LazyCollectionOption.FALSE)
  2360.     @OneToMany(cascade = CascadeType.ALL, mappedBy = "license")
  2361.     public List<Pricelist> getPricelists() {
  2362.         return pricelists;
  2363.     }
  2364.  
  2365.     public void setPricelists(List<Pricelist> pricelists) {
  2366.         this.pricelists = pricelists;
  2367.     }
  2368.  
  2369.     @Override
  2370.     public boolean equals(Object o){
  2371.         if(o != null && o instanceof License){
  2372.             return license_id == ((License) o).getLicense_id();
  2373.         }
  2374.         return false;
  2375.     }
  2376.    
  2377.     public String toString(){
  2378.         return "" + title;
  2379.     }
  2380.  
  2381.     @Column
  2382.     public Double getPrice() {
  2383.         return price;
  2384.     }
  2385.  
  2386.     public void setPrice(Double price) {
  2387.         this.price = price;
  2388.     }
  2389.  
  2390.     @Override
  2391.     public int compareTo(License o) {
  2392.         if(o.getLicense_id() == license_id) return 0;
  2393.         if(o.getLicense_id() > license_id) return 1;
  2394.         return -1;
  2395.     }
  2396.  
  2397.     @Column
  2398.     public String getLicensestate() {
  2399.         return licensestate;
  2400.     }
  2401.  
  2402.     public void setLicensestate(String licensestate) {
  2403.         this.licensestate = licensestate;
  2404.     }
  2405.  
  2406. }
  2407.  
  2408.  
  2409. LicenseBean
  2410.  
  2411. package net.peopleway.invoicesystem.license;
  2412.  
  2413. import java.io.IOException;
  2414. import java.io.Serializable;
  2415.  
  2416. import javax.annotation.PostConstruct;
  2417. import javax.faces.application.FacesMessage;
  2418. import javax.faces.context.FacesContext;
  2419. import javax.faces.view.ViewScoped;
  2420. import javax.inject.Inject;
  2421. import javax.inject.Named;
  2422.  
  2423. import net.peopleway.invoicesystem.login.UserManager;
  2424.  
  2425. @Named
  2426. @ViewScoped
  2427. public class LicenseBean implements Serializable {
  2428.     @Inject
  2429.     private UserManager userManager;
  2430.     @Inject
  2431.     private LicenseService service;
  2432.     private License newLicense;
  2433.  
  2434.     @PostConstruct
  2435.     public void test() throws IOException {
  2436.         System.out.println("Init");
  2437.         if(!userManager.getUser().isAdministrator()){
  2438.             FacesContext.getCurrentInstance().getExternalContext().redirect("/invoicesystem/customers");
  2439.         }
  2440.         newLicense = new License();
  2441.    
  2442.     }
  2443.  
  2444.     public void saveLicense() {
  2445.         try{
  2446.             service.saveLicense(newLicense);
  2447.             newLicense = new License();
  2448.         }
  2449.         catch(Exception e){
  2450.             FacesContext.getCurrentInstance().addMessage(null,
  2451.                     new FacesMessage(e.getMessage()));
  2452.         }
  2453.     }
  2454.    
  2455.     public License getNewLicense() {
  2456.         return newLicense;
  2457.     }
  2458.  
  2459.     public void setNewLicense(License newLicense) {
  2460.         this.newLicense = newLicense;
  2461.     }
  2462.  
  2463. }
  2464.  
  2465. LicenseConverter
  2466.  
  2467. package net.peopleway.invoicesystem.license;
  2468.  
  2469. import javax.enterprise.context.ApplicationScoped;
  2470. import javax.faces.component.UIComponent;
  2471. import javax.faces.context.FacesContext;
  2472. import javax.faces.convert.Converter;
  2473. import javax.inject.Inject;
  2474. import javax.inject.Named;
  2475.  
  2476. import net.peopleway.invoicesystem.pricelist.PricelistService;
  2477. import net.peopleway.invoicesystem.product.Product;
  2478.  
  2479. @Named
  2480. @ApplicationScoped
  2481. public class LicenseConverter implements Converter{
  2482.     @Inject
  2483.     private PricelistService ss;
  2484.  
  2485.     @Override
  2486.     public Object getAsObject(FacesContext context, UIComponent component, String value) {
  2487.         if (value == null) {
  2488.             return null;
  2489.         }
  2490.        
  2491.             for (License c : ss.getLicenses()) {
  2492.                 if (c.getLicense_id() == Integer.parseInt(value)) {
  2493.                     return c;
  2494.                 }
  2495.             }
  2496.        
  2497.         return null;
  2498.     }
  2499.  
  2500.     @Override
  2501.     public String getAsString(FacesContext context, UIComponent component, Object value) {
  2502.         if (value == null)
  2503.             return "";
  2504.  
  2505.         return Integer.toString(((License) value).getLicense_id());
  2506.     }
  2507. }
  2508.  
  2509. LicenseDao
  2510.  
  2511. package net.peopleway.invoicesystem.license;
  2512.  
  2513. import java.util.List;
  2514.  
  2515. import javax.enterprise.context.ApplicationScoped;
  2516. import javax.faces.view.ViewScoped;
  2517. import javax.inject.Named;
  2518.  
  2519. import org.hibernate.Criteria;
  2520. import org.hibernate.Session;
  2521. import org.hibernate.Transaction;
  2522. import org.hibernate.criterion.Restrictions;
  2523.  
  2524. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  2525.  
  2526. @Named
  2527. @ApplicationScoped
  2528. public class LicenseDao {
  2529.  
  2530.     public boolean saveLicense(License newLicense) {
  2531.         Session session = (Session) DatabaseSessionFactory.getSession();
  2532.         Transaction t = session.beginTransaction();
  2533.         Criteria c = session.createCriteria(License.class);
  2534.         c.add(Restrictions.eq("title", newLicense.getTitle()));
  2535.         List<License> licenses = c.list();
  2536.         if(licenses.size() == 0){
  2537.             session.save(newLicense);
  2538.         }
  2539.         t.commit();
  2540.         return licenses.size() == 0;
  2541.     }
  2542.  
  2543. }
  2544.  
  2545. LicenseService
  2546.  
  2547. package net.peopleway.invoicesystem.license;
  2548.  
  2549. import java.io.Serializable;
  2550. import java.util.ArrayList;
  2551.  
  2552. import javax.enterprise.context.ApplicationScoped;
  2553. import javax.inject.Inject;
  2554. import javax.inject.Named;
  2555.  
  2556. import net.peopleway.invoicesystem.pricelist.Pricelist;
  2557.  
  2558. @Named
  2559. @ApplicationScoped
  2560. public class LicenseService implements Serializable{
  2561.     @Inject
  2562.     private LicenseDao dao;
  2563.    
  2564.     public void saveLicense(License newLicense) throws Exception {
  2565.         if(newLicense == null){
  2566.             throw new Exception("No license is present");
  2567.         }
  2568.         newLicense.setPricelists(new ArrayList<Pricelist>());
  2569.         if(newLicense.getTitle() == null || newLicense.getTitle().trim().length() == 0){
  2570.             throw new Exception("License does not contain a title");
  2571.         }
  2572.         if(!dao.saveLicense(newLicense)){
  2573.             throw new Exception("The title "+newLicense.getTitle() + " already exists");
  2574.         }
  2575.     }
  2576. }
  2577.  
  2578. import net.peopleway.invoicesystem.user.User;
  2579.  
  2580. LoginBean
  2581.  
  2582. package net.peopleway.invoicesystem.login;
  2583.  
  2584. import java.io.Serializable;
  2585. import java.sql.SQLException;
  2586. import java.util.HashMap;
  2587. import java.util.Map;
  2588.  
  2589. import javax.faces.application.FacesMessage;
  2590. import javax.faces.context.FacesContext;
  2591. import javax.faces.view.ViewScoped;
  2592. import javax.inject.Inject;
  2593. import javax.inject.Named;
  2594.  
  2595. import net.peopleway.invoicesystem.user.User;
  2596.  
  2597. import org.apache.commons.lang.StringUtils;
  2598. @Named
  2599. @ViewScoped
  2600. public class LoginBean implements Serializable{
  2601.     private static final long serialVersionUID = 2524140245116159619L;
  2602. @Inject UserManager userManager;
  2603. @Inject LoginService loginService;
  2604.  
  2605.     private String password;
  2606.     private String username;
  2607.     private String returnUrl;
  2608.    
  2609.     public String getPassword() {
  2610.         return password;
  2611.     }
  2612.     public void setPassword(String password) {
  2613.         this.password = password;
  2614.     }
  2615.     public String getUsername() {
  2616.         return username;
  2617.     }
  2618.     public void setUsername(String username) {
  2619.         this.username = username;
  2620.     }
  2621.     public String getReturnUrl() {
  2622.         return returnUrl;
  2623.     }
  2624.     public void setReturnUrl(String returnUrl) {
  2625.         this.returnUrl = returnUrl;
  2626.     }
  2627.  
  2628.     public String validateUsernamePassword() throws SQLException, ClassNotFoundException {
  2629.         User user = loginService.validate(username, password);
  2630.         if (user != null) {
  2631.                 userManager.setUser(user);
  2632.                 String token = loginService.storeUserToken(user.getUser_id());
  2633.                 Map<String, Object> props = new HashMap<>();
  2634.                 props.put("httpOnly", true);
  2635.                 props.put("maxAge", 1000 * 10);
  2636.                     if(StringUtils.isBlank(returnUrl)){
  2637.                         return "/private/customers.xhtml?faces-redirect=true";
  2638.                 }
  2639.                 return returnUrl + "?faces-redirect=true";
  2640.             } else {
  2641.                 FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Incorrect Username and Password","Please enter correct username and Password"));
  2642.             }
  2643.         return null;
  2644.     }
  2645. }
  2646.  
  2647. LoginDao
  2648.  
  2649. package net.peopleway.invoicesystem.login;
  2650.  
  2651. import java.io.Serializable;
  2652. import java.sql.ResultSet;
  2653. import java.sql.SQLException;
  2654.  
  2655. import javax.enterprise.context.ApplicationScoped;
  2656. import javax.enterprise.context.Destroyed;
  2657. import javax.enterprise.event.Observes;
  2658. import javax.inject.Inject;
  2659. import javax.inject.Named;
  2660.  
  2661. import net.peopleway.invoicesystem.dbproperties.DatabaseConnectionPraktik2016;
  2662. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  2663. import net.peopleway.invoicesystem.user.User;
  2664.  
  2665. import org.hibernate.Criteria;
  2666. import org.hibernate.SQLQuery;
  2667. import org.hibernate.Session;
  2668. import org.hibernate.Transaction;
  2669. import org.hibernate.criterion.Restrictions;
  2670. @Named
  2671. @ApplicationScoped
  2672. public class LoginDao implements Serializable{
  2673.     private static final long serialVersionUID = -4503635128189222548L;
  2674.    
  2675.    
  2676.     @Inject DatabaseConnectionPraktik2016 db = new DatabaseConnectionPraktik2016();
  2677.  
  2678.     public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) throws SQLException {
  2679.         db.close();
  2680.     }
  2681.     public void destoryUserTokens(Integer id){
  2682.         Session session = (Session) DatabaseSessionFactory.getSession();
  2683.         Transaction t = session.beginTransaction();
  2684.         SQLQuery q = session.createSQLQuery("delete from usertoken where user_id = ?");
  2685.         q.setInteger(0, id);
  2686.         q.executeUpdate();
  2687.         t.commit();
  2688.     }
  2689.    
  2690.     public User validate(String username, String keyphrase) throws SQLException, ClassNotFoundException{
  2691.         User u = null;
  2692.         Session session = (Session) DatabaseSessionFactory.getSession();
  2693.         Transaction t = session.beginTransaction();
  2694.         Criteria c = session.createCriteria(User.class);
  2695.         c.add(Restrictions.eq("username", username));
  2696.         c.add(Restrictions.eq("pass", keyphrase));
  2697.         u = (User) c.uniqueResult();
  2698.         t.commit();
  2699.         return u;
  2700.     }
  2701.    
  2702.     public User getUserByToken(String token) throws SQLException, ClassNotFoundException{
  2703.         User u = null;
  2704.         ResultSet rs = null;
  2705.         db.open();
  2706.         db.prepare("select * from users, userToken where token = ? and userToken.user_id = users.user_id", token);
  2707.         rs = db.execute();
  2708.         while(rs.next()){
  2709.             u = new User();
  2710.             u.setName(rs.getString("name"));
  2711.             u.setUsername(rs.getString("username"));
  2712.             u.setPass(rs.getString("pass"));
  2713.             u.setUser_id(rs.getInt("user_id"));
  2714.             u.setAdministrator(rs.getBoolean("administrator"));
  2715.         }
  2716.         return u;
  2717.     }
  2718.    
  2719.     public void storeUserToken(Integer id, String token) throws SQLException, ClassNotFoundException{
  2720.         db.open();
  2721.         db.executeUpdate("insert into UserToken values (?,?); SELECT SCOPE_IDENTITY();", token, id);
  2722.     }
  2723. }
  2724.  
  2725. LoginFilter
  2726.  
  2727. package net.peopleway.invoicesystem.login;
  2728.  
  2729. import java.io.IOException;
  2730. import java.net.URLEncoder;
  2731. import java.sql.SQLException;
  2732.  
  2733. import javax.inject.Inject;
  2734. import javax.servlet.Filter;
  2735. import javax.servlet.FilterChain;
  2736. import javax.servlet.FilterConfig;
  2737. import javax.servlet.ServletException;
  2738. import javax.servlet.ServletRequest;
  2739. import javax.servlet.ServletResponse;
  2740. import javax.servlet.http.Cookie;
  2741. import javax.servlet.http.HttpServletRequest;
  2742. import javax.servlet.http.HttpServletResponse;
  2743.  
  2744. import net.peopleway.invoicesystem.user.User;
  2745.  
  2746. public class LoginFilter implements Filter{
  2747.     @Inject UserManager userManager;
  2748.    
  2749.     @Inject LoginService loginService;
  2750.    
  2751.     @Override
  2752.     public void init(FilterConfig filterConfig) throws ServletException {
  2753.        
  2754.     }
  2755.  
  2756.     @Override
  2757.     public void doFilter(ServletRequest req, ServletResponse res,
  2758.             FilterChain chain) throws IOException, ServletException {
  2759.         if(userManager.isLoggedIn()){
  2760.             chain.doFilter(req, res);
  2761.             return;
  2762.         }
  2763.         HttpServletRequest request = (HttpServletRequest) req;
  2764.         HttpServletResponse response = (HttpServletResponse) res;  
  2765.        
  2766.         String token = getCookie(request, "token");
  2767.         User user = null;
  2768.         try {
  2769.             user = loginService.getUserByToken(token);
  2770.         } catch (SQLException | ClassNotFoundException e) {
  2771.             e.printStackTrace();
  2772.         }
  2773.         if (user != null) {
  2774.             userManager.setUser(user);
  2775.             chain.doFilter(req, res);
  2776.             return;
  2777.         }
  2778.        
  2779.         String s = request.getRequestURI();
  2780.         s = s.substring(request.getContextPath().length());
  2781.         s = URLEncoder.encode(s, "UTF-8");
  2782.         response.sendRedirect(request.getContextPath()+ "/login?returnUrl=" + s);
  2783.  
  2784.        
  2785.     }
  2786.  
  2787.     @Override
  2788.     public void destroy() {
  2789.        
  2790.     }
  2791.     private String getCookie(HttpServletRequest request, String name){
  2792.         Cookie[] cookies = request.getCookies();
  2793.         if(cookies != null){
  2794.             for(int i = 0; i < cookies.length; i++){
  2795.                 Cookie cookie = cookies[i];
  2796.                 if(cookie.getName().equals(name))
  2797.                 return cookie.getValue();
  2798.                
  2799.             }
  2800.         }
  2801.         return null;
  2802.     }
  2803. }
  2804.  
  2805. LoginService
  2806.  
  2807. package net.peopleway.invoicesystem.login;
  2808.  
  2809. import java.io.Serializable;
  2810. import java.security.SecureRandom;
  2811. import java.sql.SQLException;
  2812.  
  2813. import javax.enterprise.context.ApplicationScoped;
  2814. import javax.inject.Inject;
  2815. import javax.inject.Named;
  2816.  
  2817. import net.peopleway.invoicesystem.user.User;
  2818.  
  2819. import org.apache.commons.codec.binary.Hex;
  2820. @Named
  2821. @ApplicationScoped
  2822. public class LoginService implements Serializable{
  2823.  
  2824.     private static final long serialVersionUID = 3065017410480034450L;
  2825.     @Inject LoginDao db = new LoginDao();
  2826.    
  2827.     public User validate(String username, String keyphrase) throws SQLException, ClassNotFoundException{
  2828.         return db.validate(username, keyphrase);
  2829.     }
  2830.     public User getUserByToken(String token) throws SQLException, ClassNotFoundException{
  2831.         return db.getUserByToken(token);
  2832.     }
  2833.     public String storeUserToken(Integer id) throws SQLException, ClassNotFoundException{
  2834.         SecureRandom rnd = new SecureRandom();
  2835.         byte bytes[] = new byte[16];
  2836.         rnd.nextBytes(bytes);
  2837.         String token = Hex.encodeHexString(bytes);
  2838.         db.storeUserToken(id, token);
  2839.         return token;
  2840.     }
  2841.     public void destroyUserToken(User user){
  2842.         db.destoryUserTokens(user.getUser_id());
  2843.     }
  2844. }
  2845.  
  2846. UserManager
  2847.  
  2848. package net.peopleway.invoicesystem.login;
  2849.  
  2850. import java.io.Serializable;
  2851.  
  2852.  
  2853.  
  2854. import javax.enterprise.context.SessionScoped;
  2855. import javax.inject.Named;
  2856.  
  2857. import net.peopleway.invoicesystem.user.User;
  2858.  
  2859.  
  2860. @Named
  2861. @SessionScoped
  2862. public class UserManager implements Serializable {
  2863.  
  2864.     private static final long serialVersionUID = 5174712862754337675L;
  2865.    
  2866.     private User user;
  2867.  
  2868.     public User getUser() {
  2869.         return user;
  2870.     }
  2871.  
  2872.     public void setUser(User user) {
  2873.         this.user = user;
  2874.     }
  2875.  
  2876.     public boolean isLoggedIn() {
  2877.         return user != null;
  2878.     }
  2879. }
  2880.  
  2881. package net.peopleway.invoicesystem.pricecalculator;
  2882.  
  2883. PriceCalculatorBean
  2884.  
  2885. package net.peopleway.invoicesystem.pricecalculator;
  2886.  
  2887. import java.io.Serializable;
  2888. import java.util.ArrayList;
  2889. import java.util.List;
  2890.  
  2891. import javax.annotation.PostConstruct;
  2892. import javax.faces.view.ViewScoped;
  2893. import javax.inject.Inject;
  2894. import javax.inject.Named;
  2895.  
  2896. import net.peopleway.invoicesystem.index.IndexService;
  2897. import net.peopleway.invoicesystem.license.License;
  2898. import net.peopleway.invoicesystem.pricelist.Pricelist;
  2899. import net.peopleway.invoicesystem.pricelist.PricelistService;
  2900. import net.peopleway.invoicesystem.product.Template;
  2901. import net.peopleway.invoicesystem.subscription.SubscriptionService;
  2902.  
  2903. @Named
  2904. @ViewScoped
  2905. public class PriceCalculatorBean implements Serializable {
  2906.  
  2907.     private static final long serialVersionUID = -8282945470947331710L;
  2908.  
  2909.     @Inject
  2910.     private SubscriptionService ss;
  2911.     @Inject
  2912.     private PricelistService ps;
  2913.     @Inject
  2914.     private IndexService is;
  2915.  
  2916.     private int expectedParticipants;
  2917.     private int employees;
  2918.     private int endUsers;
  2919.     private int testserver;
  2920.     private License license;
  2921.     private List<Template> templates;
  2922.     private List<PriceCalculatorResult> results;
  2923.     private PriceCalculatorResult recommended;
  2924.  
  2925.     @PostConstruct
  2926.     public void initialize() {
  2927.         templates = ss.getTemplates();
  2928.     }
  2929.    
  2930.  
  2931.     public void calculate() {
  2932.         results = new ArrayList<>();
  2933.         recommended = null;
  2934.  
  2935.        
  2936.         for (Template template : templates) {
  2937.             PriceCalculatorResult result = new PriceCalculatorResult();
  2938.             Pricelist p = null;
  2939.             for(Pricelist list : is.getCurrentLicenses()){
  2940.                 if(list.getLicense().equals(template.getLicense())){
  2941.                     p = list;
  2942.                     break;
  2943.                 }
  2944.             }
  2945.             result.setTitle(template.getTitle());
  2946.             result.setTemplateId(template.getTemplate_id());
  2947.             result.setLicense(template.getLicense());
  2948.             result.setExtras(template.getExtras());
  2949.             if(result.getLicense().getLicensestate().toLowerCase().equals("enduser")){
  2950.                 result.setVolume(endUsers);
  2951.             }else if(result.getLicense().getLicensestate().toLowerCase().equals("ppu")|| result.getLicense().getLicensestate().toLowerCase().equals("vendor")){
  2952.                 result.setVolume(expectedParticipants);
  2953.             }else if(result.getLicense().getLicensestate().toLowerCase().equals("enterprise")){
  2954.                 result.setVolume(employees);
  2955.             }
  2956.             result.calculate(p);
  2957.  
  2958.             if (recommended == null || recommended.getTotalPrice() > result.getTotalPrice()) {
  2959.                 recommended = result;
  2960.             }
  2961.             results.add(result);
  2962.         }
  2963.     }
  2964.  
  2965.     public int getEndUsers() {
  2966.         return endUsers;
  2967.     }
  2968.  
  2969.     public void setEndUsers(int endUsers) {
  2970.         this.endUsers = endUsers;
  2971.     }
  2972.  
  2973.     public PriceCalculatorResult getRecommended() {
  2974.         return recommended;
  2975.     }
  2976.  
  2977.     public void setRecommended(PriceCalculatorResult recommended) {
  2978.         this.recommended = recommended;
  2979.     }
  2980.  
  2981.     public List<Template> getTemplates() {
  2982.         return templates;
  2983.     }
  2984.  
  2985.     public void setTemplates(List<Template> templates) {
  2986.         this.templates = templates;
  2987.     }
  2988.  
  2989.     public License getLicense() {
  2990.         return license;
  2991.     }
  2992.  
  2993.     public void setLicense(License license) {
  2994.         this.license = license;
  2995.     }
  2996.  
  2997.     public int getExpectedParticipants() {
  2998.         return expectedParticipants;
  2999.     }
  3000.  
  3001.     public void setExpectedParticipants(int expectedParticipants) {
  3002.         this.expectedParticipants = expectedParticipants;
  3003.     }
  3004.  
  3005.     public int getEmployees() {
  3006.         return employees;
  3007.     }
  3008.  
  3009.     public void setEmployees(int employees) {
  3010.         this.employees = employees;
  3011.     }
  3012.  
  3013.     public int getTestserver() {
  3014.         return testserver;
  3015.     }
  3016.  
  3017.     public void setTestserver(int testserver) {
  3018.         this.testserver = testserver;
  3019.     }
  3020.  
  3021.     public List<PriceCalculatorResult> getResults() {
  3022.         return results;
  3023.     }
  3024.  
  3025.  
  3026.     public SubscriptionService getSs() {
  3027.         return ss;
  3028.     }
  3029.  
  3030.  
  3031.     public void setSs(SubscriptionService ss) {
  3032.         this.ss = ss;
  3033.     }
  3034.  
  3035.  
  3036.     public PricelistService getPs() {
  3037.         return ps;
  3038.     }
  3039.  
  3040.  
  3041.     public void setPs(PricelistService ps) {
  3042.         this.ps = ps;
  3043.     }
  3044.  
  3045.  
  3046.     public IndexService getIs() {
  3047.         return is;
  3048.     }
  3049.  
  3050.  
  3051.     public void setIs(IndexService is) {
  3052.         this.is = is;
  3053.     }
  3054.  
  3055. }
  3056.  
  3057. PriceCalculatorResult
  3058.  
  3059. package net.peopleway.invoicesystem.pricecalculator;
  3060.  
  3061. import java.util.ArrayList;
  3062. import java.util.Date;
  3063. import java.util.List;
  3064.  
  3065. import net.peopleway.invoicesystem.extra.Extra;
  3066. import net.peopleway.invoicesystem.license.License;
  3067. import net.peopleway.invoicesystem.pricelist.Interval;
  3068. import net.peopleway.invoicesystem.pricelist.Pricelist;
  3069.  
  3070.  
  3071. public class PriceCalculatorResult {
  3072.    
  3073.     private Integer templateId;
  3074.     private License license;
  3075.     private Integer volume;
  3076.     private List<Extra> extras = new ArrayList<>();
  3077.    
  3078.     private String title;
  3079.     private Double licensePrice = 0.0;
  3080.     private Double usagePrice = 0.0;
  3081.     private Double extrasPrice = 0.0;
  3082.     private Double totalPrice = 0.0;
  3083.    
  3084.     public String getTitle() {
  3085.         return title;
  3086.     }
  3087.    
  3088.     public void setTitle(String title) {
  3089.         this.title = title;
  3090.     }
  3091.  
  3092.     public void setTemplateId(Integer templateId) {
  3093.         this.templateId = templateId;
  3094.     }
  3095.  
  3096.     public void setLicense(License license) {
  3097.         this.license = license;
  3098.     }
  3099.    
  3100.     public License getLicense() {
  3101.         return license;
  3102.     }
  3103.    
  3104.     public List<Extra> getExtras() {
  3105.         return extras;
  3106.     }
  3107.  
  3108.     public void setExtras(List<Extra> extras) {
  3109.         this.extras = extras;
  3110.     }
  3111.  
  3112.     public void setVolume(Integer volume) {
  3113.         this.volume = volume;
  3114.     }
  3115.  
  3116.     public Double getLicensePrice() {
  3117.         return licensePrice;
  3118.     }
  3119.  
  3120.     public Double getUsagePrice() {
  3121.         return usagePrice;
  3122.     }
  3123.  
  3124.     public Double getExtrasPrice() {
  3125.         return extrasPrice;
  3126.     }
  3127.  
  3128.     public Double getTotalPrice() {
  3129.         return totalPrice;
  3130.     }
  3131.  
  3132.     public void calculate(Pricelist list) {
  3133.         licensePrice = license.getPrice();
  3134.         usagePrice = 0.0;
  3135.         if(list.getLicense().getLicensestate().toLowerCase().equals("enterprise")){
  3136.             if(volume <= 420){
  3137.                 usagePrice += list.getIntervals().get(0).getPrice() * 420;
  3138.                 totalPrice = licensePrice + extrasPrice + usagePrice;
  3139.                 return;
  3140.             }
  3141.         }
  3142.         for(Interval interval : list.getIntervals()){
  3143.             Integer from = interval.getFromInterval();
  3144.             Integer to = interval.getToInterval();
  3145.             Double price = interval.getPrice();
  3146.            
  3147.             if(volume > to) {
  3148.                 usagePrice += (to - from + 1) * price;
  3149.             }
  3150.             else if(volume >= from) {
  3151.                 usagePrice += (volume - from + 1) * price;
  3152.             }
  3153.         }
  3154.  
  3155.         extrasPrice = 0.0;
  3156.         if(extras != null) {
  3157.             for(Extra extra : extras) {
  3158.                 extrasPrice += extra.getPrice();
  3159.             }
  3160.         }
  3161.        
  3162.         totalPrice = licensePrice + usagePrice + extrasPrice;
  3163.     }
  3164.  
  3165.     @Override
  3166.     public int hashCode() {
  3167.         final int prime = 31;
  3168.         int result = 1;
  3169.         result = prime * result + ((templateId == null) ? 0 : templateId.hashCode());
  3170.         return result;
  3171.     }
  3172.  
  3173.     @Override
  3174.     public boolean equals(Object obj) {
  3175.         if (this == obj)
  3176.             return true;
  3177.         if (obj == null)
  3178.             return false;
  3179.         if (getClass() != obj.getClass())
  3180.             return false;
  3181.         PriceCalculatorResult other = (PriceCalculatorResult) obj;
  3182.         if (templateId == null) {
  3183.             if (other.templateId != null)
  3184.                 return false;
  3185.         } else if (!templateId.equals(other.templateId))
  3186.             return false;
  3187.         return true;
  3188.     }
  3189.    
  3190. }
  3191.  
  3192. package net.peopleway.invoicesystem.pricelist;
  3193.  
  3194.  
  3195. Interval
  3196.  
  3197. package net.peopleway.invoicesystem.pricelist;
  3198.  
  3199. import java.io.Serializable;
  3200.  
  3201. import javax.persistence.Column;
  3202. import javax.persistence.Entity;
  3203. import javax.persistence.GeneratedValue;
  3204. import javax.persistence.Id;
  3205. import javax.persistence.Table;
  3206.  
  3207. @Entity
  3208. @Table(name = "intervals")
  3209. public class Interval implements Serializable {
  3210.    
  3211.     private static final long serialVersionUID = -4187575836573185736L;
  3212.    
  3213.     private Integer intervals_id;
  3214.     private Integer fromInterval, toInterval;
  3215.     private Double price;
  3216.    
  3217.     @Column
  3218.     @Id
  3219.     @GeneratedValue
  3220.     public Integer getIntervals_id() {
  3221.         return intervals_id;
  3222.     }
  3223.  
  3224.     public void setIntervals_id(Integer intervals_id) {
  3225.         this.intervals_id = intervals_id;
  3226.     }
  3227.    
  3228.     @Column
  3229.     public Integer getFromInterval() {
  3230.         return fromInterval;
  3231.     }
  3232.  
  3233.     public void setFromInterval(Integer fromInterval) {
  3234.         this.fromInterval = fromInterval;
  3235.     }
  3236.  
  3237.     @Column
  3238.     public Integer getToInterval() {
  3239.         return toInterval;
  3240.     }
  3241.  
  3242.     public void setToInterval(Integer toInterval) {
  3243.         this.toInterval = toInterval;
  3244.     }
  3245.    
  3246.     @Column
  3247.     public Double getPrice() {
  3248.         return price;
  3249.     }
  3250.    
  3251.     public void setPrice(Double price) {
  3252.         this.price = price;
  3253.     }
  3254.    
  3255.     @Override
  3256.     public boolean equals(Object o){
  3257.         if(o != null && o instanceof Interval){
  3258.             if(intervals_id == ((Interval)o).getIntervals_id()){
  3259.                 return true;
  3260.             }
  3261.         }
  3262.         return false;
  3263.     }
  3264. }
  3265.  
  3266. ListBean
  3267.  
  3268. package net.peopleway.invoicesystem.pricelist;
  3269.  
  3270. import java.io.IOException;
  3271. import java.io.Serializable;
  3272. import java.util.ArrayList;
  3273. import java.util.List;
  3274.  
  3275. import javax.annotation.PostConstruct;
  3276. import javax.faces.application.FacesMessage;
  3277. import javax.faces.context.FacesContext;
  3278. import javax.faces.view.ViewScoped;
  3279. import javax.inject.Inject;
  3280. import javax.inject.Named;
  3281.  
  3282. import net.peopleway.invoicesystem.license.License;
  3283. import net.peopleway.invoicesystem.login.UserManager;
  3284.  
  3285. @Named
  3286. @ViewScoped
  3287. public class ListBean implements Serializable {
  3288.  
  3289.     private static final long serialVersionUID = 4995482822989124736L;
  3290.    
  3291.     @Inject
  3292.     private PricelistService service;
  3293.     @Inject private UserManager userManager;
  3294.    
  3295.     private List<License> licenses;
  3296.     private Pricelist list;
  3297.  
  3298.     @PostConstruct
  3299.     public void test() throws IOException {
  3300.         if(!userManager.getUser().isAdministrator()){
  3301.             FacesContext.getCurrentInstance().getExternalContext().redirect("/invoicesystem/customers");
  3302.         }else{
  3303.             list = new Pricelist();
  3304.             list.setIntervals(new ArrayList<Interval>());
  3305.             add();
  3306.             licenses = service.getLicenses();
  3307.         }
  3308.     }
  3309.    
  3310.     public List<License> getLicenses() {
  3311.         return licenses;
  3312.     }
  3313.  
  3314.     public Pricelist getList() {
  3315.         return list;
  3316.     }
  3317.    
  3318.     public List<Interval> getIntervals() {
  3319.         return list.getIntervals();
  3320.     }
  3321.    
  3322.     public Integer getSize() {
  3323.         return list.getIntervals().size();
  3324.     }
  3325.  
  3326.     public void add() {
  3327.         List<Interval> intervals = list.getIntervals();
  3328.         Interval interval = new Interval();
  3329.         Integer from = 1;
  3330.        
  3331.         if(!intervals.isEmpty()) {
  3332.             from = intervals.get(intervals.size() - 1).getFromInterval();
  3333.             from = (from != null ? from + 100 : null);
  3334.         }
  3335.        
  3336.         interval.setFromInterval(from);
  3337.         list.getIntervals().add(interval);
  3338.     }
  3339.  
  3340.     public void remove(Interval interval) {
  3341.         list.getIntervals().remove(interval);
  3342.     }
  3343.  
  3344.     public void save() {
  3345.         System.out.println(list.getStartdate());
  3346.         try {
  3347.             service.savePricelist(list);
  3348.         } catch (Exception e) {
  3349.             e.printStackTrace();
  3350.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  3351.         }
  3352.     }
  3353. }
  3354.  
  3355. Pricelist
  3356.  
  3357. package net.peopleway.invoicesystem.pricelist;
  3358.  
  3359. import java.io.Serializable;
  3360. import java.util.Date;
  3361. import java.util.List;
  3362.  
  3363. import javax.persistence.CascadeType;
  3364. import javax.persistence.Column;
  3365. import javax.persistence.Entity;
  3366. import javax.persistence.EnumType;
  3367. import javax.persistence.Enumerated;
  3368. import javax.persistence.GeneratedValue;
  3369. import javax.persistence.Id;
  3370. import javax.persistence.JoinColumn;
  3371. import javax.persistence.ManyToOne;
  3372. import javax.persistence.OneToMany;
  3373. import javax.persistence.Table;
  3374.  
  3375. import org.hibernate.annotations.LazyCollection;
  3376. import org.hibernate.annotations.LazyCollectionOption;
  3377.  
  3378. import net.peopleway.invoicesystem.license.License;
  3379. import net.peopleway.invoicesystem.subscription.State;
  3380.  
  3381. @Entity
  3382. @Table(name = "pricelist")
  3383. public class Pricelist implements Serializable {
  3384.     private int pricelist_id;
  3385.     private String title;
  3386.     private Date startdate, enddate;
  3387.     private List<Interval> intervals;
  3388.     private License license;
  3389.  
  3390.     @Id
  3391.     @GeneratedValue
  3392.     @Column
  3393.     public int getPricelist_id() {
  3394.         return pricelist_id;
  3395.     }
  3396.  
  3397.     public void setPricelist_id(int pricelist_id) {
  3398.         this.pricelist_id = pricelist_id;
  3399.     }
  3400.  
  3401.     @Column
  3402.     public String getTitle() {
  3403.         return title;
  3404.     }
  3405.  
  3406.     public void setTitle(String title) {
  3407.         this.title = title;
  3408.     }
  3409.  
  3410.     @Column
  3411.     public Date getStartdate() {
  3412.         return startdate;
  3413.     }
  3414.  
  3415.     public void setStartdate(Date startdate) {
  3416.         this.startdate = startdate;
  3417.     }
  3418.  
  3419.     @Column
  3420.     public Date getEnddate() {
  3421.         return enddate;
  3422.     }
  3423.  
  3424.     public void setEnddate(Date enddate) {
  3425.         this.enddate = enddate;
  3426.     }
  3427.  
  3428.     @LazyCollection(LazyCollectionOption.FALSE)
  3429.     @OneToMany(cascade = CascadeType.ALL)
  3430.     @JoinColumn(name = "pricelist_id")
  3431.     public List<Interval> getIntervals() {
  3432.         return intervals;
  3433.     }
  3434.  
  3435.     public void setIntervals(List<Interval> intervals) {
  3436.         this.intervals = intervals;
  3437.     }
  3438.  
  3439.     @LazyCollection(LazyCollectionOption.FALSE)
  3440.     @ManyToOne
  3441.     @JoinColumn(name = "license_id")
  3442.     public License getLicense() {
  3443.         return license;
  3444.     }
  3445.  
  3446.     public void setLicense(License license) {
  3447.         this.license = license;
  3448.     }
  3449.  
  3450.     @Override
  3451.     public boolean equals(Object o) {
  3452.         if (o != null && o instanceof Pricelist) {
  3453.             if (((Pricelist) o).getPricelist_id() == pricelist_id) {
  3454.                 return true;
  3455.             }
  3456.         }
  3457.         return false;
  3458.     }
  3459.  
  3460. }
  3461.  
  3462. PricelistDao
  3463.  
  3464. package net.peopleway.invoicesystem.pricelist;
  3465.  
  3466. import java.io.Serializable;
  3467. import java.util.List;
  3468.  
  3469. import javax.enterprise.context.ApplicationScoped;
  3470. import javax.inject.Named;
  3471.  
  3472. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  3473. import net.peopleway.invoicesystem.license.License;
  3474. import net.peopleway.invoicesystem.product.Product;
  3475. import net.peopleway.invoicesystem.subscription.Subscription;
  3476.  
  3477. import org.hibernate.Criteria;
  3478. import org.hibernate.Hibernate;
  3479. import org.hibernate.Session;
  3480. import org.hibernate.Transaction;
  3481. import org.hibernate.criterion.Restrictions;
  3482.  
  3483. @Named
  3484. @ApplicationScoped
  3485. public class PricelistDao implements Serializable {
  3486.  
  3487.     private static PricelistDao dao;
  3488.  
  3489.     public List<License> getLicenses() {
  3490.         Session session = (Session) DatabaseSessionFactory.getSession();
  3491.         Transaction t = session.beginTransaction();
  3492.         Criteria c = session.createCriteria(License.class);
  3493.         List<License> licenses = c.list();
  3494.         t.commit();
  3495.         return licenses;
  3496.     }
  3497.  
  3498.     public void savePriceList(Pricelist newPricelist) {
  3499.         Session session = (Session) DatabaseSessionFactory.getSession();
  3500.         Transaction t = session.beginTransaction();
  3501.         session.save(newPricelist);
  3502.         t.commit();
  3503.     }
  3504. }
  3505.  
  3506. PricelistService
  3507.  
  3508. package net.peopleway.invoicesystem.pricelist;
  3509.  
  3510. import java.io.Serializable;
  3511. import java.util.Collections;
  3512. import java.util.Comparator;
  3513. import java.util.List;
  3514.  
  3515. import javax.enterprise.context.ApplicationScoped;
  3516. import javax.inject.Inject;
  3517. import javax.inject.Named;
  3518.  
  3519. import net.peopleway.invoicesystem.license.License;
  3520.  
  3521. @Named
  3522. @ApplicationScoped
  3523. public class PricelistService implements Serializable {
  3524.     @Inject
  3525.     private PricelistDao dao;
  3526.  
  3527.     public List<License> getLicenses() {
  3528.         return dao.getLicenses();
  3529.     }
  3530.  
  3531.     public void savePricelist(Pricelist newPricelist) throws Exception {
  3532.         if (newPricelist != null) {
  3533.             List<Interval> intervals = newPricelist.getIntervals();
  3534.             Interval prev = null;
  3535.            
  3536.             if(intervals.get(0).getFromInterval() != 1) {
  3537.                 throw new RuntimeException("First interval must start from 1!");
  3538.             }
  3539.             int start = 0;
  3540.             for(Interval interval : newPricelist.getIntervals()) {
  3541.                 if(1 >= interval.getFromInterval()){
  3542.                     throw new Exception("The value cannot be less than 1");
  3543.                 }
  3544.                 if(start >= interval.getFromInterval()){
  3545.                     throw new Exception("There is intervals with a start value that is lower or equal to the previos intervals start value: "+start);
  3546.                 }
  3547.                 start = interval.getFromInterval();
  3548.                 if(interval.getPrice() == null) {
  3549.                     throw new RuntimeException("There intervals with empty price!");
  3550.                 }
  3551.                
  3552.                 if(interval.getFromInterval() == null) {
  3553.                     throw new RuntimeException("There empty intervals!");
  3554.                 }
  3555.                
  3556.                 if(prev != null && interval.getFromInterval() < prev.getFromInterval()) {
  3557.                     throw new RuntimeException("There are overlapping intervals!");
  3558.                 }
  3559.                
  3560.                 if(prev != null) {
  3561.                     prev.setToInterval(interval.getFromInterval() - 1);
  3562.                 }
  3563.                    
  3564.                 prev = interval;
  3565.             }
  3566.  
  3567.             intervals.get(intervals.size() - 1).setToInterval(Integer.MAX_VALUE);
  3568.             dao.savePriceList(newPricelist);
  3569.         }
  3570.     }
  3571.  
  3572.     public PricelistDao getDao() {
  3573.         return dao;
  3574.     }
  3575.  
  3576.     public void setDao(PricelistDao dao) {
  3577.         this.dao = dao;
  3578.     }
  3579.    
  3580.    
  3581. }
  3582.  
  3583. product
  3584.  
  3585. package net.peopleway.invoicesystem.product;
  3586.  
  3587. import java.io.Serializable;
  3588. import java.util.Date;
  3589.  
  3590. import javax.persistence.CascadeType;
  3591. import javax.persistence.Column;
  3592. import javax.persistence.Entity;
  3593. import javax.persistence.EnumType;
  3594. import javax.persistence.Enumerated;
  3595. import javax.persistence.GeneratedValue;
  3596. import javax.persistence.Id;
  3597. import javax.persistence.JoinColumn;
  3598. import javax.persistence.ManyToOne;
  3599. import javax.persistence.OneToOne;
  3600. import javax.persistence.Table;
  3601.  
  3602. import org.hibernate.annotations.LazyCollection;
  3603. import org.hibernate.annotations.LazyCollectionOption;
  3604.  
  3605. import net.peopleway.invoicesystem.extra.Extra;
  3606. import net.peopleway.invoicesystem.invoice.InvoiceInterval;
  3607. import net.peopleway.invoicesystem.license.License;
  3608. import net.peopleway.invoicesystem.subscription.Subscription;
  3609.  
  3610. @Entity
  3611. @Table(name="product")
  3612. public class Product implements Serializable, Comparable<Product>{
  3613.     private static final long serialVersionUID = 1L;
  3614.     private int product_id;
  3615.     private Subscription subscription;
  3616.    
  3617.     private Double discount;
  3618.    
  3619.     private Date startDate, endDate, resignationDate, indexFreeze;
  3620.    
  3621.     private InvoiceInterval periodInterval;
  3622.    
  3623.     private Double price;
  3624.    
  3625.     private License license;
  3626.    
  3627.     private Extra extra;
  3628.    
  3629.     public Product() {
  3630.     }
  3631.    
  3632.     @Id
  3633.     @GeneratedValue
  3634.     @Column
  3635.     public int getProduct_id() {
  3636.         return product_id;
  3637.     }
  3638.  
  3639.     public void setProduct_id(int product_id) {
  3640.         this.product_id = product_id;
  3641.     }
  3642.    
  3643.     @LazyCollection(LazyCollectionOption.FALSE)
  3644.     @ManyToOne(optional = false, cascade=CascadeType.ALL)
  3645.     @JoinColumn(name = "subscription_id")
  3646.     public Subscription getSubscription() {
  3647.         return subscription;
  3648.     }
  3649.     public void setSubscription(Subscription subscription) {
  3650.         this.subscription = subscription;
  3651.     }
  3652.  
  3653.     @Column
  3654.     public Date getStartDate() {
  3655.         return startDate;
  3656.     }
  3657.  
  3658.     public void setStartDate(Date startDate) {
  3659.         this.startDate = startDate;
  3660.     }
  3661.  
  3662.     @Column
  3663.     public Date getEndDate() {
  3664.         return endDate;
  3665.     }
  3666.  
  3667.     public void setEndDate(Date endDate) {
  3668.         this.endDate = endDate;
  3669.     }
  3670.  
  3671.     @Column
  3672.     public Date getResignationDate() {
  3673.         return resignationDate;
  3674.     }
  3675.  
  3676.     public void setResignationDate(Date resignationDate) {
  3677.         this.resignationDate = resignationDate;
  3678.     }
  3679.  
  3680.     @Enumerated(EnumType.STRING)
  3681.     public InvoiceInterval getPeriodInterval() {
  3682.         return periodInterval;
  3683.     }
  3684.  
  3685.     public void setPeriodInterval(InvoiceInterval periodInterval) {
  3686.         this.periodInterval = periodInterval;
  3687.     }
  3688.  
  3689.     @Override
  3690.     public String toString() {
  3691.         if(license != null){
  3692.             return license.getTitle();
  3693.         }
  3694.         else if(extra != null){
  3695.             return extra.getTitle();
  3696.         }
  3697.         else{
  3698.             return "No License or Extra";
  3699.         }
  3700.     }
  3701.     @Override
  3702.     public boolean equals(Object obj) {
  3703.         if (this == obj)
  3704.             return true;
  3705.         if (obj == null)
  3706.             return false;
  3707.         if (getClass() != obj.getClass())
  3708.             return false;
  3709.         Product other = (Product) obj;
  3710.         if (product_id != other.product_id)
  3711.             return false;
  3712.         return true;
  3713.     }
  3714.     @Override
  3715.     public int compareTo(Product o) {
  3716.         if(this.product_id == o.getProduct_id()){
  3717.             return 0;
  3718.         }
  3719.         else if(this.product_id > o.getProduct_id()){
  3720.             return 1;
  3721.         }
  3722.         else{
  3723.             return -1;
  3724.         }
  3725.     }
  3726.  
  3727.     @Column
  3728.     public Double getPrice() {
  3729.         return price;
  3730.     }
  3731.  
  3732.     public void setPrice(Double price) {
  3733.         this.price = price;
  3734.     }
  3735.  
  3736.     @Column
  3737.     public Double getDiscount() {
  3738.         return discount;
  3739.     }
  3740.  
  3741.     public void setDiscount(Double discount) {
  3742.         this.discount = discount;
  3743.     }
  3744.  
  3745.     @LazyCollection(LazyCollectionOption.FALSE)
  3746.     @OneToOne
  3747.     @JoinColumn(name = "license_id", nullable= true)
  3748.     public License getLicense() {
  3749.         return license;
  3750.     }
  3751.  
  3752.     public void setLicense(License license) {
  3753.         this.license = license;
  3754.     }
  3755.    
  3756.     @LazyCollection(LazyCollectionOption.FALSE)
  3757.     @OneToOne
  3758.     @JoinColumn(name = "extra_id", nullable = true)
  3759.     public Extra getExtra() {
  3760.         return extra;
  3761.     }
  3762.    
  3763.     public void setExtra(Extra extra) {
  3764.         this.extra = extra;
  3765.     }
  3766.  
  3767.     @Column
  3768.     public Date getIndexFreeze() {
  3769.         return indexFreeze;
  3770.     }
  3771.  
  3772.     public void setIndexFreeze(Date indexFreeze) {
  3773.         this.indexFreeze = indexFreeze;
  3774.     }
  3775. }
  3776.  
  3777. ProductBean
  3778.  
  3779. package net.peopleway.invoicesystem.product;
  3780.  
  3781. import java.io.IOException;
  3782. import java.io.Serializable;
  3783. import java.sql.SQLException;
  3784. import java.util.ArrayList;
  3785. import java.util.List;
  3786.  
  3787. import javax.faces.application.FacesMessage;
  3788. import javax.faces.context.FacesContext;
  3789. import javax.faces.view.ViewScoped;
  3790. import javax.inject.Inject;
  3791. import javax.inject.Named;
  3792.  
  3793. import net.peopleway.invoicesystem.customer.Customer;
  3794. import net.peopleway.invoicesystem.customer.CustomerService;
  3795. import net.peopleway.invoicesystem.license.License;
  3796. import net.peopleway.invoicesystem.login.LoginService;
  3797. import net.peopleway.invoicesystem.login.UserManager;
  3798. import net.peopleway.invoicesystem.subscription.Subscription;
  3799. import net.peopleway.invoicesystem.subscription.SubscriptionService;
  3800.  
  3801.  
  3802. @Named
  3803. @ViewScoped
  3804. public class ProductBean implements Serializable{
  3805.     @Inject private SubscriptionService ss;
  3806.     @Inject private UserManager userManager;
  3807.     @Inject private LoginService loginService;
  3808.     @Inject private CustomerService customerService;
  3809.    
  3810.    
  3811.     private List<Subscription> subscriptions = new ArrayList<Subscription>();
  3812.     private List<Product> products;
  3813.     private List<License> licenses;
  3814.     private Subscription selectedSubscription;
  3815.     private Customer selectedCustomer;
  3816.     private Product selectedProduct;
  3817.     private License selectedLicense;
  3818.     private boolean subDetails;
  3819.     private boolean productDetails;
  3820.     private boolean createProduct;
  3821.     private boolean editProductSave;
  3822.     private boolean productgroup;
  3823.     private boolean addButton;
  3824.     private Product newProduct;
  3825.    
  3826.    
  3827.     public void logout() throws IOException{
  3828.         loginService.destroyUserToken(userManager.getUser());
  3829.         userManager.setUser(null);
  3830.         FacesContext.getCurrentInstance().getExternalContext().redirect("/invoicesystem/login");
  3831.     }
  3832.    
  3833.     public void renderSubDetails(){
  3834.         if(selectedCustomer != null && selectedSubscription != null){
  3835.             subDetails = true;
  3836.             products = selectedSubscription.getProducts();
  3837.         }else{
  3838.             subDetails = false;
  3839.         }
  3840.     }
  3841.     public void renderProductDetails(){
  3842.         if(selectedProduct != null){
  3843.             newProduct = selectedProduct;
  3844.             createProduct = false;
  3845.             productDetails = true;
  3846.         }else{
  3847.             productDetails = false;
  3848.             editProductSave = false;
  3849.             productgroup = false;
  3850.         }
  3851.         addButton = false;
  3852.     }
  3853.     public void addProduct(){
  3854.         newProduct = new Product();
  3855.         productDetails = true;
  3856.         createProduct = true;
  3857.         addButton = true;
  3858.         productgroup = false;
  3859.         editProductSave = false;
  3860.     }
  3861.     public void createNewProduct() throws Exception{
  3862.         if(!selectedSubscription.getSubstate().toString().toLowerCase().equals("active")){
  3863.             if(newProduct.getDiscount() != null && newProduct.getLicense() != null && newProduct.getPrice() != null){
  3864.                 ss.createNewProduct(newProduct, selectedSubscription);
  3865.             }else{
  3866.                 FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Fill out all blanks","Fill out all blanks"));
  3867.             }
  3868.         }else{
  3869.             FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Cannot add product to active subscription","Cannot add product to active subscription"));
  3870.         }
  3871.     }
  3872.     public void deleteProduct(){
  3873.         if(selectedProduct != null && !selectedSubscription.toString().toLowerCase().equals("active")){
  3874.             ss.deleteLicenseSubscription(selectedProduct);
  3875.             products = ss.getProductsSub(selectedSubscription);
  3876.             productDetails = false;
  3877.         }
  3878.     }
  3879.     public void editProduct(){
  3880.         if(selectedProduct != null){
  3881.             newProduct = selectedProduct;
  3882.             editProductSave = true;
  3883.             createProduct = true;
  3884.             addButton = false;
  3885.             selectedLicense = newProduct.getLicense();
  3886.         }
  3887.     }
  3888.     public void editOldProduct(){
  3889.         if(selectedProduct != null)
  3890.         ss.editProduct(newProduct);
  3891.     }
  3892.    
  3893.  
  3894.     public boolean isAddButton() {
  3895.         return addButton;
  3896.     }
  3897.  
  3898.     public void setAddButton(boolean addButton) {
  3899.         this.addButton = addButton;
  3900.     }
  3901.  
  3902.    
  3903.  
  3904.     public boolean isProductgroup() {
  3905.         return productgroup;
  3906.     }
  3907.  
  3908.     public void setProductgroup(boolean productgroup) {
  3909.         this.productgroup = productgroup;
  3910.     }
  3911.  
  3912.  
  3913.     public boolean isEditProductSave() {
  3914.         return editProductSave;
  3915.     }
  3916.  
  3917.     public void setEditProductSave(boolean editProductSave) {
  3918.         this.editProductSave = editProductSave;
  3919.     }
  3920.  
  3921.     public Product getNewProduct() {
  3922.         return newProduct;
  3923.     }
  3924.  
  3925.     public void setNewProduct(Product newProduct) {
  3926.         this.newProduct = newProduct;
  3927.     }
  3928.  
  3929.     public boolean isCreateProduct() {
  3930.         return createProduct;
  3931.     }
  3932.  
  3933.     public void setCreateProduct(boolean createProduct) {
  3934.         this.createProduct = createProduct;
  3935.     }
  3936.  
  3937.     public boolean isProductDetails() {
  3938.         return productDetails;
  3939.     }
  3940.  
  3941.     public void setProductDetails(boolean productDetails) {
  3942.         this.productDetails = productDetails;
  3943.     }
  3944.  
  3945.     public boolean isSubDetails() {
  3946.         return subDetails;
  3947.     }
  3948.     public void setSubDetails(boolean subDetails) {
  3949.         this.subDetails = subDetails;
  3950.     }
  3951.     public List<Product> getProducts() {
  3952.         return products;
  3953.     }
  3954.     public void setProducts(List<Product> products) {
  3955.         this.products = products;
  3956.     }
  3957.     public Product getSelectedProduct() {
  3958.         return selectedProduct;
  3959.     }
  3960.     public void setSelectedProduct(Product selectedProduct) {
  3961.         this.selectedProduct = selectedProduct;
  3962.     }
  3963.     public Customer getSelectedCustomer() {
  3964.         return selectedCustomer;
  3965.     }
  3966.     public void setSelectedCustomer(Customer selectedCustomer) {
  3967.         this.selectedCustomer = selectedCustomer;
  3968.     }
  3969.     public List<Subscription> getSubscriptions() {
  3970.         return subscriptions;
  3971.     }
  3972.     public void setSubscriptions(List<Subscription> subscriptions) {
  3973.         this.subscriptions = subscriptions;
  3974.     }
  3975.    
  3976.     public Subscription getSelectedSubscription() {
  3977.         return selectedSubscription;
  3978.     }
  3979.     public void setSelectedSubscription(Subscription selectedSubscription) {
  3980.         this.selectedSubscription = selectedSubscription;
  3981.     }
  3982.     public void load() throws IOException, ClassNotFoundException, SQLException{
  3983.         if(selectedCustomer != null){
  3984.             subscriptions = ss.getCustSubs(selectedCustomer);
  3985.         }else{
  3986.             for(Customer c : customerService.getCustomers()){
  3987.                 if(c.getUser().equals(userManager.getUser())){
  3988.                     selectedCustomer = c;
  3989.                     subscriptions.addAll(ss.getCustSubs(c));
  3990.                 }else{
  3991.                     FacesContext.getCurrentInstance().getExternalContext().redirect("/invoicesystem/consultant");
  3992.                 }
  3993.             }
  3994.         }
  3995.         licenses = ss.getLicenses();
  3996.        
  3997.     }
  3998.    
  3999. }
  4000.  
  4001. ProductConverter
  4002.  
  4003. package net.peopleway.invoicesystem.product;
  4004.  
  4005. import javax.enterprise.context.ApplicationScoped;
  4006. import javax.faces.component.UIComponent;
  4007. import javax.faces.context.FacesContext;
  4008. import javax.faces.convert.Converter;
  4009. import javax.inject.Inject;
  4010. import javax.inject.Named;
  4011.  
  4012. import net.peopleway.invoicesystem.subscription.SubscriptionService;
  4013.  
  4014. @Named
  4015. @ApplicationScoped
  4016. public class ProductConverter implements Converter{
  4017.         @Inject
  4018.         private SubscriptionService ss;
  4019.  
  4020.         @Override
  4021.         public Object getAsObject(FacesContext context, UIComponent component, String value) {
  4022.             if (value == null) {
  4023.                 return null;
  4024.             }
  4025.            
  4026.                 for (Product c : ss.getProducts()) {
  4027.                     if (c.getProduct_id()== Integer.parseInt(value)) {
  4028.                         return c;
  4029.                     }
  4030.                 }
  4031.            
  4032.             return null;
  4033.         }
  4034.  
  4035.         @Override
  4036.         public String getAsString(FacesContext context, UIComponent component, Object value) {
  4037.             if (value == null)
  4038.                 return "";
  4039.  
  4040.             return Integer.toString(((Product) value).getProduct_id());
  4041.         }
  4042. }
  4043.  
  4044. Template
  4045.  
  4046. package net.peopleway.invoicesystem.product;
  4047.  
  4048. import java.util.List;
  4049.  
  4050. import javax.persistence.CascadeType;
  4051. import javax.persistence.Column;
  4052. import javax.persistence.Entity;
  4053. import javax.persistence.GeneratedValue;
  4054. import javax.persistence.Id;
  4055. import javax.persistence.JoinColumn;
  4056. import javax.persistence.JoinTable;
  4057. import javax.persistence.ManyToMany;
  4058. import javax.persistence.ManyToOne;
  4059. import javax.persistence.Table;
  4060.  
  4061. import net.peopleway.invoicesystem.extra.Extra;
  4062. import net.peopleway.invoicesystem.license.License;
  4063.  
  4064. import org.hibernate.annotations.LazyCollection;
  4065. import org.hibernate.annotations.LazyCollectionOption;
  4066.  
  4067. @Entity
  4068. @Table(name="template")
  4069. public class Template {
  4070.     private int template_id;
  4071.     private String title;
  4072.     private License license;
  4073.     private List<Extra> extras;
  4074.    
  4075.     @Id
  4076.     @GeneratedValue
  4077.     @Column
  4078.     public int getTemplate_id() {
  4079.         return template_id;
  4080.     }
  4081.     public void setTemplate_id(int template_id) {
  4082.         this.template_id = template_id;
  4083.     }
  4084.    
  4085.     @Column
  4086.     public String getTitle() {
  4087.         return title;
  4088.     }
  4089.     public void setTitle(String title) {
  4090.         this.title = title;
  4091.     }
  4092.    
  4093.     @LazyCollection(LazyCollectionOption.FALSE)
  4094.     @ManyToOne
  4095.     @JoinColumn(name = "license_id")
  4096.     public License getLicense() {
  4097.         return license;
  4098.     }
  4099.     public void setLicense(License license) {
  4100.         this.license = license;
  4101.     }
  4102.    
  4103.     @LazyCollection(LazyCollectionOption.FALSE)
  4104.     @ManyToMany(cascade= CascadeType.ALL)
  4105.     @JoinTable(name = "templateExtras", joinColumns = @JoinColumn(name = "template_id"))
  4106.     public List<Extra> getExtras() {
  4107.         return extras;
  4108.     }
  4109.     public void setExtras(List<Extra> extras) {
  4110.         this.extras = extras;
  4111.     }
  4112. }
  4113.  
  4114. package net.peopleway.invoicesystem.rewrite;
  4115.  
  4116. ConfigurationProvider
  4117.  
  4118. package net.peopleway.invoicesystem.rewrite;
  4119.  
  4120. import javax.servlet.ServletContext;
  4121.  
  4122. import org.ocpsoft.rewrite.annotation.RewriteConfiguration;
  4123. import org.ocpsoft.rewrite.config.Configuration;
  4124. import org.ocpsoft.rewrite.config.ConfigurationBuilder;
  4125. import org.ocpsoft.rewrite.servlet.config.HttpConfigurationProvider;
  4126. import org.ocpsoft.rewrite.servlet.config.rule.Join;
  4127.  
  4128. @RewriteConfiguration
  4129. public class ConfigurationProvider extends HttpConfigurationProvider {
  4130.     @Override
  4131.     public int priority() {
  4132.         return 10;
  4133.     }
  4134.  
  4135.     @Override
  4136.     public Configuration getConfiguration(final ServletContext context) {
  4137.         return ConfigurationBuilder.begin()
  4138.                 .addRule(Join.path("/login").to("/public/login.xhtml"))
  4139.                 .addRule(Join.path("/subscriptionmanagement").to("/private/SubStart.xhtml"))
  4140.                 .addRule(Join.path("/subscription").to("/private/subscription.xhtml"))
  4141.                 .addRule(Join.path("/customers").to("/private/customers.xhtml"))
  4142.                 .addRule(Join.path("/customer").to("/private/customer.xhtml"))
  4143.                 .addRule(Join.path("/users").to("/private/adminUserManagement.xhtml"))
  4144.                 .addRule(Join.path("/newLicense").to("/private/licenseNew.xhtml"))
  4145.                 .addRule(Join.path("/newExtra").to("/private/extraNew.xhtml"))
  4146.                 .addRule(Join.path("/newPricelist").to("/private/pricelistNew.xhtml"))
  4147.                 .addRule(Join.path("/priceCalculator").to("/private/priceCalculator.xhtml"))
  4148.                 .addRule(Join.path("/updatePrices").to("/private/pricesUpdateIndex.xhtml"));       
  4149.     }
  4150. }
  4151.  
  4152. package net.peopleway.invoicesystem.server;
  4153.  
  4154.  
  4155. InvoiceThread
  4156.  
  4157. package net.peopleway.invoicesystem.server;
  4158.  
  4159. import java.util.Calendar;
  4160. import java.util.Date;
  4161. import java.util.List;
  4162. import java.util.TimeZone;
  4163. import java.util.TreeMap;
  4164.  
  4165. import net.peopleway.invoicesystem.product.Product;
  4166. import net.peopleway.invoicesystem.utilities.DateUtilities;
  4167.  
  4168. public class InvoiceThread extends Thread {
  4169.     private TreeMap<Date, List<Product>> invoices;
  4170.     public InvoiceThread(){
  4171.         invoices = new TreeMap<Date, List<Product>>();
  4172.     }
  4173.    
  4174.     public void run(){
  4175.         boolean run = true;
  4176.        
  4177.         while(run){
  4178.             long sleepTime = DateUtilities.timeUntilNextWakeUp(new Date());
  4179.             try {
  4180.                 Thread.sleep(sleepTime);
  4181.             } catch (InterruptedException e) {
  4182.                 e.printStackTrace();
  4183.             }
  4184.         }
  4185.     }
  4186.    
  4187.     public void startUp(){
  4188.         this.start();
  4189.     }
  4190.    
  4191.     public static void main(String[] args) {
  4192.         InvoiceThread thread = new InvoiceThread();
  4193.         thread.startUp();
  4194.     }
  4195. }
  4196.  
  4197. package net.peopleway.invoicesystem.serverstartup;
  4198.  
  4199.  
  4200. InvoiceStartUpListener
  4201.  
  4202. package net.peopleway.invoicesystem.serverstartup;
  4203.  
  4204. import javax.servlet.ServletContextEvent;
  4205. import javax.servlet.ServletContextListener;
  4206.  
  4207. import net.peopleway.invoicesystem.hibernate.DatabaseSessionFactory;
  4208. import net.peopleway.invoicesystem.server.InvoiceThread;
  4209.  
  4210.  
  4211. public class InvoiceStartUpListener implements ServletContextListener{
  4212.    
  4213.  
  4214.     @Override
  4215.     public void contextDestroyed(ServletContextEvent arg0) {
  4216.        
  4217.     }
  4218.  
  4219.     @Override
  4220.     public void contextInitialized(ServletContextEvent arg0) {
  4221.         DatabaseSessionFactory.configure();
  4222.         InvoiceThread thread = new InvoiceThread();
  4223.         thread.startUp();
  4224.     }
  4225.  
  4226.    
  4227.    
  4228. }
  4229.  
  4230. package net.peopleway.invoicesystem.subscription;
  4231.  
  4232.  
  4233. NewSubscriptionBean
  4234.  
  4235. package net.peopleway.invoicesystem.subscription;
  4236.  
  4237. import java.io.IOException;
  4238. import java.io.Serializable;
  4239. import java.util.ArrayList;
  4240. import java.util.Date;
  4241. import java.util.List;
  4242.  
  4243. import javax.faces.application.FacesMessage;
  4244. import javax.faces.context.FacesContext;
  4245. import javax.faces.view.ViewScoped;
  4246. import javax.inject.Inject;
  4247. import javax.inject.Named;
  4248.  
  4249. import net.peopleway.invoicesystem.customer.Customer;
  4250. import net.peopleway.invoicesystem.customer.CustomerService;
  4251. import net.peopleway.invoicesystem.extra.Extra;
  4252. import net.peopleway.invoicesystem.extra.ExtraService;
  4253. import net.peopleway.invoicesystem.invoice.InvoiceInterval;
  4254. import net.peopleway.invoicesystem.license.License;
  4255. import net.peopleway.invoicesystem.login.UserManager;
  4256. import net.peopleway.invoicesystem.product.Product;
  4257.  
  4258. import org.omnifaces.util.Faces;
  4259.  
  4260. @Named
  4261. @ViewScoped
  4262. public class NewSubscriptionBean implements Serializable{
  4263.    
  4264.     private static final long serialVersionUID = 8327353921900478821L;
  4265.     private String name;
  4266.     private List<Product> products;
  4267.  
  4268.     private Customer customer;
  4269.     private int dateInterval;
  4270.     private State substate;
  4271.     private Date creationdate;
  4272.     private Date indexFreeze;
  4273.     private InvoiceInterval paymentDelay;
  4274.     private int id;
  4275.     private int customerId;
  4276.    
  4277.     private Product selectedProduct;
  4278.     private License selectedLicense;
  4279.     private List<License> availableLicenses;
  4280.     private List<String> periodintervals = new ArrayList<String>();
  4281.     private List<String> periodintervalsProduct = new ArrayList<String>();
  4282.     private List<Extra> availableExtras = new ArrayList<Extra>();
  4283.     private Extra selectedExtra;
  4284.     private String selectedTitle;
  4285.     private Double discount;
  4286.     private Date resignationDate;
  4287.     private Date startDate;
  4288.     private String periodInterval;
  4289.     private String periodIntervalSub;
  4290.     private Double price;
  4291.     private Subscription s;
  4292.     private String deleteSubString;
  4293.     private boolean viewProduct;
  4294.    
  4295.     private boolean newSub;
  4296.     private Product newProduct;
  4297.     private boolean editing;
  4298.     @Inject private SubscriptionService ss;
  4299.     @Inject private CustomerService cs;
  4300.     @Inject private UserManager userManager;
  4301.     @Inject private ExtraService es;
  4302.    
  4303.     public void load() throws IOException {
  4304.         if(customerId != 0 && id == 0 && checkcustomerid() == true){
  4305.             products = new ArrayList<Product>();
  4306.             customer = cs.getCustomerById(customerId);
  4307.             s = new Subscription();
  4308.             newSub = true;
  4309.             periodIntervalSub = "None";
  4310.             deleteSubString = "Cancel";
  4311.         }else if(id != 0 && checksubscriptionid() == true){
  4312.             Subscription sub = ss.getSubscriptionById(id);
  4313.             customer = sub.getCustomer();
  4314.             dateInterval = sub.getDateInterval();
  4315.             substate = sub.getSubstate();
  4316.             creationdate = sub.getCreationDate();
  4317.             paymentDelay = sub.getPaymentDelay();
  4318.             name = sub.getName();
  4319.             products = sub.getProducts();
  4320.             newSub = false;
  4321.             deleteSubString ="Delete subscription";
  4322.         }else{
  4323.             Faces.redirect("customers");
  4324.         }
  4325.         availableLicenses = ss.getLicenses();
  4326.         availableExtras = es.getExtras();
  4327.         periodintervals.add("None");
  4328.         periodintervals.add("Days");
  4329.         periodintervals.add("Weeks");
  4330.         periodintervals.add("Months");
  4331.         periodintervals.add("Years");
  4332.         periodintervals.add("Quarters");
  4333.        
  4334.         periodintervalsProduct.add("Daily");
  4335.         periodintervalsProduct.add("Weekly");
  4336.         periodintervalsProduct.add("Monthly");
  4337.         periodintervalsProduct.add("Quarterly");
  4338.         periodintervalsProduct.add("Yearly");
  4339.         editing = false;
  4340.        
  4341.     }
  4342.     public String back(){
  4343.         return "customers.xhtml?faces-redirect=true";
  4344.     }
  4345.    
  4346.     public void deleteProduct(){
  4347.         if(id != 0){
  4348.             ss.deleteLicenseSubscription(selectedProduct);
  4349.             products = ss.getSubscriptionById(id).getProducts();
  4350.         }else{
  4351.             products.remove(selectedProduct);
  4352.         }
  4353.     }
  4354.    
  4355.    
  4356.     public boolean checkcustomerid(){
  4357.         for(Customer c : cs.getCustomersUser(userManager.getUser())){
  4358.             if(c.getCustomer_id() == customerId){
  4359.                 return true;
  4360.             }
  4361.         }
  4362.         return false;
  4363.        
  4364.     }
  4365.     public boolean checksubscriptionid(){
  4366.         for(Customer c : cs.getCustomersUser(userManager.getUser())){
  4367.             for(Subscription s : c.getSubscriptions()){
  4368.                 if(s.getSubscription_id() == id){
  4369.                     return true;
  4370.                 }
  4371.             }
  4372.         }
  4373.         return false;
  4374.     }
  4375.     public void createSubscription() throws Exception{
  4376.         if(!name.isEmpty()){
  4377.             //TODO relog side med nye sub id?
  4378.             s.setCustomer(customer);
  4379.             s.setName(name);
  4380.             s.setCreationDate(new Date());
  4381.             s.setPaymentDelay(checkInterval(periodIntervalSub));
  4382.             s.setDateInterval(dateInterval);
  4383.             ss.createSub(s);
  4384.             for(Product p : products){
  4385.                 ss.createNewProduct(p, s);
  4386.             }
  4387.            
  4388.             deleteSubString = "Delete Subscription";
  4389.             Faces.redirect("customers");
  4390.         }
  4391.         else{
  4392.             FacesContext.getCurrentInstance().addMessage("subname",new FacesMessage(FacesMessage.SEVERITY_WARN,"Name is required","Name is required"));
  4393.         }
  4394.     }
  4395.    
  4396.     public void viewProduct(){
  4397.         viewProduct = true;
  4398.         price = selectedProduct.getPrice();
  4399.         discount = selectedProduct.getDiscount();
  4400.         startDate = selectedProduct.getStartDate();
  4401.         resignationDate = selectedProduct.getResignationDate();
  4402.         periodInterval = selectedProduct.getPeriodInterval().toString();
  4403.     }
  4404.    
  4405. //  public void edit() {
  4406. //      editing = true;
  4407. //      selectedGroupProduct = selectedProduct.getGroupProduct();
  4408. //      selectedTitle = selectedProduct.getTitle();
  4409. //      discount = selectedProduct.getDiscount();
  4410. //      resignationDate = selectedProduct.getResignationDate();
  4411. //      startDate = selectedProduct.getStartDate();
  4412. //      periodInterval = selectedProduct.getPeriodInterval().toString();
  4413. //  }
  4414.    
  4415.     public void newProduct(){
  4416.         viewProduct = false;
  4417.         price = 0.0;
  4418.         discount = 0.0;
  4419.         editing = false;
  4420.         selectedLicense = null;
  4421.         selectedExtra = null;
  4422.         selectedTitle = null;
  4423.         discount = null;
  4424.         resignationDate = null;
  4425.         startDate = null;
  4426.         periodInterval = null;
  4427.     }
  4428.    
  4429.    
  4430.     public void addProduct() throws Exception{
  4431.         newProduct = new Product();
  4432.         Double d = 0.0;
  4433.         if(discount == null){
  4434.             discount = 0.0;
  4435.         }
  4436.         try{
  4437.             newProduct.setDiscount(discount);
  4438.             if(selectedExtra != null && selectedLicense == null){
  4439.                 d = selectedExtra.getPrice() - (selectedExtra.getPrice() * (discount/100));
  4440.                 newProduct.setExtra(selectedExtra);
  4441.             } else if(selectedLicense != null && selectedExtra == null){
  4442.                 d = selectedLicense.getPrice() - (selectedLicense.getPrice() * (discount/100));
  4443.                 newProduct.setLicense(selectedLicense);
  4444.             }else if((selectedLicense != null && selectedExtra != null)|| (selectedLicense == null && selectedExtra == null)){
  4445.                 throw new Exception("Must choose between license or extra");
  4446.             }
  4447.         }
  4448.         catch(Exception e){
  4449.             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  4450.             return;
  4451.         }
  4452.         newProduct.setPrice((double) Math.round(d));
  4453.         newProduct.setPeriodInterval(productinterval(periodInterval));
  4454.         newProduct.setResignationDate(resignationDate);
  4455.         newProduct.setStartDate(startDate);
  4456.         newProduct.setIndexFreeze(indexFreeze);
  4457.         if(id != 0){
  4458.             try{
  4459.                 ss.createNewProduct(newProduct, ss.getSubscriptionById(id));
  4460.                 products.add(newProduct);
  4461.             }
  4462.             catch(Exception e){
  4463.                 FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(e.getMessage()));
  4464.             }
  4465.         }else{
  4466.             try{
  4467.                 if(newProduct.getStartDate() == null || newProduct.getResignationDate() == null){
  4468.                     throw new Exception("Can't create a product without start and resignation date");
  4469.                 }
  4470.                 products.add(newProduct);
  4471.             }
  4472.             catch(Exception e){
  4473.                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
  4474.             }
  4475.         }
  4476.     }
  4477.     // Save er edit
  4478. //  public void saveProduct() throws IOException {
  4479. //      Product p = new Product();
  4480. //      p.setGroupProduct(selectedGroupProduct);
  4481. //      p.setSubscription(selectedProduct.getSubscription());
  4482. //      p.setTitle(selectedTitle);
  4483. //      p.setPrice(price);
  4484. //      p.setDiscount(discount);
  4485. //      p.setResignationDate(resignationDate);
  4486. //      p.setStartDate(startDate);
  4487. //      p.setPeriodInterval(checkInterval(periodInterval));
  4488. //      p.setSubscription(s);
  4489. //      p.setProduct_id(selectedProduct.getProduct_id());
  4490. //      ss.editProduct(p);
  4491. //      load();
  4492. //      editing = false;
  4493. //  }
  4494.    
  4495.     public InvoiceInterval checkInterval(String s){
  4496.         if (s.toLowerCase().equals("days")) {
  4497.             return InvoiceInterval.Daily;
  4498.         } else if (s.toLowerCase().equals("weeks")) {
  4499.             return InvoiceInterval.Weekly;
  4500.         } else if (s.toLowerCase().equals("months")) {
  4501.             return InvoiceInterval.Monthly;
  4502.         } else if (s.toLowerCase().equals("years")) {
  4503.             return InvoiceInterval.Yearly;
  4504.         } else if (s.toLowerCase().equals("quarters")) {
  4505.             return InvoiceInterval.Quarterly;
  4506.         }
  4507.         return null;
  4508.     }
  4509.     public InvoiceInterval productinterval(String s){
  4510.         if (s.toLowerCase().equals("daily")) {
  4511.             return InvoiceInterval.Daily;
  4512.         } else if (s.toLowerCase().equals("weekly")) {
  4513.             return InvoiceInterval.Weekly;
  4514.         } else if (s.toLowerCase().equals("monthly")) {
  4515.             return InvoiceInterval.Monthly;
  4516.         } else if (s.toLowerCase().equals("yearly")) {
  4517.             return InvoiceInterval.Yearly;
  4518.         } else if (s.toLowerCase().equals("quarterly")) {
  4519.             return InvoiceInterval.Quarterly;
  4520.         }
  4521.         return null;
  4522.     }
  4523.  
  4524.  
  4525.     public List<Extra> getAvailableExtras() {
  4526.         return availableExtras;
  4527.     }
  4528.     public void setAvailableExtras(List<Extra> availableExtras) {
  4529.         this.availableExtras = availableExtras;
  4530.     }
  4531.     public Extra getSelectedExtra() {
  4532.         return selectedExtra;
  4533.     }
  4534.     public void setSelectedExtra(Extra selectedExtra) {
  4535.         this.selectedExtra = selectedExtra;
  4536.     }
  4537.     public boolean isViewProduct() {
  4538.         return viewProduct;
  4539.     }
  4540.     public void setViewProduct(boolean viewProduct) {
  4541.         this.viewProduct = viewProduct;
  4542.     }
  4543.     public List<String> getPeriodintervalsProduct() {
  4544.         return periodintervalsProduct;
  4545.     }
  4546.     public void setPeriodintervalsProduct(List<String> periodintervalsProduct) {
  4547.         this.periodintervalsProduct = periodintervalsProduct;
  4548.     }
  4549.     public String getDeleteSubString() {
  4550.         return deleteSubString;
  4551.     }
  4552.  
  4553.     public void setDeleteSubString(String deleteSubString) {
  4554.         this.deleteSubString = deleteSubString;
  4555.     }
  4556.  
  4557.     public boolean isEditing() {
  4558.         return editing;
  4559.     }
  4560.  
  4561.     public void setEditing(boolean editing) {
  4562.         this.editing = editing;
  4563.     }
  4564.  
  4565.     public Product getNewProduct() {
  4566.         return newProduct;
  4567.     }
  4568.     public void setNewProduct(Product newProduct) {
  4569.         this.newProduct = newProduct;
  4570.     }
  4571.     public int getCustomerId() {
  4572.         return customerId;
  4573.     }
  4574.  
  4575.     public void setCustomerId(int customerId) {
  4576.         this.customerId = customerId;
  4577.     }
  4578.  
  4579.     public String getPeriodIntervalSub() {
  4580.         return periodIntervalSub;
  4581.     }
  4582.  
  4583.     public void setPeriodIntervalSub(String periodIntervalSub) {
  4584.         this.periodIntervalSub = periodIntervalSub;
  4585.     }
  4586.  
  4587.     public boolean isNewSub() {
  4588.         return newSub;
  4589.     }
  4590.  
  4591.     public void setNewSub(boolean newSub) {
  4592.         this.newSub = newSub;
  4593.     }
  4594.  
  4595.     public List<String> getPeriodintervals() {
  4596.         return periodintervals;
  4597.     }
  4598.  
  4599.     public void setPeriodintervals(List<String> periodintervals) {
  4600.         this.periodintervals = periodintervals;
  4601.     }
  4602.  
  4603.     public Double getPrice() {
  4604.         return price;
  4605.     }
  4606.  
  4607.     public void setPrice(Double price) {
  4608.         this.price = price;
  4609.     }
  4610.  
  4611.     public String getSelectedTitle() {
  4612.         return selectedTitle;
  4613.     }
  4614.  
  4615.     public void setSelectedTitle(String selectedTitle) {
  4616.         this.selectedTitle = selectedTitle;
  4617.     }
  4618.  
  4619.     public Double getDiscount() {
  4620.         return discount;
  4621.     }
  4622.  
  4623.     public void setDiscount(Double discount) {
  4624.         this.discount = discount;
  4625.     }
  4626.  
  4627.     public Date getResignationDate() {
  4628.         return resignationDate;
  4629.     }
  4630.  
  4631.     public void setResignationDate(Date resignationDate) {
  4632.         this.resignationDate = resignationDate;
  4633.     }
  4634.  
  4635.     public Date getStartDate() {
  4636.         return startDate;
  4637.     }
  4638.  
  4639.     public void setStartDate(Date startDate) {
  4640.         this.startDate = startDate;
  4641.     }
  4642.  
  4643.     public String getPeriodInterval() {
  4644.         return periodInterval;
  4645.     }
  4646.  
  4647.     public void setPeriodInterval(String periodInterval) {
  4648.         this.periodInterval = periodInterval;
  4649.     }
  4650.  
  4651.     public int getId() {
  4652.         return id;
  4653.     }
  4654.  
  4655.     public void setId(int id) {
  4656.         this.id = id;
  4657.     }
  4658.  
  4659.     public String getName() {
  4660.         return name;
  4661.     }
  4662.     public void setName(String name) {
  4663.         this.name = name;
  4664.     }
  4665.     public List<Product> getProducts() {
  4666.         return products;
  4667.     }
  4668.     public void setProducts(List<Product> products) {
  4669.         this.products = products;
  4670.     }
  4671.     public Customer getCustomer() {
  4672.         return customer;
  4673.     }
  4674.     public void setCustomer(Customer customer) {
  4675.         this.customer = customer;
  4676.     }
  4677.     public int getDateInterval() {
  4678.         return dateInterval;
  4679.     }
  4680.     public void setDateInterval(int dateInterval) {
  4681.         this.dateInterval = dateInterval;
  4682.     }
  4683.     public State getSubstate() {
  4684.         return substate;
  4685.     }
  4686.     public void setSubstate(State substate) {
  4687.         this.substate = substate;
  4688.     }
  4689.     public Date getCreationdate() {
  4690.         return creationdate;
  4691.     }
  4692.     public void setCreationdate(Date creationdate) {
  4693.         this.creationdate = creationdate;
  4694.     }
  4695.     public Date getIndexFreeze() {
  4696.         return indexFreeze;
  4697.     }
  4698.     public void setIndexFreeze(Date indexFreeze) {
  4699.         this.indexFreeze = indexFreeze;
  4700.     }
  4701.     public InvoiceInterval getPaymentDelay() {
  4702.         return paymentDelay;
  4703.     }
  4704.     public void setPaymentDelay(InvoiceInterval paymentDelay) {
  4705.         this.paymentDelay = paymentDelay;
  4706.     }
  4707.  
  4708.     public Product getSelectedProduct() {
  4709.         return selectedProduct;
  4710.     }
  4711.  
  4712.     public void setSelectedProduct(Product selectedProduct) {
  4713.         this.selectedProduct = selectedProduct;
  4714.     }
  4715.     public License getSelectedLicense() {
  4716.         return selectedLicense;
  4717.     }
  4718.     public void setSelectedLicense(License selectedLicense) {
  4719.         this.selectedLicense = selectedLicense;
  4720.     }
  4721.     public List<License> getAvailableLicenses() {
  4722.         return availableLicenses;
  4723.     }
  4724.     public void setAvailableLicenses(List<License> availableLicenses) {
  4725.         this.availableLicenses = availableLicenses;
  4726.     }
  4727.  
  4728.    
  4729. }
  4730.  
  4731. State
  4732.  
  4733. package net.peopleway.invoicesystem.subscription;
  4734.  
  4735. public enum State {
  4736.     InProgress, Active,InActive, ToStart, ToEnd
  4737. }
  4738.  
  4739. Subscription
  4740.  
  4741. package net.peopleway.invoicesystem.subscription;
  4742.  
  4743. import java.io.Serializable;
  4744.  
  4745. import java.util.Date;
  4746. import java.util.List;
  4747.  
  4748. import javax.persistence.CascadeType;
  4749. import javax.persistence.Column;
  4750. import javax.persistence.Entity;
  4751. import javax.persistence.EnumType;
  4752. import javax.persistence.Enumerated;
  4753. import javax.persistence.FetchType;
  4754. import javax.persistence.GeneratedValue;
  4755. import javax.persistence.Id;
  4756. import javax.persistence.JoinColumn;
  4757. import javax.persistence.JoinTable;
  4758. import javax.persistence.ManyToOne;
  4759. import javax.persistence.OneToMany;
  4760. import javax.persistence.Table;
  4761.  
  4762. import net.peopleway.invoicesystem.customer.Customer;
  4763. import net.peopleway.invoicesystem.invoice.Invoice;
  4764. import net.peopleway.invoicesystem.invoice.InvoiceInterval;
  4765. import net.peopleway.invoicesystem.product.Product;
  4766.  
  4767. import org.hibernate.annotations.LazyCollection;
  4768. import org.hibernate.annotations.LazyCollectionOption;
  4769.  
  4770.  
  4771.  
  4772. @Entity
  4773. @Table(name="subscription")
  4774. public class Subscription implements Serializable, Comparable<Subscription> {
  4775.     private int  subscription_id;
  4776.     private List<Product> products;
  4777.    
  4778.     private List<Invoice> invoices;
  4779.    
  4780.     private Customer customer;
  4781.  
  4782.     private InvoiceInterval paymentDelay;
  4783.  
  4784.     private int dateInterval;
  4785.    
  4786.     private State substate;
  4787.  
  4788.     private Date creationDate;
  4789.    
  4790.     private String name;
  4791.    
  4792.  
  4793.     public Subscription() {
  4794.     }
  4795.  
  4796.     @LazyCollection(LazyCollectionOption.FALSE)
  4797.     @OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY,orphanRemoval=true, mappedBy = "subscription")
  4798.     public List<Product> getProducts() {
  4799.         return products;
  4800.     }
  4801.  
  4802.     public void setProducts(List<Product> products) {
  4803.         this.products = products;
  4804.     }
  4805.     @Id
  4806.     @GeneratedValue
  4807.     @Column(name="subscription_id")
  4808.     public int getSubscription_id() {
  4809.         return subscription_id;
  4810.     }
  4811.  
  4812.     public void setSubscription_id(int subscription_id) {
  4813.         this.subscription_id = subscription_id;
  4814.     }
  4815.  
  4816.    
  4817.  
  4818.     public void setInvoices(List<Invoice> invoices) {
  4819.         this.invoices = invoices;
  4820.     }
  4821.  
  4822.     @LazyCollection(LazyCollectionOption.FALSE)
  4823.     @OneToMany(cascade = CascadeType.ALL, mappedBy = "subscription")
  4824.     public List<Invoice> getInvoices() {
  4825.         return invoices;
  4826.     }
  4827.  
  4828.     @Enumerated(EnumType.STRING)
  4829.     public InvoiceInterval getPaymentDelay() {
  4830.         return paymentDelay;
  4831.     }
  4832.  
  4833.  
  4834.     public void setPaymentDelay(InvoiceInterval paymentDelay) {
  4835.         this.paymentDelay = paymentDelay;
  4836.     }
  4837.  
  4838.  
  4839.     @Column
  4840.     public int getDateInterval() {
  4841.         return dateInterval;
  4842.     }
  4843.  
  4844.  
  4845.     public void setDateInterval(int dateInterval) {
  4846.         this.dateInterval = dateInterval;
  4847.     }
  4848.  
  4849.     @Enumerated(EnumType.STRING)
  4850.     public State getSubstate() {
  4851.         return substate;
  4852.     }
  4853.  
  4854.  
  4855.     public void setSubstate(State substate) {
  4856.         this.substate = substate;
  4857.     }
  4858.  
  4859.     @Column
  4860.     public Date getCreationDate() {
  4861.         return creationDate;
  4862.     }
  4863.  
  4864.  
  4865.     public void setCreationDate(Date creationDate) {
  4866.         this.creationDate = creationDate;
  4867.     }
  4868.  
  4869.     @LazyCollection(LazyCollectionOption.FALSE)
  4870.     @ManyToOne(optional = false)
  4871.     @JoinColumn(name = "customer_id")
  4872.     public Customer getCustomer() {
  4873.         return customer;
  4874.     }
  4875.  
  4876.     public void setCustomer(Customer customer) {
  4877.         this.customer = customer;
  4878.     }
  4879.  
  4880.     @Column
  4881.     public String getName() {
  4882.         return name;
  4883.     }
  4884.  
  4885.     public void setName(String name) {
  4886.         this.name = name;
  4887.     }
  4888.     @Override
  4889.     public String toString() {
  4890.         return name + " " + substate.toString().toLowerCase();
  4891.     }
  4892.    
  4893.     @Override
  4894.     public int hashCode() {
  4895.         return super.hashCode();
  4896.     }
  4897.     @Override
  4898.     public boolean equals(Object obj) {
  4899.         if (this == obj)
  4900.             return true;
  4901.         if (obj == null)
  4902.             return false;
  4903.         if (getClass() != obj.getClass())
  4904.             return false;
  4905.         Subscription other = (Subscription) obj;
  4906.         if (subscription_id != other.subscription_id)
  4907.             return false;
  4908.         return true;
  4909.     }
  4910.     @Override
  4911.     public int compareTo(Subscription o) {
  4912.         return this.name.compareTo(o.name);
  4913.     }
  4914. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement