×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Alexandros Kyriazis
Added: Jan 25, 2022 6:45 PM
Views: 393
Tags: no tags
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package semesterprojectv5;
  7.  
  8. import com.google.gson.Gson;
  9. import com.google.gson.GsonBuilder;
  10. import com.google.gson.JsonArray;
  11. import com.google.gson.JsonElement;
  12. import com.google.gson.JsonObject;
  13. import java.text.SimpleDateFormat;
  14. import java.util.Date;
  15. import java.util.Locale;
  16. import java.util.Map;
  17. import static java.util.Map.entry;
  18. import java.util.Set;
  19. import javax.persistence.EntityManager;
  20. import javax.persistence.EntityManagerFactory;
  21. import javax.persistence.EntityTransaction;
  22. import javax.persistence.Persistence;
  23. import javax.persistence.Query;
  24. import javax.swing.JOptionPane;
  25. import okhttp3.OkHttpClient;
  26. import okhttp3.Request;
  27.  
  28. /**
  29.  *
  30.  * @author alexa
  31.  */
  32. public class Datamanager extends javax.swing.JFrame {
  33.     EntityManagerFactory emf = Persistence.createEntityManagerFactory("Semesterprojectv5PU");
  34.     EntityManager em = emf.createEntityManager();
  35.     EntityTransaction tx = em.getTransaction();
  36.     CountryJpaController cjc = new CountryJpaController(emf);
  37.     CoviddataJpaController covjc = new CoviddataJpaController(emf);
  38.    
  39.     public Datamanager() {
  40.         initComponents();
  41.     }
  42.  
  43.     /**
  44.      * This method is called from within the constructor to initialize the form.
  45.      * WARNING: Do NOT modify this code. The content of this method is always
  46.      * regenerated by the Form Editor.
  47.      */
  48.     @SuppressWarnings("unchecked")
  49.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  50.     private void initComponents() {
  51.  
  52.         jButton1 = new javax.swing.JButton();
  53.         jButton2 = new javax.swing.JButton();
  54.         jLabel1 = new javax.swing.JLabel();
  55.         jLabel2 = new javax.swing.JLabel();
  56.         jLabel3 = new javax.swing.JLabel();
  57.         jComboBox1 = new javax.swing.JComboBox<>();
  58.         jButton5 = new javax.swing.JButton();
  59.         jButton6 = new javax.swing.JButton();
  60.  
  61.         setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
  62.  
  63.         jButton1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
  64.         jButton1.setText("Insert");
  65.         jButton1.addActionListener(new java.awt.event.ActionListener() {
  66.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  67.                 jButton1ActionPerformed(evt);
  68.             }
  69.         });
  70.  
  71.         jButton2.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
  72.         jButton2.setText("Delete");
  73.         jButton2.addActionListener(new java.awt.event.ActionListener() {
  74.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  75.                 jButton2ActionPerformed(evt);
  76.             }
  77.         });
  78.  
  79.         jLabel1.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N
  80.         jLabel1.setText("Insert-Delete Countries");
  81.  
  82.         jLabel2.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N
  83.         jLabel2.setText("Insert-Delete Data");
  84.  
  85.         jLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
  86.         jLabel3.setText("Chose Data");
  87.  
  88.         jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
  89.         jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Deaths", "Recovered", "Confirmed Cases" }));
  90.         jComboBox1.addActionListener(new java.awt.event.ActionListener() {
  91.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  92.                 jComboBox1ActionPerformed(evt);
  93.             }
  94.         });
  95.  
  96.         jButton5.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
  97.         jButton5.setText("Insert");
  98.         jButton5.addActionListener(new java.awt.event.ActionListener() {
  99.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  100.                 jButton5ActionPerformed(evt);
  101.             }
  102.         });
  103.  
  104.         jButton6.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
  105.         jButton6.setText("Delete");
  106.         jButton6.addActionListener(new java.awt.event.ActionListener() {
  107.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  108.                 jButton6ActionPerformed(evt);
  109.             }
  110.         });
  111.  
  112.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  113.         getContentPane().setLayout(layout);
  114.         layout.setHorizontalGroup(
  115.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  116.             .addGroup(layout.createSequentialGroup()
  117.                 .addGap(49, 49, 49)
  118.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  119.                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  120.                         .addGroup(layout.createSequentialGroup()
  121.                             .addComponent(jButton1)
  122.                             .addGap(78, 78, 78)
  123.                             .addComponent(jButton2))
  124.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  125.                             .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
  126.                             .addComponent(jLabel1)))
  127.                     .addComponent(jLabel2)
  128.                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
  129.                         .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  130.                         .addGroup(layout.createSequentialGroup()
  131.                             .addComponent(jButton5)
  132.                             .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  133.                             .addComponent(jButton6))))
  134.                 .addContainerGap(62, Short.MAX_VALUE))
  135.         );
  136.         layout.setVerticalGroup(
  137.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  138.             .addGroup(layout.createSequentialGroup()
  139.                 .addGap(32, 32, 32)
  140.                 .addComponent(jLabel1)
  141.                 .addGap(35, 35, 35)
  142.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  143.                     .addComponent(jButton1)
  144.                     .addComponent(jButton2))
  145.                 .addGap(33, 33, 33)
  146.                 .addComponent(jLabel2)
  147.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  148.                 .addComponent(jLabel3)
  149.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  150.                 .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  151.                 .addGap(18, 18, 18)
  152.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  153.                     .addComponent(jButton5)
  154.                     .addComponent(jButton6))
  155.                 .addContainerGap(51, Short.MAX_VALUE))
  156.         );
  157.  
  158.         pack();
  159.     }// </editor-fold>                        
  160.  
  161.     private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  162.         // TODO add your handling code here:
  163.  
  164.         // Complete any data deletion after it has been completed
  165.         // verification query with user confirmation.
  166.         int a = JOptionPane.showConfirmDialog(null, "The system will delete from the database\n" + "all countries. Are you sure?", "Delete Data", JOptionPane.YES_NO_OPTION);
  167.         if (a == JOptionPane.YES_OPTION) {
  168.             try {
  169.                 // Delete table COUNTRY
  170.                 tx.begin();
  171.                 // We check if we have data entries in Coviddata table
  172.                 Query q1 = em.createQuery("SELECT c FROM Coviddata c");
  173.                 if (q1.getResultList().isEmpty()) {
  174.                     em.createQuery("DELETE FROM Country").executeUpdate();
  175.                     em.createNativeQuery("ALTER TABLE COUNTRY ALTER COLUMN COUNTRY RESTART WITH 1").executeUpdate();
  176.                     tx.commit();
  177.                     JOptionPane.showMessageDialog(null, "The Countries deleted from Database", "Delete Countries", JOptionPane.INFORMATION_MESSAGE);
  178.                 } else {
  179.                     JOptionPane.showMessageDialog(null, "Countries not deleted from Database\n" + "Please delete the Coviddata first.", "Delete Countries", JOptionPane.INFORMATION_MESSAGE);
  180.                 }
  181.             } catch (Exception ex) {
  182.                 System.out.println(ex);
  183.             }
  184.        
  185.     }
  186.     }                                        
  187.  
  188.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  189.             // TODO add your handling code here:
  190.             String urlToCall = "https://covid2019-api.herokuapp.com/timeseries/recovered";
  191.  
  192.             //Create a object OkHttpClient
  193.             OkHttpClient client = new OkHttpClient();
  194. //Create a object Request with reference the url we call
  195.             Request request = new Request.Builder().url(urlToCall).build();
  196.  
  197.             //We check if the url we call give us the data
  198.             try (okhttp3.Response response = client.newCall(request).execute()) {
  199.                 if (response.isSuccessful() && response.body() != null) {
  200.                     //We save the response String
  201.                     String responseString = response.body().string();
  202.                     //Create a object GsonBuilder
  203.                     GsonBuilder builder = new GsonBuilder();
  204.                     builder.setPrettyPrinting();
  205.                     Gson gson = builder.create();
  206.  
  207.                     //We get the results in JsonObject and we create a JsonArray
  208.                     JsonObject json = gson.fromJson(responseString, JsonObject.class);
  209.                     JsonArray items = json.get("recovered").getAsJsonArray();
  210.  
  211.                     //foreach in JsonElements
  212.                     for (JsonElement element : items) {
  213.                         JsonObject object = element.getAsJsonObject();
  214.                         try {
  215.                             //We get Country/Region, Lat και Long
  216.                             String Name = object.getAsJsonObject().get("Country/Region").getAsString();
  217.                             Double Lat = object.getAsJsonObject().get("Lat").getAsDouble();
  218.                             Double Long = object.getAsJsonObject().get("Long").getAsDouble();
  219.  
  220.                             //Create a object Country
  221.                             Country c = new Country();
  222.                             c.setName(Name);
  223.                             c.setLat(Lat);
  224.                             c.setLong1(Long);
  225.  
  226.                             //We search the country if it's in Database
  227.                             String name = object.getAsJsonObject().get("Country/Region").getAsString();
  228.                             Query q1 = em.createQuery("SELECT c FROM Country c WHERE c.name = :name");
  229.                             q1.setParameter("name", name);
  230.                             //We check if we have data in Database
  231.                             if (q1.getResultList().isEmpty()) {
  232.                                 //With CountryJpaController we send the object to the Database
  233.                                 cjc.create(c);
  234.                             }
  235.                         } catch (Exception e) {
  236.                         }
  237.                     }
  238.  
  239.                     // Information message
  240.                     JOptionPane.showMessageDialog(null, "The countries were registered in the database ", "Information", JOptionPane.INFORMATION_MESSAGE);
  241.                 }
  242.             } catch (Exception ex) {
  243.                 System.out.println(ex);
  244.             }
  245.     }                                        
  246.  
  247.     private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  248.     Integer selectint = jComboBox1.getSelectedIndex();    
  249.     String selecturl = null;    
  250.         if (selectint == 0) {
  251.            selecturl = "deaths";
  252.         }else if (selectint == 1) {
  253.             selecturl = "recovered";
  254.         }else if (selectint == 2) {
  255.             selecturl = "confirmed";
  256.         }
  257.  
  258.          String urlToCall = "https://covid2019-api.herokuapp.com/timeseries/" + selecturl;
  259.             //Create a object OkHttpClient
  260.             OkHttpClient client = new OkHttpClient();
  261. //Create a object Request with reference the url we call
  262.             Request request = new Request.Builder().url(urlToCall).build();    
  263.             //We check if the url we call give us the data
  264.             try (okhttp3.Response response = client.newCall(request).execute()) {
  265.                 if (response.isSuccessful() && response.body() != null) {
  266.                     //We save the response String
  267.                     String responseString = response.body().string();
  268.                     //Create a object GsonBuilder
  269.                     GsonBuilder builder = new GsonBuilder();
  270.                     builder.setPrettyPrinting();
  271.                     Gson gson = builder.create();
  272.  
  273.                     //We get the results in JsonObject and we create a JsonArray
  274.                     JsonObject json = gson.fromJson(responseString, JsonObject.class);
  275.                     JsonArray items = json.get(selecturl).getAsJsonArray();    
  276.                     for (JsonElement element : items) {
  277.                         JsonObject object = element.getAsJsonObject();    
  278.                         Set<Map.Entry<String, JsonElement>> entries = object.entrySet();
  279.                         //System.out.println(entries);
  280.                         try{  
  281.                             String Name = object.getAsJsonObject().get("Country/Region").getAsString();
  282.                             Query q1 = em.createQuery("SELECT c FROM Country c WHERE c.name = :name");
  283.                             q1.setParameter("name", Name);
  284.                            
  285.                             Country country = (Country) q1.getSingleResult();
  286.                            
  287.                             Coviddata coviddata = new Coviddata();
  288.                            
  289.                             coviddata.setCountry(country);
  290.                            
  291.                             short Datakind = selectint.shortValue();
  292.                             coviddata.setDatakind(++Datakind);
  293.                             int qty = 0;
  294.                            
  295.                            
  296.                            
  297.                             for (Map.Entry<String, JsonElement> entry : entries) {
  298.                                 System.out.println(entry);
  299.                                 if (entry.getKey().charAt(1) == '/' || entry.getKey().charAt(2) == '/'){
  300.                                 Date date = new SimpleDateFormat ("MM/dd/yy").parse(entry.getKey());
  301.                                 coviddata.setTrndate(date);
  302.                                
  303.                                 int proodqty = entry.getValue().getAsInt();
  304.                                 coviddata.setProodqty(proodqty);
  305.                                
  306.                                
  307.                                
  308.                                
  309.                                 if (proodqty > qty){
  310.                                 qty = proodqty - qty;
  311.                                 coviddata.setQty(qty);
  312.                                 qty = proodqty;
  313.                                 }else if (proodqty == qty){
  314.                                     coviddata.setQty(0);
  315.                                 }
  316.                                 System.out.println(coviddata);
  317.                                 covjc.create(coviddata);
  318.                                 }                          
  319.                             }
  320.                         } catch(Exception ex){
  321.                             System.out.println(ex);
  322.                          }
  323.                      }
  324.                     JOptionPane.showMessageDialog(null, "The data " +selecturl + " were registered in the database ", "Information", JOptionPane.INFORMATION_MESSAGE);
  325.                 }
  326.             } catch (Exception ex){
  327.                 System.out.println(ex);}
  328.                        
  329.                        
  330.                        
  331.                        
  332.                        
  333.                        
  334.     }                                        
  335.  
  336.     private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  337. int a = JOptionPane.showConfirmDialog(null, "The system will delete from the database\n" + "all countries. Are you sure?", "Delete Data", JOptionPane.YES_NO_OPTION);
  338. Integer selectint = jComboBox1.getSelectedIndex();    
  339.     String selecturl = null;    
  340.         if (selectint == 0) {
  341.            selecturl = "deaths";
  342.         }else if (selectint == 1) {
  343.             selecturl = "recovered";
  344.         }else if (selectint == 2) {
  345.             selecturl = "confirmed";
  346.         }
  347.         if (a == JOptionPane.YES_OPTION) {
  348.             try {
  349.                 // Delete table COUNTRY
  350.                 tx.begin();
  351.                 // We check if we have data entries in Coviddata table
  352.                
  353.                
  354.                     em.createQuery("DELETE FROM"+selecturl).executeUpdate();
  355.                     em.createNativeQuery("ALTER TABLE COVIDDATA ALTER COLUMN COVIDDATA RESTART WITH 1").executeUpdate();
  356.                     tx.commit();
  357.                     JOptionPane.showMessageDialog(null, "The "+ selecturl +" deleted from Database", "Delete coviddata", JOptionPane.INFORMATION_MESSAGE);
  358.                
  359.             } catch (Exception ex) {
  360.                 System.out.println(ex);
  361.             }
  362.        
  363.     }      
  364.        
  365.        
  366.     }                                        
  367.  
  368.     private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
  369.         // TODO add your handling code here:
  370.     }                                          
  371.  
  372.     /**
  373.      * @param args the command line arguments
  374.      */
  375.     public static void main(String args[]) {
  376.         /* Set the Nimbus look and feel */
  377.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  378.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  379.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  380.          */
  381.         try {
  382.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  383.                 if ("Nimbus".equals(info.getName())) {
  384.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  385.                     break;
  386.                 }
  387.             }
  388.         } catch (ClassNotFoundException ex) {
  389.             java.util.logging.Logger.getLogger(Datamanager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  390.         } catch (InstantiationException ex) {
  391.             java.util.logging.Logger.getLogger(Datamanager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  392.         } catch (IllegalAccessException ex) {
  393.             java.util.logging.Logger.getLogger(Datamanager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  394.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  395.             java.util.logging.Logger.getLogger(Datamanager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  396.         }
  397.         //</editor-fold>
  398.  
  399.         /* Create and display the form */
  400.         java.awt.EventQueue.invokeLater(new Runnable() {
  401.             public void run() {
  402.                 new Datamanager().setVisible(true);
  403.             }
  404.         });
  405.     }
  406.  
  407.     // Variables declaration - do not modify                    
  408.     private javax.swing.JButton jButton1;
  409.     private javax.swing.JButton jButton2;
  410.     private javax.swing.JButton jButton5;
  411.     private javax.swing.JButton jButton6;
  412.     private javax.swing.JComboBox<String> jComboBox1;
  413.     private javax.swing.JLabel jLabel1;
  414.     private javax.swing.JLabel jLabel2;
  415.     private javax.swing.JLabel jLabel3;
  416.     // End of variables declaration                  
  417. }
  418.