asked on
public class Interface extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
static RrdDb rrdDb;
public TablePanel tablePanel;
boolean finish = false;
public JButton b,cln,q,c,d,chg,dta;
public JMenuItem enregistrer,exitAction ,ca,dem,Arr;
JMenu File;
JMenuBar bmenu;
public static JLabel label ;
public static JTextField text;
JTextArea dt;
JTable table;
private JProgressBar progress;
Thread t;
Border blackline, raisedetched, loweredetched,raisedbevel, loweredbevel, empty;
static final long START = Util.getTimestamp(2011,05,16);
static final long END = Util.getTimestamp(2011,05,16);
static final int MAX_STEP = 300;
long start = START;
long end = END;
static final String FILE = "Test de creation RRD4J";
static final long SEED = 1909752002L;
static final Random RANDOM = new Random(SEED);
static String rrdPath = Util.getRrd4jDemoPath(FILE + ".rrd");
String logPath = Util.getRrd4jDemoPath(FILE + ".log");
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(b)|| e.getSource().equals(dem) ){
this.finish = false;
t = new Thread() {
public void run() {
while(!finish )
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));//cursseur wait
progress.setIndeterminate(true);
new Packets().simulate();
}
}
};
t.start();
}
if (e.getSource().equals(c)|| e.getSource().equals(Arr) ){
finishThread();
t.interrupt();
t.stop();
progress.setIndeterminate(false);
updateBd();
}
if(e.getSource().equals(d)|| e.getSource().equals(enregistrer) ){
JFileChooser filechoose = new JFileChooser();
filechoose.setCurrentDirectory(new File("."));
String approve = new String("ENREGISTRER");
int resultatEnregistrer = filechoose.showDialog(filechoose,approve); // Pour afficher le JFileChooser…
if (resultatEnregistrer ==JFileChooser.APPROVE_OPTION) // Si l’utilisateur clique
{ String monFichier= new String(filechoose.getSelectedFile().toString());
if(monFichier.endsWith(".txt")|| monFichier.endsWith(".TXT")) {;}
else monFichier = monFichier + ".txt";
{
try
{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(monFichier,true));
PrintWriter fileWriter = new PrintWriter(bufferedWriter);
for(int i=0; i<( table.getRowCount()); ++i)
{
for(int j=0; j<table.getColumnCount(); ++j)
{
String s = table.getValueAt(i,j).toString();
fileWriter.print(s);
}
fileWriter.println("");
}
fileWriter.close();
JOptionPane.showMessageDialog(null, "Votre fichier a été enregistré avec succès");
}catch(Exception e1)
{
JOptionPane.showMessageDialog(null,"L'enregistrement n'est pas effecué");
}
}
}
}
if(e.getSource().equals(dta)){
dt.setSelectionEnd(dt.getText().length());
String TypePO;
int ligne = table.getSelectedRow();
Object cellule = table.getValueAt(ligne, 1);
Object cellule1 = table.getValueAt(ligne, 8);
Object cellule2 = table.getValueAt(ligne, 9);
Object cellule3 = table.getValueAt(ligne, 7);
String dc=cellule.toString();
String dc1=cellule1.toString();
String dc3=cellule2.toString();
String dc2=cellule3.toString();
if(dc2.equals("TCP")){
TypePO="(Transmission Controle Protocol)";
}
else TypePO="(User Datagram Protocol)";
dt.setText("Numero du paquet:"+(ligne+1)+"\t"+"\t"+"Type de protocole:"+TypePO+"\n"+"\n"+"IP source:"+
dc.substring(1, dc.indexOf('-'))+"\t"+"\t"+"Port source:"+dc1+"\n"+"\n"+"IP destination :"+dc.substring(dc.indexOf('>')+2)+"\t"+"\t"+"Port destination:"+dc3);
}
if(e.getSource().equals(q)||e.getSource().equals(exitAction ) ){
JOptionPane.showMessageDialog(null,"Vous voulez vraiment quitter l'application?");
System.exit(0);
}
if(e.getSource().equals(ca)||e.getSource().equals(chg)){
NetworksInterface Ink= new NetworksInterface();
String[] carte =new String[3];
carte=Ink.remplirTable(carte);
String txt= (String) JOptionPane.showInputDialog(null,"Choisissez la carte reseaux svp:","CARTE RESEAUX",JOptionPane.QUESTION_MESSAGE,null,carte, carte[1]);
if (txt==null)
JOptionPane.showMessageDialog(null,"pas de choix effectue");
else
text.setText(txt);
}
if((e.getSource().equals(cln)||e.getSource().equals(chg))){
DefaultTableModel modele = (DefaultTableModel)table.getModel();
modele.setRowCount(0);
table.setModel(modele);
table.repaint();
for(int i = modele.getRowCount(); i > 0; --i)
modele.removeRow(i-1);
}
}
public void actionPerformed(MouseEvent e) {
table.getToolTipText( e);
}
@SuppressWarnings("deprecation")
public void finishThread(){
this.finish = true;
t.stop();
}
public void setGui() {
try {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Network Analyser");
setDefaultLookAndFeelDecorated(UIManager.getLookAndFeel().getSupportsWindowDecorations());
setDefaultLookAndFeelDecorated(true);
Container cp = getContentPane();
JPanel bPanel = new JPanel();
JPanel bPanel1 = new JPanel();
bPanel1.setLayout(new BoxLayout(bPanel1,BoxLayout.LINE_AXIS));
bPanel1.setBorder(BorderFactory.createEmptyBorder(5,2,2,5));
progress =new JProgressBar();
progress.setBackground(new Color(0, 204, 110));
JMenuBar bmenu = new JMenuBar();
setJMenuBar(bmenu);
JMenu File = new JMenu("File");
bmenu.add(File);
enregistrer = new JMenuItem("enregistrer");
exitAction =new JMenuItem("Exit");
ca=new JMenuItem("Changer la carte reseaux");
File.add(ca);
File.add(enregistrer);
File.add(exitAction );
File.insertSeparator(2);
JMenu analyser = new JMenu(" Analyse");
dem = new JMenuItem("Demarrer l'analyse");
Arr=new JMenuItem("Arrêter l'analyse");
analyser.add(dem);
analyser.add(Arr);
analyser.insertSeparator(1);
JMenu editMenu = new JMenu(" Edit");
String[] editItems = new String[] { "Undo", "Cut", "Copy", "Paste" };
add(editMenu);
editMenu.insertSeparator(2);
bmenu.add(editMenu);
bmenu.add(analyser);
for (int i = 0; i < editItems.length; i++) {
JMenuItem item = new JMenuItem(editItems[i]);
editMenu.add(item);
}
Font f = new Font("Sanserif", ALLBITS, 12);
JLabel label1=new JLabel("Carte réseau selectionner:");
label1.setForeground(new Color(21, 38, 147));
label1.setFont(f);
dt = new JTextArea();
label1.setLayout(null);
tablePanel = new TablePanel();
b = new JButton("", new ImageIcon("C:/Users/Raéd/icons/1303671431_search_button.png"));
q = new JButton ("", new ImageIcon("C:/Users/Raéd/icons/1303953412_button_59.png"));
c = new JButton ("", new ImageIcon("C:/Users/Raéd/icons/1303674426_PauseHot.png"));
d= new JButton("", new ImageIcon("C:/Users/Raéd/icons/1303671832_save_download.png"));
cln=new JButton("", new ImageIcon("C:/Users/Raéd/icons/1303674737_paint.png"));
chg=new JButton("", new ImageIcon("C:/Users/Raéd/icons/1303673596_interact.png"));
dta = new JButton("",new ImageIcon("C:/Users/Raéd/icons/1303952450_taskbar.png"));
q.setFocusPainted(false);
q.setBorderPainted(true);
q.setContentAreaFilled(false);
b.setToolTipText("Démarrer la capture du paquet IP.");
q.setToolTipText("Quitter l'application.");
c.setToolTipText("Arréter la capture du paquet.");
d.setToolTipText("Enregistrer les paquet dans un fichier texte.");
cln.setToolTipText("Nettoyer le tableau.");
chg.setToolTipText("Séléctionner la carte reseau.");
dta.setToolTipText("Afficher les détail du paquet Selectionner.");
q.addActionListener(this);
cln.addActionListener(this);
b.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
enregistrer.addActionListener(this);
chg.addActionListener(this);
exitAction.addActionListener(this);
ca.addActionListener(this);
dem.addActionListener(this);
Arr.addActionListener(this);
dta.addActionListener(this);
bPanel1.add(label1);
bPanel1.add(text);
text.setBackground(new Color(0, 204, 110));
bPanel1.add(b);
bPanel1.add(c);
bPanel1.add(dta);
bPanel1.add(Box.createHorizontalStrut(5));
bPanel1.add(new JSeparator(SwingConstants.VERTICAL));
bPanel1.add(Box.createHorizontalStrut(5));
bPanel1.add(cln);
bPanel1.add(d);
bPanel1.add(Box.createHorizontalStrut(5));
bPanel1.add(new JSeparator(SwingConstants.VERTICAL));
bPanel1.add(Box.createHorizontalStrut(5));
bPanel1.add(chg);
bPanel1.add(Box.createHorizontalStrut(5));
bPanel1.add(new JSeparator(SwingConstants.VERTICAL));
bPanel1.add(Box.createHorizontalStrut(5));
bPanel1.add(q);
blackline = BorderFactory.createLineBorder(Color.black);
//raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
//raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
progress.setPreferredSize(new Dimension(60,90));
/*bPanel.add(Box.createHorizontalStrut(6));
bPanel.add(new JSeparator(SwingConstants.VERTICAL));
bPanel.add(Box.createHorizontalStrut(6));*/
dt.setPreferredSize(new Dimension(900,90));
bPanel.setBorder(BorderFactory.createCompoundBorder(loweredbevel,loweredetched));
bPanel.add(dt, FlowLayout.LEFT);
bPanel.add(progress);
text.setEditable(false);
dt.setEditable(false);
dt.setFont(new Font("Serif", Font.BOLD, 12));
dt.setSelectedTextColor(Color.GREEN);
dt.setCaretColor(Color.BLUE);
dt.setSelectionColor(Color.BLUE);
cp.add(tablePanel,BorderLayout.CENTER);
cp.add(bPanel, BorderLayout.PAGE_END);
cp.add(bPanel1,BorderLayout.NORTH);
} catch (Exception e) {
e.printStackTrace();
}
}
public void rrd4j(){
//PrintWriter log;
try {
//log = new PrintWriter(new BufferedOutputStream(new FileOutputStream(logPath, false)));
long startTime = System.currentTimeMillis();
System.out.println("== Creating RRD file " + rrdPath);
RrdDef rrdDef = new RrdDef(rrdPath, startTime, 300);
rrdDef.setVersion(2);
rrdDef.addDatasource("http", DsType.COUNTER, 600, 0, Double.NaN);
rrdDef.addDatasource("local", DsType.COUNTER, 600, 0, Double.NaN);
rrdDef.addArchive(AVERAGE, 0.5, 1, 600); // 1 step, 600 rows
rrdDef.addArchive(AVERAGE, 0.5, 6, 700); // 6 steps, 700 rows
rrdDef.addArchive(MAX, 0.5, 1, 600);
//log.println(rrdDef.dump());
System.out.println("Estimated file size: " + rrdDef.getEstimatedSize());
RrdDb rrdDb = new RrdDb(rrdDef);
System.out.println("== RRD file created.");
if (rrdDb.getRrdDef().equals(rrdDef)) {
System.out.println("Checking RRD file structure... OK");
} else {
System.out.println("Invalid RRD file created. This is a serious bug, bailing out");
return;
}
rrdDb.close();
System.out.println("== RRD file closed.");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updateBd(){
System.out.println("== Simulating one month of RRD file updates with step not larger than " +
MAX_STEP + " seconds (* denotes 1000 updates)");
long t = start;
int f=1305512473;
int n = 0;
try {
rrdDb = new RrdDb(rrdPath);
Sample sample = rrdDb.createSample();
sample.setTime(f*900);
for(int i=0;i< table.getRowCount();i++) {//convertir la valeur du tableau d'un objet a double
if (table.getValueAt(i, 8)==null)
{ i++;
}
Object cellul = table.getValueAt(i, 8);
String dc=cellul.toString();
double empid = 0;
if(dc != null && (!dc.equals("")) ) {
empid = Double.parseDouble(dc);
}
//nombre = Double.parseDouble(field4);
sample.setValue("http", empid );
// sample.setValue("local", (Double) table.getValueAt(3, 5));
// log.println(sample.dump());
sample.update();
t += RANDOM.nextDouble() * MAX_STEP + 1;
if (((++n) % 1000) == 0) {
System.out.print("*");
}
}
rrdDb.close();
System.out.println("");
System.out.println("== Finished. RRD file updated " + n + " times");
} catch (IOException e) {
e.printStackTrace();
System.out.println("save data error");
}
}
public class Packets {
public void simulate() {
try {
PacketCaptureSimulator sim = new PacketCaptureSimulator();
sim.addPacketListener(tablePanel);
sim.capture(1);
sim.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public class NetworksInterface extends java.lang.Object {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
@SuppressWarnings("restriction")
public String[] remplirTable(String[] table){
for (int i = 0; i < devices.length; i++){
table[i]=i+ devices[i].name+" "+(devices[i].description);
}
return table;
}
public void ShowInterface(){
{
JpcapCaptor.getDeviceList();
for (int i = 0; i < devices.length; i++) {
System.out.println(i+": "+devices[i].name + "(" + devices[i].description+")");
System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")");
System.out.print(" MAC address:");
for (byte b : devices[i].mac_address){
System.out.print(Integer.toHexString(b&0xff) + ":");
System.out.println();
}
for (NetworkInterfaceAddress a : devices[i].addresses){
System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);
}
}
}
}
public void OpenInterface(int index){
JpcapCaptor captor=null;
try {
captor = JpcapCaptor.openDevice(devices[index], 65535 , false, 20);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,"Pas de connection internet detecté,vérifier ta connection svp!!");
e.printStackTrace();
}
System.out.println( captor);
}
@SuppressWarnings("restriction")
public String[] affichePaquet(int index) throws IOException{
JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535 , false, 20);
String pak;
pak=captor.getPacket().toString();
for(;;){
if (((captor.getPacket()==null)))
{//String[] data ={"null","null","null","null","null","null","null","null","null","null","null","null"};
captor.close();
}
String[] data =pak.split(" ");
captor.close();
return data;
}
}
}
public class TablePanel extends JPanel implements PacketListener {
/**
* @return
*
*/
private static final long serialVersionUID = 3L;
Object[] headers = {
"Adresse MAC Source","@ IP source->@ IP destination",
"Protocole","priority","eli","numéro de saut","eli","Fragment Offset","numéro d'identification","protocole de transmission","port Source","eli","port destination"
};
public TablePanel() {
table = new JTable(new DefaultTableModel(null, headers))
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column );
if ((row & 1) == 0) { // Ligne paire
comp.setBackground(new Color(135, 213, 242));
} else { // Ligne impaire
comp.setBackground(new Color(204, 222, 229));
}
return comp;
}
};
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("eli")));
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("eli")));
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("eli")));
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(170);
table.setPreferredScrollableViewportSize(new Dimension(950, 400));
add(new JScrollPane(table));
}
NetworksInterface Ink1=new NetworksInterface();
public void packetArrived(Packet packet) {
//int ni=Integer.parseInt(text.getText());
try {
updateTable(Ink1.affichePaquet(0));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updateTable(final String[] info) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(info);
}
});
}
}
public static void main(String[] args) {
try
{
UIManager.setLookAndFeel(new SyntheticaBlueMoonLookAndFeel());
JFrame.setDefaultLookAndFeelDecorated(UIManager.getLookAndFeel().getSupportsWindowDecorations());
JFileChooser.setDefaultLocale(new Locale("en","US"));
}
catch (Exception e)
{
e.printStackTrace();
}
NetworksInterface Ink= new NetworksInterface();
String[] carte =new String[3];
carte=Ink.remplirTable(carte);
String txt= (String) JOptionPane.showInputDialog(null,"Choisissez la carte reseaux svp:","CARTE RESEAUX",JOptionPane.QUESTION_MESSAGE,null,carte, carte[1]);
if (txt==null)
JOptionPane.showMessageDialog(null,"Pas de choix effectué !!");
else
text=new JTextField(txt);
//ni=Integer.parseInt(txt.substring(0));
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
Interface f = new Interface();
f.setGui();
f.pack();
f.setVisible(true);
f.rrd4j();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class TablePanel extends JPanel implements PacketListener {
/**
* @return
*
*/
private static final long serialVersionUID = 3L;
Object[] headers = {
"Adresse MAC Source","@ IP source->@ IP destination",
"Protocole","priority","eli","numéro de saut","eli","Fragment Offset","numéro d'identification","protocole de transmission","port Source","eli","port destination"
};
public TablePanel() {
table = new JTable(new DefaultTableModel(null, headers))
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column );
if ((row & 1) == 0) { // Ligne paire
comp.setBackground(new Color(135, 213, 242));
} else { // Ligne impaire
comp.setBackground(new Color(204, 222, 229));
}
return comp;
}
};
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("eli")));
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("eli")));
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("eli")));
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(170);
table.setPreferredScrollableViewportSize(new Dimension(950, 400));
add(new JScrollPane(table));
}
NetworksInterface Ink1=new NetworksInterface();
public void packetArrived(Packet packet) {
//int ni=Integer.parseInt(text.getText());
try {
updateTable(Ink1.affichePaquet(0));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updateTable(final String[] info) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(info);
}
});
}
}
}
help please!!