ANNFileDetect.detectFile.java Source code

Java tutorial

Introduction

Here is the source code for ANNFileDetect.detectFile.java

Source

/*
 * Copyright 2013 ragnar0k@fabytes.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ANNFileDetect;

/**
 *
 * @author ragnar0k@fabytes.com
 */

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;

public class detectFile extends javax.swing.JFrame {

    SQLiteLib sql;
    String nndir;
    HashMap invt;
    ArrayList scores;

    /**
     * Creates new form detectFile
     */
    public detectFile(SQLiteLib sqldb, String nnets) {
        initComponents();
        sql = sqldb;
        nndir = nnets;
    }

    private class StartFileBrowser implements Runnable {

        CountDownLatch ctd;
        String txt = "";

        public StartFileBrowser(String boxTxt) {
            txt = boxTxt;
        }

        public final void run() {
            ctd = new CountDownLatch(1);
            SelectFiles sf = null;
            if (txt.length() > 0)
                sf = new SelectFiles("ALL", "*", ctd, txt);
            else
                sf = new SelectFiles("ALL", "*", ctd);
            sf.setVisible(true);
            try {
                ctd.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            String tmp = sf.returnSelected();
            sf.dispose();
            FileBox.setText(tmp);
        }
    }

    /**
     * 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() {

        FileBox = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        Result = new javax.swing.JLabel();
        ResField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        Detection = new javax.swing.JButton();
        GPanel = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Choose file to identify");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        Result.setText("Result:");

        ResField.setEnabled(false);

        jLabel1.setText("Result Breakdown");

        Detection.setText("Detect!");
        Detection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DetectionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout GPanelLayout = new javax.swing.GroupLayout(GPanel);
        GPanel.setLayout(GPanelLayout);
        GPanelLayout.setHorizontalGroup(GPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 0, Short.MAX_VALUE));
        GPanelLayout.setVerticalGroup(GPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 272, Short.MAX_VALUE));

        jButton2.setText("Get detailed results");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(GPanel, javax.swing.GroupLayout.Alignment.TRAILING,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                Short.MAX_VALUE)
                        .addComponent(ResField)
                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 178,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(FileBox, javax.swing.GroupLayout.PREFERRED_SIZE, 623,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(jLabel1).addComponent(Result)
                                        .addComponent(Detection, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addComponent(jButton2)).addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1).addComponent(FileBox,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(9, 9, 9).addComponent(Detection).addGap(18, 18, 18).addComponent(Result)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ResField, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GPanel, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jButton2)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        CountDownLatch ctd = new CountDownLatch(1);
        String txt = FileBox.getText();
        new Thread(new StartFileBrowser(txt)).start();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void DetectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DetectionActionPerformed
        ResField.setText("");
        EncogTestClass ec = new EncogTestClass();
        String[] nets = sql.GetNetworkNames();
        HashMap resulthm = new HashMap();
        scores = new ArrayList();
        for (String net : nets) {
            ec.removeStdDirs();
            String netfile = sql.GetNetworkFile(net);
            String FPnetfile = sql.GetNetworkFPFile(net);
            ec.runNet(FileBox.getText(), nndir + "/" + netfile, false, 0);
            double out = ec.testSingleFPfile(nndir + "/" + FPnetfile);
            HashMap hm = sql.GetValuescore(net, out);
            resulthm.put(net, hm);
            scores.add("Net: " + net + " Score: " + out);
        }
        //make an inventory of all possible files
        Iterator it = resulthm.entrySet().iterator();
        HashMap inventory = new HashMap();
        while (it.hasNext()) {
            Map.Entry entries = (Map.Entry) it.next();
            Iterator itb = ((HashMap) entries.getValue()).entrySet().iterator();
            while (itb.hasNext()) {
                Map.Entry pair = (Map.Entry) itb.next();
                String file = (String) pair.getKey();
                String[] tmpvw = ((String) pair.getValue()).split(",");
                double score = Double.parseDouble(tmpvw[0]);
                double weight = Double.parseDouble(tmpvw[1]);

                if (inventory.containsKey(file)) {
                    String caz = inventory.get(file).toString();
                    double curscore = Double.parseDouble(caz);
                    double out = 0.0;
                    if (score > 1)
                        out = ((curscore + ((score * weight) / 100)) / 2);
                    if (score == 0)
                        out = (curscore / 2);
                    inventory.put(file, out);
                } else {
                    inventory.put(file, (score * weight) / 100);
                }

            }
        }
        String file = sql.GetFinalResultsMetrics(inventory);
        if (file.length() > 0)
            ResField.setText("File is likely to be a " + file);
        else
            ResField.setText("No file detected");
        JFreeChart jf = new GraphingClass().chartOutcome(inventory);
        ChartPanel cp = new ChartPanel(jf);
        cp.setSize(new Dimension(GPanel.getWidth(), GPanel.getHeight()));
        cp.setVisible(true);
        GPanel.removeAll();
        GPanel.add(cp);
        GPanel.repaint();
        GPanel.setVisible(true);
        System.out.println();
        invt = resulthm;

    }//GEN-LAST:event_DetectionActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        Iterator it = invt.entrySet().iterator();
        String toPrint = "";
        for (int i = 0; i < scores.size(); i++)
            toPrint = toPrint + scores.get(i) + "\n";
        toPrint = toPrint + "\n\n";
        while (it.hasNext()) {
            Map.Entry entries = (Map.Entry) it.next();
            toPrint = toPrint + "Network: " + entries.getKey() + "\n";
            HashMap tmphm = (HashMap) entries.getValue();
            Iterator at = tmphm.entrySet().iterator();
            while (at.hasNext()) {
                Map.Entry ent = (Map.Entry) at.next();
                toPrint = toPrint + "File: " + ent.getKey() + " Score: " + ent.getValue() + "\n";
            }
            toPrint = toPrint + "\n\n";
        }
        //new Thread(new Display(toPrint)).start();
        Display disp = new Display(toPrint);
        disp.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @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(detectFile.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(detectFile.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(detectFile.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(detectFile.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //new detectFile().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Detection;
    private javax.swing.JTextField FileBox;
    private javax.swing.JPanel GPanel;
    private javax.swing.JTextField ResField;
    private javax.swing.JLabel Result;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}