View Javadoc
1   /*
2    * Copyright (c) Patrick Magauran 2018.
3    *   Licensed under the AGPLv3. All conditions of said license apply.
4    *       This file is part of ABOS.
5    *
6    *       ABOS is free software: you can redistribute it and/or modify
7    *       it under the terms of the GNU Affero General Public License as published by
8    *       the Free Software Foundation, either version 3 of the License, or
9    *       (at your option) any later version.
10   *
11   *       ABOS is distributed in the hope that it will be useful,
12   *       but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   *       GNU Affero General Public License for more details.
15   *
16   *       You should have received a copy of the GNU Affero General Public License
17   *       along with ABOS.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  
20  package Launchers;//import ABOS.Derby.Utilities.DbInt;
21  
22  import Exceptions.addressException;
23  import Utilities.*;
24  import Workers.AddCustomerWorker;
25  import javafx.application.Application;
26  import javafx.application.Platform;
27  import javafx.collections.FXCollections;
28  import javafx.collections.ObservableList;
29  import javafx.scene.control.TableColumn;
30  import javafx.scene.control.TableView;
31  import javafx.scene.control.cell.PropertyValueFactory;
32  import javafx.scene.control.cell.TextFieldTableCell;
33  import javafx.stage.Stage;
34  import javafx.util.Pair;
35  
36  import java.io.IOException;
37  import java.math.BigDecimal;
38  import java.sql.Connection;
39  import java.sql.PreparedStatement;
40  import java.sql.ResultSet;
41  import java.sql.SQLException;
42  import java.util.ArrayList;
43  import java.util.Collection;
44  import java.util.HashSet;
45  import java.util.Set;
46  
47  //import ABOS.Derby.Product;
48  
49  public class ConvertDerbyToSQL extends Application {
50      private static String derbyLocation;
51      private static String userName;
52      private static String password;
53      private static String fullName;
54      private static String adminUser;
55      private static String adminPass;
56      private ObservableList<formattedProductProps> data;
57      private Boolean columnsFilled = false;
58  
59      public static void main(String[] args) {
60          derbyLocation = args[0];
61          userName = args[1];
62          password = args[2];
63          fullName = args[3];
64          adminUser = args[4];
65          adminPass = args[5];
66  
67          launch(args);
68      }
69  
70      @Override
71      public void start(final Stage stage) {
72          Convert();
73          stage.close();
74          Platform.exit();
75      }
76  
77      public void Convert() {
78          try {
79  
80              ABOS.Derby.DbInt.DbLoc = derbyLocation;
81              Iterable<String> ret = ABOS.Derby.DbInt.getYears();
82              Set<String> years = new HashSet<>();
83  
84              Boolean newUser = !DbInt.verifyLogin(new Pair<>(userName, password));
85              if (!DbInt.verifyLoginAndUser(new Pair<>(adminUser, adminPass))) {
86                  throw new Exception("Invalid Admin Username/Password");
87  
88              }
89              if (newUser) {
90                  User.createUser(userName, password, "", true);
91              } else {
92                  User.updateUser(userName, password, "", true);
93  
94              }
95  
96              ArrayList<ArrayList<String>> yearUsers = new ArrayList<>();
97  
98  
99              ///Select all years
100             //Create a button for each year
101 /*        for (String aRet : ret) {
102             JButton b = new JButton(aRet);
103             b.addActionListener(e -> {
104                 //On button click open Utilities.Year window
105                 new YearWindow(((AbstractButton) e.getSource()).getText());
106 
107             });
108             panel_1.add(b);
109         }*/
110             for (String year : ret) {
111                 ArrayList<String> usersManage = new ArrayList<>();
112                 usersManage.add(userName);
113                 years.add(year);
114 
115                 ABOS.Derby.Year yearObj = new ABOS.Derby.Year(year);
116                 Year yearNew = new Year(year);
117                 Collection<Year.category> rowCats = new ArrayList<>();
118                 ObservableList<formattedProductProps> productList = FXCollections.observableArrayList();
119                 yearObj.getCategories().forEach(category -> {
120                     rowCats.add(new Year.category(category.catName, category.catDate));
121                 });
122                 int productKey = 1;
123                 for (ABOS.Derby.Product.formattedProduct product : yearObj.getAllProducts()) {
124                     productList.add(new formattedProductProps(productKey++, product.productID, product.productName, product.productSize, new BigDecimal(product.productUnitPrice.replace("$", "")), product.productCategory, product.orderedQuantity, product.extendedCost));
125                 }
126 
127                 yearNew.CreateDb(productList, rowCats);
128                 User yearUser = new User(userName, fullName, usersManage, years, true, 1);
129                 DbInt.verifyLoginAndUser(new Pair<>(userName, password));
130                 try (Connection con = DbInt.getConnection(year);
131                      PreparedStatement prep = con.prepareStatement("DELETE FROM users WHERE userName=?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
132                     prep.setString(1, userName);
133                     prep.execute();
134                 } catch (SQLException e) {
135                     LogToFile.log(e, Severity.SEVERE, CommonErrors.returnSqlMessage(e));
136                 }
137                 if (newUser) {
138                     yearUser.addToYear(year);
139                 } else {
140                     yearUser.updateYear(year);
141                 }
142                 {
143 
144 
145                     Iterable<String> customers = yearObj.getCustomerNames();
146                     for (String customer : customers) {
147                         TableView productTable = new TableView();
148                         ABOS.Derby.Customer customerDbInfo = new ABOS.Derby.Customer(customer, year);
149                         Integer cID = customerDbInfo.getId();
150                         ABOS.Derby.Order.orderArray order = new ABOS.Derby.Order().createOrderArray(year, customerDbInfo.getName(), false);
151                         data = FXCollections.observableArrayList();
152                         BigDecimal cost = BigDecimal.ZERO;
153                         int i = 1;
154                         for (ABOS.Derby.Product.formattedProduct productOrder : order.orderData) {
155                             //String productID, String productName, String productSize, String productUnitPrice, String productCategory, int orderedQuantity, BigDecimal extendedCost
156                             formattedProductProps prodProps = new formattedProductProps(i, productOrder.productID, productOrder.productName, productOrder.productSize, new BigDecimal(productOrder.productUnitPrice.replace("$", "")), productOrder.productCategory, productOrder.orderedQuantity, productOrder.extendedCost);
157                             data.add(prodProps);
158                             cost = cost.add(productOrder.extendedCost);
159                             i++;
160                         }
161                         if (!columnsFilled) {
162                             String[][] columnNames = {{"ID", "productID"}, {"Item", "productName"}, {"Size", "productSize"}, {"Price/Item", "productUnitPrice"}};
163                             for (String[] column : columnNames) {
164                                 TableColumn<ABOS.Derby.Product.formattedProductProps, String> tbCol = new TableColumn<>(column[0]);
165                                 tbCol.setCellValueFactory(new PropertyValueFactory<>(column[1]));
166                                 productTable.getColumns().add(tbCol);
167                             }
168                         }
169                         //{"Quantity", "orderedQuantity"}, {"Price", "extendedCost"}
170                         TableColumn<ABOS.Derby.Product.formattedProductProps, String> quantityCol = new TableColumn<>("Quantity");
171                         TableColumn<ABOS.Derby.Product.formattedProductProps, String> priceCol = new TableColumn<>("Price");
172                         quantityCol.setCellValueFactory(new PropertyValueFactory<>("orderedQuantityString"));
173 
174                         quantityCol.setCellFactory(TextFieldTableCell.forTableColumn());
175 
176                         quantityCol.setOnEditCommit(t -> {
177                             //t.getTableView().getItems().get(t.getTablePosition().getRow()).orderedQuantity.set(Integer.valueOf(t.getNewValue()));
178                             int quantity = Integer.valueOf(t.getNewValue());
179                             BigDecimal unitCost = new BigDecimal(t.getTableView().getItems().get(t.getTablePosition().getRow()).productUnitPrice.get().replaceAll("\\$", ""));
180                             //Removes $ from cost and multiplies to get the total cost for that item
181                             BigDecimal ItemTotalCost = unitCost.multiply(new BigDecimal(quantity));
182                             t.getRowValue().extendedCost.set(ItemTotalCost);
183                             t.getRowValue().orderedQuantity.set(quantity);
184                             t.getRowValue().orderedQuantityString.set(String.valueOf(quantity));
185 
186                             data.get(t.getTablePosition().getRow()).orderedQuantity.set(quantity);
187                             data.get(t.getTablePosition().getRow()).extendedCost.set(ItemTotalCost);
188                             t.getTableView().refresh();
189 
190 
191                         });
192                         priceCol.setCellValueFactory(new PropertyValueFactory<>("extendedCost"));
193                         productTable.getColumns().addAll(quantityCol, priceCol);
194 
195                         columnsFilled = true;
196 
197                         productTable.setItems(data);
198 
199                         //Fills original totals to calculate new values to insert in TOTALS table
200 
201 
202                         {
203                             ProgressForm progDial = new ProgressForm();
204 
205                             AddCustomerWorker addCustWork = new AddCustomerWorker(-1, customerDbInfo.getAddr(),
206                                     customerDbInfo.getTown(),
207                                     customerDbInfo.getState(),
208                                     year,
209                                     productTable,
210                                     customerDbInfo.getName(),
211                                     customerDbInfo.getZip(),
212                                     customerDbInfo.getPhone(),
213                                     customerDbInfo.getEmail(),
214                                     customerDbInfo.getDontation().toPlainString(),
215                                     customerDbInfo.getName(),
216                                     (Boolean.valueOf(customerDbInfo.getPaid()) ? BigDecimal.ONE.multiply(cost) : BigDecimal.ZERO).toPlainString(),
217                                     Boolean.valueOf(customerDbInfo.getDelivered()),
218                                     userName);
219 
220         /*addCustWork.addPropertyChangeListener(event -> {
221             switch (event.getPropertyName()) {
222                 case "progress":
223                     progDial.progressBar.setIndeterminate(false);
224                     progDial.progressBar.setValue((Integer) event.getNewValue());
225                     break;
226                 case "state":
227                     switch ((SwingWorker.StateValue) event.getNewValue()) {
228                         case DONE:
229                             try {
230                                 int success = addCustWork.get();
231                                 if (success == 1) {
232                                     updateTots();
233                                     dispose();
234                                     setVisible(false);
235                                 }
236                             } catch (CancellationException e) {
237                                 Utilities.LogToFile.log(e, Utilities.Severity.INFO, "The process was cancelled.");
238                             } catch (Exception e) {
239                                 Utilities.LogToFile.log(e, Utilities.Severity.WARNING, "The process Failed.");
240                             }
241                             addCustWork = null;
242                             progDial.dispose();
243                             break;
244                         case STARTED:
245                         case PENDING:
246                             progDial.progressBar.setVisible(true);
247                             progDial.progressBar.setIndeterminate(true);
248                             break;
249                     }
250                     break;
251             }
252         });*/
253                             progDial.activateProgressBar(addCustWork);
254                             addCustWork.setOnSucceeded(event -> {
255 
256                             });
257                             addCustWork.setOnFailed(event -> {
258                                 progDial.getDialogStage().close();
259 
260                                 Throwable e = addCustWork.getException();
261                                 if (e instanceof addressException) {
262                                     LogToFile.log(null, Severity.WARNING, "Invalid Address. Please Verify spelling and numbers are correct.");
263 
264                                 }
265                                 if (e instanceof SQLException) {
266                                     LogToFile.log((SQLException) e, Severity.SEVERE, CommonErrors.returnSqlMessage(((SQLException) addCustWork.getException())));
267 
268                                 }
269                                 if (e instanceof InterruptedException) {
270                                     if (addCustWork.isCancelled()) {
271                                         LogToFile.log((InterruptedException) e, Severity.FINE, "Add Customer process canceled.");
272 
273                                     }
274                                 }
275                                 if (e instanceof IOException) {
276                                     LogToFile.log((IOException) e, Severity.WARNING, "Error contacting geolaction service. Please try again or contasct support.");
277                                 }
278 
279                             });
280 
281 
282                             progDial.getDialogStage().show();
283                             addCustWork.run();
284                         }
285                     }
286                 }
287             }
288 
289         } catch (Exception e) {
290             LogToFile.log(e, Severity.SEVERE, "Something went wrong converting Database. See log for details.");
291 
292         }
293     }
294 }