Package getfacts.conf

Source Code of getfacts.conf.ConfigurationFrame

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package getfacts.conf;

import getfacts.Configuration;
import getfacts.ConfigurationItems;
import getfacts.ConfigurationSafe;
import getfacts.NewsSafe;
import getfacts.plugins.HtmlReader;
import getfacts.plugins.feeds.RssReader;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.SqlJetTransactionMode;
import org.tmatesoft.sqljet.core.table.ISqlJetCursor;
import org.tmatesoft.sqljet.core.table.ISqlJetTable;
import org.tmatesoft.sqljet.core.table.SqlJetDb;

/**
*
* @author jmc15
*/
public class ConfigurationFrame
extends javax.swing.JFrame
{
    private Configuration configuration;
   
    /**
     * Creates new form ConfigurationFrame
     */
    public ConfigurationFrame()
    {
        initComponents();
        configurationItemsList.setCellRenderer( new ConfigurationItemsListRenderer() );
    }

    private File getTemplatesDbFile()
    {
        InputStream is = getClass().getResourceAsStream("/getfacts/conf/templates.db");       
        try
        {
            File templatesFile = new File( NewsSafe.getBaseDir(), "templates.db" );
            FileOutputStream fos = new FileOutputStream(templatesFile);
            try
            {
                byte[] buffer = new byte[2048];
                int count = is.read(buffer);
                while(count > 0 )
                {
                    fos.write(buffer, 0, count);
                    count = is.read(buffer);
                }
                return templatesFile;
            }
            finally
            {
                fos.close();
            }
        }
        catch(Exception ex)
        {
            Logger.getLogger(ConfigurationFrame.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException ex)
            {
                Logger.getLogger(ConfigurationFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
   
   
    private JMenu FindMenu(JMenu parent, String s)
    {
        for(int i=0; i<parent.getMenuComponentCount(); i++)
        {
            Component p = parent.getMenuComponent(i);
            if( p instanceof JMenu )
            {
                JMenu menu = (JMenu)p;
                if(menu.getText().compareToIgnoreCase(s)==0 )
                {
                    return menu;
                }
            }
        }
       
        JMenu menu = new JMenu(s);
        parent.add(menu);
        return menu;
    }
   
    private void initRssReaderTemplates()
    {
        try
        {
            // open the storage area
            File dbFile = getTemplatesDbFile();          

            SqlJetDb db = SqlJetDb.open(dbFile, false);

            try
            {
                db.beginTransaction(SqlJetTransactionMode.READ_ONLY);
                try
                {
                    ISqlJetTable table = db.getTable("RssReader");
                    ISqlJetCursor cursor = table.open();
                    try
                    {
                        do
                        {
                            final String feedLanguage = cursor.getString("language");
                            final String feedTitle = cursor.getString("title");
                            final String feedUrl = cursor.getString("url");
                           
                            JMenu parent = FindMenu(rssFeedsMenu, feedLanguage);
                            JMenuItem item = new JMenuItem(feedTitle);
                           
                            item.addActionListener( new ActionListener()
                            {
                                @Override
                                public void actionPerformed(ActionEvent ae)
                                {
                                    addRssReader(feedTitle, feedUrl);
                                }
                            });
                           
                            parent.add(item);

                        }while( cursor.next() );
                    }
                    finally
                    {
                        cursor.close();
                    }
                }
                finally
                {
                    db.rollback();
                }
            }
            finally
            {
                db.close();
            }
        }
        catch (SqlJetException ex)
        {
            Logger.getLogger(ConfigurationFrame.class.getName()).log(Level.SEVERE, null, ex);
        }     
    }
   
    private void addRssReader(String title, String url)
    {
        // verify if configuration entry with same title
        // already exists
        if( configuration.exists(title) == true )
        {
            throw new IllegalArgumentException(title);
        }
       
        ConfigurationItems config = RssReader.createConfig(title, url);
        configuration.addConfiguration(config);
    }
      
    private void initHtmlReaderTemplates()
    {
        try
        {
            // open the storage area
            File dbFile = getTemplatesDbFile();          

            SqlJetDb db = SqlJetDb.open(dbFile, false);

            try
            {
                db.beginTransaction(SqlJetTransactionMode.READ_ONLY);
                try
                {
                    ISqlJetTable table = db.getTable("HtmlReader");
                    ISqlJetCursor cursor = table.open();
                    try
                    {
                        do
                        {
                            final String siteLanguage = cursor.getString("language");
                            final String siteTitle = cursor.getString("title");
                            final String siteUrl = cursor.getString("url");
                            final String xpathToFrontPageTitle = cursor.getString("xp_fp_title");
                            final String xpathToArticleNodes = cursor.getString("xp_a_nodes");
                            final String xpathToArticleTitle = cursor.getString("xp_a_title");
                            final String xpathToArticleContent = cursor.getString("xp_a_content");
                            final String xpathToArticleUrl = cursor.getString("xp_a_url");
                            final String xpathToArticleGuid = cursor.getString("xp_a_guid");
                            final String xpathToArticleImageUrl = cursor.getString("xp_a_img");
                            final String xpathToArticlePubDate = cursor.getString("xp_a_date");
                           
                            JMenu parent = FindMenu(websitesMenu, siteLanguage);
                            JMenuItem item = new JMenuItem(siteTitle);
                           
                            item.addActionListener( new ActionListener()
                            {
                                @Override
                                public void actionPerformed(ActionEvent ae)
                                {
                                    addHtmlReader(siteTitle, siteUrl,
                                            xpathToFrontPageTitle,
                                            xpathToArticleNodes,
                                            xpathToArticleTitle,
                                            xpathToArticleContent,
                                            xpathToArticleUrl,
                                            xpathToArticleGuid,
                                            xpathToArticleImageUrl,
                                            xpathToArticlePubDate);
                                }                           
                            });
                           
                            parent.add(item);

                        }while( cursor.next() );
                    }
                    finally
                    {
                        cursor.close();
                    }
                }
                finally
                {
                    db.rollback();
                }
            }
            finally
            {
                db.close();
            }
        }
        catch (SqlJetException ex)
        {
            Logger.getLogger(ConfigurationFrame.class.getName()).log(Level.SEVERE, null, ex);
        }     
    }
   
   
    private void addHtmlReader(String title, String url,
            String xpathToFrontPageTitle,
            String xpathToArticleNodes,
            String xpathToArticleTitle,
            String xpathToArticleContent,
            String xpathToArticleUrl,
            String xpathToArticleGuid,
            String xpathToArticleImageUrl,
            String xpathToArticlePubDate)
    {
        // verify if configuration entry with same title
        // already exists
        if( configuration.exists(title) == true )
        {
            throw new IllegalArgumentException(title);
        }
       
        ConfigurationItems config = HtmlReader.createConfig(title, url,
                 xpathToFrontPageTitle,
                 xpathToArticleNodes,
                 xpathToArticleTitle,
                 xpathToArticleContent,
                 xpathToArticleUrl,
                xpathToArticleGuid,
                xpathToArticleImageUrl,
                xpathToArticlePubDate);
        configuration.addConfiguration(config);
    }   
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        centralSplitPane = new javax.swing.JSplitPane();
        configurationItemsPanel = new javax.swing.JPanel();
        configurationItemsScrollPane = new javax.swing.JScrollPane();
        configurationItemsList = new javax.swing.JList();
        configPanelScrollPane = new javax.swing.JScrollPane();
        globalMenuBar = new javax.swing.JMenuBar();
        jConfigMenu = new javax.swing.JMenu();
        jSaveAndExitMenuItem = new javax.swing.JMenuItem();
        jFeedsMenu = new javax.swing.JMenu();
        rssFeedsMenu = new javax.swing.JMenu();
        websitesMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        centralSplitPane.setDividerLocation(400);

        configurationItemsPanel.setLayout(new java.awt.BorderLayout());

        configurationItemsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        configurationItemsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                configurationItemsListValueChanged(evt);
            }
        });
        configurationItemsList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                configurationItemsListKeyPressed(evt);
            }
        });
        configurationItemsScrollPane.setViewportView(configurationItemsList);

        configurationItemsPanel.add(configurationItemsScrollPane, java.awt.BorderLayout.CENTER);

        centralSplitPane.setLeftComponent(configurationItemsPanel);
        centralSplitPane.setRightComponent(configPanelScrollPane);

        getContentPane().add(centralSplitPane, java.awt.BorderLayout.CENTER);

        jConfigMenu.setText("Configuration");

        jSaveAndExitMenuItem.setText("Save and exit");
        jSaveAndExitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jSaveAndExitMenuItemActionPerformed(evt);
            }
        });
        jConfigMenu.add(jSaveAndExitMenuItem);

        globalMenuBar.add(jConfigMenu);

        jFeedsMenu.setText("Feeds");

        rssFeedsMenu.setText("Rss feeds");
        jFeedsMenu.add(rssFeedsMenu);

        websitesMenu.setText("Web sites");
        jFeedsMenu.add(websitesMenu);

        globalMenuBar.add(jFeedsMenu);

        setJMenuBar(globalMenuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        // Read existing configuration
        configuration = ConfigurationSafe.loadConfiguration();
        configurationItemsList.setModel(configuration);
       
        // Open "templates" database to load RssReader templates
        initRssReaderTemplates();
       
        // Open "templates" database to load WebSites templates
        initHtmlReaderTemplates();
       
    }//GEN-LAST:event_formWindowOpened

    private void configurationItemsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_configurationItemsListValueChanged

        if( evt.getValueIsAdjusting()==false )
        {
            Object selection = configurationItemsList.getSelectedValue();
            if( selection instanceof ConfigurationItems )
            {
                showConfigurationItemsPanel( (ConfigurationItems)selection );
            }
        }  
    }//GEN-LAST:event_configurationItemsListValueChanged

    private void jSaveAndExitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSaveAndExitMenuItemActionPerformed
        try {
            ConfigurationSafe.saveConfiguration(configuration);
        } catch (IOException ex) {
            Logger.getLogger(ConfigurationFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.exit(0);
    }//GEN-LAST:event_jSaveAndExitMenuItemActionPerformed

    private void configurationItemsListKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_configurationItemsListKeyPressed
        switch(evt.getKeyCode())
        {
            case KeyEvent.VK_DELETE:
                deleteConfigurationItems();
                break;
        }
    }//GEN-LAST:event_configurationItemsListKeyPressed

    private void showConfigurationItemsPanel(ConfigurationItems config) {
        ConfigurationPanel cp = new ConfigurationPanel(config);
        configPanelScrollPane.setViewportView(cp);
    }
   
   
    private void deleteConfigurationItems()
    {
        // retrieve selected entry
        //int index = configurationItemsList.getSelectedIndex();
        Object o = configurationItemsList.getSelectedValue();
        configuration.removeConfiguration( (ConfigurationItems)o );
        // verify if configuration entry with same title
        // already exists
        /*if( configuration.exists(title) == true )
        {
            throw new IllegalArgumentException(title);
        }
       
        ConfigurationItems config =
        configuration.removeConfiguration(config);
        */
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConfigurationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConfigurationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConfigurationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConfigurationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ConfigurationFrame().setVisible(true);
            }
        });
    }
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSplitPane centralSplitPane;
    private javax.swing.JScrollPane configPanelScrollPane;
    private javax.swing.JList configurationItemsList;
    private javax.swing.JPanel configurationItemsPanel;
    private javax.swing.JScrollPane configurationItemsScrollPane;
    private javax.swing.JMenuBar globalMenuBar;
    private javax.swing.JMenu jConfigMenu;
    private javax.swing.JMenu jFeedsMenu;
    private javax.swing.JMenuItem jSaveAndExitMenuItem;
    private javax.swing.JMenu rssFeedsMenu;
    private javax.swing.JMenu websitesMenu;
    // End of variables declaration//GEN-END:variables
}
TOP

Related Classes of getfacts.conf.ConfigurationFrame

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.