Advertisement
Guest User

Untitled

a guest
Nov 28th, 2014
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.02 KB | None | 0 0
  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 currencyconverter;
  7.  
  8. import java.io.BufferedInputStream;
  9. import java.io.BufferedOutputStream;
  10. import java.io.File;
  11. import java.io.FileInputStream;
  12. import java.io.FileNotFoundException;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.ObjectInput;
  17. import java.io.ObjectInputStream;
  18. import java.io.ObjectOutput;
  19. import java.io.ObjectOutputStream;
  20. import java.io.OutputStream;
  21. import java.io.Serializable;
  22. import java.net.MalformedURLException;
  23. import java.net.URL;
  24. import java.text.DecimalFormat;
  25. import java.util.ArrayList;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import javax.swing.JOptionPane;
  29. import javax.xml.stream.XMLInputFactory;
  30. import javax.xml.stream.XMLStreamConstants;
  31. import javax.xml.stream.XMLStreamException;
  32. import javax.xml.stream.XMLStreamReader;
  33.  
  34. /**
  35.  *
  36.  * @author Sandkar
  37.  */
  38.  
  39. /*
  40.  
  41. HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!
  42. To get the correct JavaDoc you have to go to:
  43.  
  44. Run -> Set Project Configuration -> Customize -> Documenting -> check Include Private and Package Private Members
  45.  
  46. */
  47.  
  48.  
  49. /**
  50. * Main window for the currency converter
  51. */
  52. public class CurrencyConverter extends javax.swing.JFrame implements Serializable {
  53.    
  54.     private ArrayList<Currency> currencies = new ArrayList<>();
  55.     private String time = new String();
  56.     private Double currentFromRate;
  57.     private Double currentToRate;
  58.     private final DecimalFormat df;
  59.    
  60.     /**
  61.      * Creates new form CurrencyConverter
  62.      */
  63.     public CurrencyConverter() throws IOException {
  64.         this.openCurrencyXML();
  65.         this.df = new DecimalFormat("#.#####");
  66.         this.currentFromRate = new Double(1);
  67.         this.currentToRate = new Double(1);
  68.         initComponents();
  69.        
  70.         for(int i = 1; i < currencies.size(); ++i) {
  71.             jComboBox1.addItem(currencies.get(i).getName());
  72.             jComboBox2.addItem(currencies.get(i).getName());
  73.         }
  74.        
  75.         jLabel1.setText("Rates from: " + currencies.get(0).getDate());
  76.     }
  77.  
  78.     @SuppressWarnings("unchecked")
  79.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  80.     private void initComponents() {
  81.  
  82.         jComboBox1 = new javax.swing.JComboBox();
  83.         jLabel1 = new javax.swing.JLabel();
  84.         jComboBox2 = new javax.swing.JComboBox();
  85.         jLabel2 = new javax.swing.JLabel();
  86.         jLabel3 = new javax.swing.JLabel();
  87.         jLabel4 = new javax.swing.JLabel();
  88.         jLabel5 = new javax.swing.JLabel();
  89.         jTextField1 = new javax.swing.JTextField();
  90.         jTextField2 = new javax.swing.JTextField();
  91.  
  92.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  93.         setTitle("Ye Olde Currency Converter - Avast Ye Swashbucklers");
  94.  
  95.         jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));
  96.         jComboBox1.setToolTipText("");
  97.         jComboBox1.addActionListener(new java.awt.event.ActionListener() {
  98.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  99.                 jComboBox1ActionPerformed(evt);
  100.             }
  101.         });
  102.  
  103.         jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));
  104.         jComboBox2.setToolTipText("");
  105.         jComboBox2.addActionListener(new java.awt.event.ActionListener() {
  106.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  107.                 jComboBox2ActionPerformed(evt);
  108.             }
  109.         });
  110.  
  111.         jLabel2.setText("From");
  112.  
  113.         jLabel3.setText("To");
  114.  
  115.         jLabel4.setText("Amount");
  116.  
  117.         jLabel5.setText("Result");
  118.  
  119.         jTextField1.addActionListener(new java.awt.event.ActionListener() {
  120.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  121.                 jTextField1ActionPerformed(evt);
  122.             }
  123.         });
  124.  
  125.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  126.         getContentPane().setLayout(layout);
  127.         layout.setHorizontalGroup(
  128.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  129.             .addGroup(layout.createSequentialGroup()
  130.                 .addContainerGap()
  131.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  132.                     .addGroup(layout.createSequentialGroup()
  133.                         .addComponent(jLabel4)
  134.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  135.                         .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
  136.                     .addGroup(layout.createSequentialGroup()
  137.                         .addComponent(jLabel5)
  138.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  139.                         .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
  140.                     .addGroup(layout.createSequentialGroup()
  141.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  142.                             .addComponent(jLabel2)
  143.                             .addComponent(jLabel3))
  144.                         .addGap(25, 25, 25)
  145.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  146.                             .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
  147.                             .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)))
  148.                     .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
  149.                 .addGap(18, 18, Short.MAX_VALUE))
  150.         );
  151.         layout.setVerticalGroup(
  152.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  153.             .addGroup(layout.createSequentialGroup()
  154.                 .addContainerGap()
  155.                 .addComponent(jLabel1)
  156.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  157.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  158.                     .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  159.                     .addComponent(jLabel2))
  160.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  161.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  162.                     .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  163.                     .addComponent(jLabel3))
  164.                 .addGap(18, 18, 18)
  165.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  166.                     .addComponent(jLabel4)
  167.                     .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  168.                 .addGap(18, 18, 18)
  169.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  170.                     .addComponent(jLabel5)
  171.                     .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  172.                 .addContainerGap(22, Short.MAX_VALUE))
  173.         );
  174.  
  175.         pack();
  176.     }// </editor-fold>                        
  177.    
  178.     /**
  179.      * Outputs the correct amount depending on which rate you have chosen
  180.      */
  181.     private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
  182.         // TODO add your handling code here:
  183.         jTextField2.setText(df.format(Double.parseDouble(jTextField1.getText()) * currentToRate / currentFromRate));
  184.     }                                          
  185.    
  186.     /**
  187.      * Updates your current from rate
  188.     */
  189.     private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
  190.         // TODO add your handling code here:
  191.         currentFromRate = currencies.get(jComboBox1.getSelectedIndex()).getRate();
  192.     }                                          
  193.     /**
  194.      * Updates your current to rate
  195.     */
  196.     private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {                                          
  197.         // TODO add your handling code here:
  198.         currentToRate = currencies.get(jComboBox2.getSelectedIndex()).getRate();
  199.     }                                          
  200.    
  201.     /**
  202.     * Reads the currencies name, rate and date into a list
  203.     */
  204.     private void writeToFile() throws IOException {
  205.         File file = new File(System.getProperty("user.home") + "/currencies.cur");
  206.  
  207.         if(!file.exists()) {
  208.             file.createNewFile();
  209.         }
  210.        
  211.         try(OutputStream out = new FileOutputStream(file.getPath());
  212.             OutputStream buffer = new BufferedOutputStream(out);
  213.             ObjectOutput output = new ObjectOutputStream(buffer);) {
  214.             output.writeObject(currencies);
  215.         } catch (IOException e) {
  216.         }
  217.     }
  218.     /**
  219.     * Reads the currencies name, rate and date into a list
  220.     */
  221.     private void readFromFile() throws IOException {
  222.         File file = new File(System.getProperty("user.home") + "/currencies.cur");
  223.        
  224.         try(InputStream in = new FileInputStream(file.getPath());
  225.             InputStream buffer = new BufferedInputStream(in);
  226.             ObjectInput input = new ObjectInputStream(buffer);) {
  227.             currencies = (ArrayList<Currency>) input.readObject();
  228.  
  229.             } catch (FileNotFoundException ex) {
  230.                 showErrorMsg("Could not fetch rates online and no cached file found.");
  231.                 System.exit(0);
  232.             } catch (IOException | ClassNotFoundException ex) {
  233.                 showErrorMsg("Could not fetch rates online and no cached file found.");
  234.                 System.exit(0);
  235.             }
  236.     }
  237.     /**
  238.      * Shows the parameter as an information message
  239.      */
  240.     private static void showInformationMsg(String msg) {
  241.         JOptionPane.showMessageDialog(
  242.         null,
  243.         msg,
  244.         "Information",
  245.         JOptionPane.INFORMATION_MESSAGE);
  246.     }
  247.     /**
  248.      * Shows the parameter as an error message
  249.      */
  250.     private static void showErrorMsg(String msg) {
  251.         JOptionPane.showMessageDialog(
  252.         null,
  253.         msg,
  254.         "Error",
  255.         JOptionPane.ERROR_MESSAGE);
  256.     }
  257.     /**
  258.      * Reads the XML currency file into a list, if no connection is found it reads from a .cur file in the home folder. If no .cur file is found it terminates the program.
  259.      */
  260.     private void openCurrencyXML() throws IOException {
  261.         XMLInputFactory factory = XMLInputFactory.newInstance();
  262.         URL url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
  263.        
  264.         try {
  265.             InputStream stream = url.openStream();
  266.             XMLStreamReader reader = factory.createXMLStreamReader(stream);
  267.        
  268.             while(reader.hasNext()) {
  269.                 int event = reader.next();
  270.                 switch (event) {
  271.                     case XMLStreamConstants.START_ELEMENT:
  272.                         String attributeValue = reader.getAttributeValue(0);
  273.                         String attributeValue2 = reader.getAttributeValue(1);
  274.                         String attributeName = reader.getAttributeLocalName(0);
  275.  
  276.                         if("time".equals(attributeName)) {
  277.                             time = attributeValue;
  278.                             currencies.add(new Currency("EUR", (double) 1, time)); // Puts the "base" in there as well
  279.                         }
  280.  
  281.                         if("currency".equals(attributeName))
  282.                             currencies.add(new Currency(attributeValue, Double.parseDouble(attributeValue2), time));
  283.                     break;
  284.                     case XMLStreamConstants.CHARACTERS:
  285.                         if (!reader.isWhiteSpace()) {
  286.                             String contents = reader.getText().trim();
  287.                         }
  288.                     break;
  289.                 }
  290.             }
  291.      
  292.             this.writeToFile();
  293.         }
  294.         catch(IOException | XMLStreamException | NumberFormatException e) {
  295.             readFromFile();
  296.             showInformationMsg("Could not fetch rates online, using cached file instead.");
  297.         }
  298.  
  299.     }
  300.     /**
  301.      * @param args the command line arguments
  302.      */
  303.     public static void main(String args[]) throws MalformedURLException, IOException, XMLStreamException {
  304.        
  305.  
  306.         /* Set the Nimbus look and feel */
  307.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  308.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  309.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  310.          */
  311.         try {
  312.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  313.                 if ("Nimbus".equals(info.getName())) {
  314.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  315.                     break;
  316.                 }
  317.             }
  318.         } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
  319.             java.util.logging.Logger.getLogger(CurrencyConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  320.         }
  321.         //</editor-fold>
  322.        
  323.         //</editor-fold>
  324.  
  325.         /* Create and display the form */
  326.         java.awt.EventQueue.invokeLater(() -> {
  327.             try {
  328.                 new CurrencyConverter().setVisible(true);
  329.             } catch (IOException ex) {
  330.                 Logger.getLogger(CurrencyConverter.class.getName()).log(Level.SEVERE, null, ex);
  331.             }
  332.         });
  333.        
  334.        
  335.     }
  336.  
  337.     // Variables declaration - do not modify                    
  338.     private static javax.swing.JComboBox jComboBox1;
  339.     private static javax.swing.JComboBox jComboBox2;
  340.     private static javax.swing.JLabel jLabel1;
  341.     private javax.swing.JLabel jLabel2;
  342.     private javax.swing.JLabel jLabel3;
  343.     private javax.swing.JLabel jLabel4;
  344.     private javax.swing.JLabel jLabel5;
  345.     private javax.swing.JTextField jTextField1;
  346.     private javax.swing.JTextField jTextField2;
  347.     // End of variables declaration                  
  348. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement