mstover1    2002/08/21 16:35:48

  Modified:    src/components/org/apache/jmeter/visualizers
                        MailerVisualizer.java
  Added:       src/components/org/apache/jmeter/visualizers
                        ModelListener.java MailerModel.java
  Log:
  updates to mailer visualizer (Wolfram Rittmeyer)
  
  Revision  Changes    Path
  1.3       +154 -278  
jakarta-jmeter/src/components/org/apache/jmeter/visualizers/MailerVisualizer.java
  
  Index: MailerVisualizer.java
  ===================================================================
  RCS file: 
/home/cvs/jakarta-jmeter/src/components/org/apache/jmeter/visualizers/MailerVisualizer.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- MailerVisualizer.java     15 Aug 2002 15:37:06 -0000      1.2
  +++ MailerVisualizer.java     21 Aug 2002 23:35:48 -0000      1.3
  @@ -84,10 +84,12 @@
   import javax.swing.border.Border;
   import javax.swing.border.EmptyBorder;
   
  +import org.apache.log4j.Category;
   import org.apache.jmeter.gui.util.VerticalLayout;
   import org.apache.jmeter.samplers.Clearable;
   import org.apache.jmeter.samplers.SampleResult;
   import org.apache.jmeter.util.JMeterUtils;
  +import org.apache.jmeter.testelement.TestElement;
   import org.apache.jmeter.visualizers.gui.AbstractVisualizer;
   
   /*
  @@ -108,31 +110,15 @@
    *@created    $Date$
    *@version    $Revision$ $Date$
    ***********************************************************/
  -//public class MailerVisualizer extends JPanel implements Visualizer, ActionListener
  -public class MailerVisualizer extends AbstractVisualizer 
  -             implements ActionListener, FocusListener, Clearable {
  -
  -     private String addressie;
  -     private String from;
  -     private String smtpHost;
  -     private String failsubject;
  -     private String successsubject;
  -     private long failureCount = 0;
  -     private long successCount = 0;
  -     private long failureLimit = 2;
  -     private long successLimit = 2;
  -     private boolean failureMsgSent = false;
  -     private boolean siteDown = false;
  -     private boolean successMsgSent = false;
  -
  -     private Properties appProperties;
  +public class MailerVisualizer extends AbstractVisualizer
  +             implements ActionListener, FocusListener, Clearable, ModelListener {
   
        private JButton testerButton;
        private JTextField addressField;
        private JTextField fromField;
        private JTextField smtpHostField;
  -     private JTextField failsubjectField;
  -     private JTextField successsubjectField;
  +     private JTextField failureSubjectField;
  +     private JTextField successSubjectField;
        private JTextField failureField;
        private JTextField failureLimitField;
        private JTextField successLimitField;
  @@ -140,33 +126,19 @@
        private JPanel mainPanel;
        private JLabel panelTitleLabel;
   
  +     private MailerModel model;
   
  -     //-----------
  +     private static Category logger = 
Category.getInstance("org.apache.jmeter.visualizers.MailerVisualizer");
   
  -     /************************************************************
  -      *  !ToDo (Constructor description)
  -      ***********************************************************/
  +     /**
  +      * Constructs the MailerVisualizer and initializes its GUI.
  +      */
        public MailerVisualizer() {
                super();
   
  -             // Properties connection.
  -             this.appProperties = JMeterUtils.getJMeterProperties();
  -
  -             // retrieve successLimit from properties
  -             try {
  -                     successLimit =  
Long.parseLong(appProperties.getProperty("mailer.successlimit"));
  -             }
  -             catch (Exception ex) {
  -                     // Ignore any garbage
  -             }
  -
  -             // retrieve failureLimit from properties
  -             try {
  -                     failureLimit =  
Long.parseLong(appProperties.getProperty("mailer.failurelimit"));
  -             }
  -             catch (Exception ex) {
  -                     // Ignore any garbage
  -             }
  +             // construct the model
  +             model = new MailerModel();
  +             model.addModelListener(this);
   
                // initialize GUI.
                initGui();
  @@ -177,126 +149,28 @@
         *
         *@return    !ToDo (Return description)
         ***********************************************************/
  -     public synchronized boolean isFailing()
  -     {
  -             return (failureCount > failureLimit);
  -     }
  -
  -     /************************************************************
  -      *  !ToDoo (Method description)
  -      *
  -      *@return    !ToDo (Return description)
  -      ***********************************************************/
        public JPanel getControlPanel()
        {
                return this;
        }
   
  -
  -     /************************************************************
  -      *  !ToDo (Method description)
  -      *
  -      *@param  theAddressie  !ToDo (Parameter description)
  -      *@return               !ToDo (Return description)
  -      ***********************************************************/
  -     public synchronized Vector newAddressVector(String theAddressie)
  -     {
  -             Vector addressVector = new Vector();
  -             if (theAddressie != null) {
  -                     String addressSep = ", ";
  -     
  -                     StringTokenizer next = new StringTokenizer(theAddressie, 
addressSep);
  -     
  -                     while (next.hasMoreTokens())
  -                     {
  -                             String theToken = next.nextToken();
  -     
  -                             if (theToken.indexOf("@") > 0)
  -                             {
  -                                     addressVector.addElement(theToken);
  -                             }
  -                     }
  -             }
  -             else {
  -                     return new Vector(0);
  -             }
  -
  -             return addressVector;
  -     }
  -
  -
  -     /************************************************************
  -      *  !ToDo (Method description)
  +     /**
  +      * Adds a SampleResult. Actually this method just delegates calls
  +      * to the ActionModel.
         *
  -      *@param  sample  !ToDo (Parameter description)
  -      ***********************************************************/
  +      * @param sample The SampleResult encapsulating informations about the last 
sample.
  +      */
        public synchronized void add(SampleResult sample)
        {
  -
  -             // -1 is the code for a failed sample.
  -             //
  -             if (!sample.isSuccessful())
  -             {
  -                     failureCount++;
  -             }
  -             else
  -             {
  -                     successCount++;
  -             }
  -
  -             if (this.isFailing() && !siteDown && !failureMsgSent)
  -             {
  -                     // Display ...
  -                     failureField.setText(Long.toString(failureCount));
  -                     repaint();
  -
  -                     // Send the mail ...
  -                     Vector addressVector = newAddressVector(addressie);
  -                     if (addressVector.size() != 0) {
  -                             sendMail(from, addressVector, failsubject, "URL 
Failed: " +
  -                                             sample.getSampleLabel(), smtpHost);
  -                             siteDown = true;
  -                             failureMsgSent = true;
  -                             successCount = 0;
  -                     }
  -             }
  -
  -             if (siteDown && (sample.getTime() != -1) & !successMsgSent)
  -             {
  -                     // Display ...
  -                     failureField.setText(Long.toString(failureCount));
  -                     repaint();
  -
  -                     // Send the mail ...
  -                     if (successCount > successLimit)
  -                     {
  -                             Vector addressVector = newAddressVector(addressie);
  -                             sendMail(from, addressVector, successsubject, "URL 
Restarted: " +
  -                                             sample.getSampleLabel(), smtpHost);
  -                             siteDown = false;
  -                             successMsgSent = true;
  -                     }
  -             }
  -
  -             if (successMsgSent && failureMsgSent)
  -             {
  -                     clear();
  -             }
  +             model.add(sample);
        }
   
  -     /************************************************************
  -      *  !ToDo (Method description)
  -      ***********************************************************/
  +     /**
  +      * Clears any stored sampling-informations.
  +      */
        public synchronized void clear()
        {
  -             failureCount = 0;
  -             successCount = 0;
  -             siteDown = false;
  -             successMsgSent = false;
  -             failureMsgSent = false;
  -
  -             failureField.setText(Long.toString(failureCount));
  -             repaint();
  +             model.clear();
        }
   
        /************************************************************
  @@ -309,65 +183,6 @@
                return "E-Mail Notification";
        }
   
  -     //-----------
  -     //function to send a mail to list mailaddresses
  -
  -     /************************************************************
  -      *  !ToDo (Method description)
  -      *
  -      *@param  from      !ToDo (Parameter description)
  -      *@param  vEmails   !ToDo (Parameter description)
  -      *@param  subject   !ToDo (Parameter description)
  -      *@param  attText   !ToDo (Parameter description)
  -      *@param  SMTPHost  !ToDo (Parameter description)
  -      ***********************************************************/
  -     public static synchronized void sendMail(String from,
  -                     Vector vEmails,
  -                     String subject,
  -                     String attText,
  -                     String SMTPHost)
  -     {
  -             try
  -             {
  -                     String host = SMTPHost;
  -                     boolean debug = Boolean.valueOf(host).booleanValue();
  -                     InetAddress remote = InetAddress.getByName(host);
  -
  -                     InternetAddress[] address = new 
InternetAddress[vEmails.size()];
  -                     for (int k = 0; k < vEmails.size(); k++)
  -                     {
  -                             address[k] = new 
InternetAddress(vEmails.elementAt(k).toString());
  -                     }
  -
  -                     // create some properties and get the default Session
  -                     Properties props = new Properties();
  -                     props.put("mail.smtp.host", host);
  -                     Session session = Session.getDefaultInstance(props, null);
  -                     session.setDebug(debug);
  -
  -                     // create a message
  -                     Message msg = new MimeMessage(session);
  -                     msg.setFrom(new InternetAddress(from));
  -                     msg.setRecipients(Message.RecipientType.TO, address);
  -                     msg.setSubject(subject);
  -                     msg.setText(attText);
  -                     Transport.send(msg);
  -                     System.out.println("Mail sent successfully!!");
  -             }
  -             catch (UnknownHostException e1)
  -             {
  -                     System.out.println("Invalid Mail Server " + e1);
  -                     JOptionPane.showMessageDialog(null, 
JMeterUtils.getResString("invalid_mail_server"), "Error", JOptionPane.ERROR_MESSAGE);
  -                     //System.exit(1);
  -             }
  -             catch (Exception e)
  -             {
  -                     System.out.println("Couldn't send mail...");
  -                     JOptionPane.showMessageDialog(null, 
JMeterUtils.getResString("mailer_error"), "Error", JOptionPane.ERROR_MESSAGE);
  -                     //System.exit(1);
  -             }
  -     }
  -
        /**
         * Initializes the GUI. Lays out components and adds them to the
         * container.
  @@ -394,7 +209,7 @@
   
                // mailer panel
                JPanel mailerPanel = new JPanel();
  -             
mailerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
 getAttributesTitle()));
  +             
mailerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
 model.getAttributesTitle()));
                GridBagLayout g = new GridBagLayout();
                mailerPanel.setLayout(g);
                GridBagConstraints c = new GridBagConstraints();
  @@ -404,8 +219,7 @@
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("From:"));
   
  -             from = appProperties.getProperty("mailer.from");
  -             fromField = new JTextField(from, 25);
  +             fromField = new JTextField(model.getFromAddress(), 25);
                fromField.setEditable(true);
                fromField.addActionListener(this);
                fromField.addFocusListener(this);
  @@ -418,8 +232,7 @@
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("Addressie(s):"));
   
  -             addressie = appProperties.getProperty("mailer.addressies");
  -             addressField = new JTextField(addressie, 25);
  +             addressField = new JTextField(model.getToAddress(), 25);
                addressField.setEditable(true);
                addressField.addActionListener(this);
                addressField.addFocusListener(this);
  @@ -430,8 +243,7 @@
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("SMTP Host:"));
   
  -             smtpHost = appProperties.getProperty("mailer.smtphost");
  -             smtpHostField = new JTextField(smtpHost, 25);
  +             smtpHostField = new JTextField(model.getSmtpHost(), 25);
                smtpHostField.setEditable(true);
                smtpHostField.addActionListener(this);
                smtpHostField.addFocusListener(this);
  @@ -442,31 +254,29 @@
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("Failure Subject:"));
   
  -             failsubject = appProperties.getProperty("mailer.failsubject");
  -             failsubjectField = new JTextField(failsubject, 25);
  -             failsubjectField.setEditable(true);
  -             failsubjectField.addActionListener(this);
  -             failsubjectField.addFocusListener(this);
  +             failureSubjectField = new JTextField(model.getFailureSubject(), 25);
  +             failureSubjectField.setEditable(true);
  +             failureSubjectField.addActionListener(this);
  +             failureSubjectField.addFocusListener(this);
                c.gridwidth = GridBagConstraints.REMAINDER;
  -             g.setConstraints(failsubjectField, c);
  -             mailerPanel.add(failsubjectField);
  +             g.setConstraints(failureSubjectField, c);
  +             mailerPanel.add(failureSubjectField);
   
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("Success Subject:"));
   
  -             successsubject = appProperties.getProperty("mailer.successsubject");
  -             successsubjectField = new JTextField(successsubject, 25);
  -             successsubjectField.setEditable(true);
  -             successsubjectField.addActionListener(this);
  -             successsubjectField.addFocusListener(this);
  +             successSubjectField = new JTextField(model.getSuccessSubject(), 25);
  +             successSubjectField.setEditable(true);
  +             successSubjectField.addActionListener(this);
  +             successSubjectField.addFocusListener(this);
                c.gridwidth = GridBagConstraints.REMAINDER;
  -             g.setConstraints(successsubjectField, c);
  -             mailerPanel.add(successsubjectField);
  +             g.setConstraints(successSubjectField, c);
  +             mailerPanel.add(successSubjectField);
   
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("Failure Limit:"));
   
  -             failureLimitField = new JTextField(Long.toString(failureLimit), 6);
  +             failureLimitField = new 
JTextField(Long.toString(model.getFailureLimit()), 6);
                failureLimitField.setEditable(true);
                failureLimitField.addActionListener(this);
                failureLimitField.addFocusListener(this);
  @@ -477,7 +287,7 @@
                c.gridwidth = 1;
                mailerPanel.add(new JLabel("Success Limit:"));
   
  -             successLimitField = new JTextField(Long.toString(successLimit), 6);
  +             successLimitField = new 
JTextField(Long.toString(model.getSuccessLimit()), 6);
                successLimitField.setEditable(true);
                successLimitField.addActionListener(this);
                successLimitField.addFocusListener(this);
  @@ -511,7 +321,7 @@
         * as set up in the properties-file using the lookup-constant
         * "mailer_visualizer_title".
         *
  -      *@return  The title of the component.
  +      * @return  The title of the component.
         */
        public String getStaticLabel()
        {
  @@ -529,19 +339,16 @@
        {
                return JMeterUtils.getResString("mailer_attributes_panel");
        }
  +
        /**
  -     * Method used to log a String.
  -     *
  -     * @param str String to be logged.
  -     */
  +      * Method used to log a String.
  +      *
  +      * @param str String to be logged.
  +      */
        private static void log(String str) {
  -             // this is just a tewmporary solution
  -             // will be replaced by a call to the logging-API
  -             // of the commons-project.
  -             System.out.println("MailerVisualizer - " + str);
  +             logger.info(str);
        }
   
  -
        /**
         * Does the actual EventHandling. Gets called by EventHandlers
         * for either ActionEvents or FocusEvents.
  @@ -550,32 +357,37 @@
         */
        private void doEventHandling(Object source) {
                if (source == addressField) {
  -                     this.addressie = this.addressField.getText();
  -                     log("AddressField=" + addressField.getText());
  +                     model.setToAddress(this.addressField.getText());
                }
                else if (source == fromField) {
  -                     this.from = this.fromField.getText();
  -                     log("FromField=" + fromField.getText());
  +                     model.setFromAddress(this.fromField.getText());
                }
                else if (source == smtpHostField) {
  -                     this.smtpHost = this.smtpHostField.getText();
  -                     log("smtpHostField=" + smtpHostField.getText());
  +                     model.setSmtpHost(this.smtpHostField.getText());
                }
  -             else if (source == failsubjectField) {
  -                     this.failsubject = this.failsubjectField.getText();
  -                     log("failsubjectField=" + failsubjectField.getText());
  -             }
  -             else if (source == successsubjectField) {
  -                     this.successsubject = this.successsubjectField.getText();
  -                     log("successsubjectField=" + successsubjectField.getText());
  +             else if (source == failureSubjectField) {
  +                     model.setFailureSubject(this.failureSubjectField.getText());
  +             }
  +             else if (source == successSubjectField) {
  +                     model.setSuccessSubject(this.successSubjectField.getText());
                }
                else if (source == failureLimitField) {
  -                     this.failureLimit = 
Long.parseLong(this.failureLimitField.getText());
  -                     log("failureLimitField=" + failureLimitField.getText());
  +                     try {
  +                             
model.setFailureLimit(Long.parseLong(this.failureLimitField.getText()));
  +                     }
  +                     catch (NumberFormatException e) {
  +                             log("failureLimitField=" + 
failureLimitField.getText());
  +                             JOptionPane.showMessageDialog(null, 
JMeterUtils.getResString("you_must_enter_a_valid_number"), "Error", 
JOptionPane.ERROR_MESSAGE);
  +                     }
                }
                else if (source == successLimitField) {
  -                     this.successLimit = 
Long.parseLong(this.successLimitField.getText());
  +                     try {
  +                             
model.setSuccessLimit(Long.parseLong(this.successLimitField.getText()));
  +                     }
  +                     catch (NumberFormatException e) {
                        log("successLimitField=" + successLimitField.getText());
  +                     JOptionPane.showMessageDialog(null, 
JMeterUtils.getResString("you_must_enter_a_valid_number"), "Error", 
JOptionPane.ERROR_MESSAGE);
  +                     }
                }
        }
   
  @@ -586,34 +398,37 @@
        //
        //////////////////////////////////////////////////////////////
   
  -     /************************************************************
  -      *  !ToDo (Method description)
  +     /**
  +      * Reacts on an ActionEvent (like pressing a button).
         *
  -      *@param  e  !ToDo (Parameter description)
  -      ***********************************************************/
  +      * @param e The ActionEvent with information about the event and its source.
  +      */
        public void actionPerformed(ActionEvent e) {
                try {
                        JComponent c = (JComponent)e.getSource();
                        if (c == testerButton) {
  -                             log("### Test To:  " + this.addressie + ", " +
  -                                             "Via:  " + this.smtpHost + ", " +
  -                                             "Fail Subject:  " + this.failsubject + 
", " +
  -                                             "Success Subject:  " + 
this.successsubject);
  -
  -                             String testMessage = ("### Test To:  " + 
this.addressie + ", " +
  -                                             "Via:  " + this.smtpHost + ", " +
  -                                             "Fail Subject:  " + this.failsubject + 
", " +
  -                                             "Success Subject:  " + 
this.successsubject);
  -
  -                             Vector addressVector = newAddressVector(addressie);
  -                             sendMail(from, addressVector, "Testing addressies", 
testMessage, smtpHost);
  +                             String testString = "JMeter-Testmail" + "\n" +
  +                                                                     "To:  " + 
model.getToAddress() + "\n" +
  +                                                                     "Via:  " + 
model.getSmtpHost() + "\n" +
  +                                                                     "Fail Subject: 
 " + model.getFailureSubject() + "\n" +
  +                                                                     "Success 
Subject:  " + model.getSuccessSubject();
  +                             log(testString);
  +                             model.sendMail(model.getFromAddress(), 
model.getAddressVector(), "Testing mail-addresses", testString, model.getSmtpHost());
  +                             log("Mail sent successfully!!");
                        }
                        else {
                                doEventHandling(c);
                        }
                }
  -             catch (Exception ex)    {
  -                     JOptionPane.showMessageDialog(this, ex, "Error", 
JOptionPane.ERROR_MESSAGE);
  +             catch (UnknownHostException e1)
  +             {
  +                     log("Invalid Mail Server " + e1.toString());
  +                     
displayMessage(JMeterUtils.getResString("invalid_mail_server"), true);
  +             }
  +             catch (Exception ex)
  +             {
  +                     log("Couldn't send mail..." + ex.toString());
  +                     
displayMessage(JMeterUtils.getResString("invalid_mail_server"), true);
                }
        }
   
  @@ -642,6 +457,67 @@
                doEventHandling(source);
        }
   
  +     //////////////////////////////////////////////////////////////
  +     //
  +     // Methods used to store and retrieve the MailerVisualizer.
  +     //
  +     //////////////////////////////////////////////////////////////
  +
  +     /**
  +      * Restores MailerVisualizer.
  +      */
  +     public void configure(TestElement el)
  +     {
  +             super.configure(el);
  +             model.retrieveModel(el);
  +             updateVisualizer();
  +     }
  +
  +     /**
  +      * Makes MailerVisualizer storable.
  +      */
  +     public TestElement createTestElement()
  +     {
  +             TestElement element = super.createTestElement();
  +             model.storeModel(element);
  +             return element;
  +     }
  +
  +     //////////////////////////////////////////////////////////////
  +     //
  +     // Methods to implement the ModelListener.
  +     //
  +     //////////////////////////////////////////////////////////////
  +
  +     /**
  +      * Notifies this Visualizer about model-changes. Causes the Visualizer to
  +      * query the model about its new state.
  +      */
  +     public void updateVisualizer() {
  +             addressField.setText(model.getToAddress());
  +             fromField.setText(model.getFromAddress());
  +             smtpHostField.setText(model.getSmtpHost());
  +             successSubjectField.setText(model.getSuccessSubject());
  +             failureSubjectField.setText(model.getFailureSubject());
  +             failureLimitField.setText(String.valueOf(model.getFailureLimit()));
  +             failureField.setText(String.valueOf(model.getFailureCount()));
  +             successLimitField.setText(String.valueOf(model.getSuccessLimit()));
  +             repaint();
  +     }
  +
  +     /**
  +      * Shows a message using a DialogBox.
  +      */
  +     public void displayMessage(String message, boolean isError) {
  +             int type = 0;
  +             if (isError) {
  +                     type = JOptionPane.ERROR_MESSAGE;
  +             }
  +             else {
  +                     type = JOptionPane.INFORMATION_MESSAGE;
  +             }
  +             JOptionPane.showMessageDialog(null, message, "Error", type);
  +     }
   }
   
   
  
  
  
  1.1                  
jakarta-jmeter/src/components/org/apache/jmeter/visualizers/ModelListener.java
  
  Index: ModelListener.java
  ===================================================================
  /*
   * ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   * notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   * notice, this list of conditions and the following disclaimer in
   * the documentation and/or other materials provided with the
   * distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   * if any, must include the following acknowledgment:
   * "This product includes software developed by the
   * Apache Software Foundation (http://www.apache.org/)."
   * Alternately, this acknowledgment may appear in the software itself,
   * if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   * "Apache JMeter" must not be used to endorse or promote products
   * derived from this software without prior written permission. For
   * written permission, please contact [EMAIL PROTECTED]
   *
   * 5. Products derived from this software may not be called "Apache",
   * "Apache JMeter", nor may "Apache" appear in their name, without
   * prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
   package org.apache.jmeter.visualizers;
  
  /**
   * The Interface to be implemented by any class that wants to be notified by
   * model which makes use of this callback-Interface.
   *
   * @author     <a href="mailto:[EMAIL PROTECTED]";>Wolfram Rittmeyer</a>
   * @version    $Revision: 1.1 $ $Date: 2002/08/21 23:35:48 $
   */
  public interface ModelListener
  {
  
        /**
         * Informs the Visualizer that the model has changed.
         */
        public void updateVisualizer();
  
        /**
         * Informs the Visualizer that a message should be displayed.
         */
        public void displayMessage(String messageString, boolean isError);
  }
  
  
  1.1                  
jakarta-jmeter/src/components/org/apache/jmeter/visualizers/MailerModel.java
  
  Index: MailerModel.java
  ===================================================================
  /*
   * ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   * notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   * notice, this list of conditions and the following disclaimer in
   * the documentation and/or other materials provided with the
   * distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   * if any, must include the following acknowledgment:
   * "This product includes software developed by the
   * Apache Software Foundation (http://www.apache.org/)."
   * Alternately, this acknowledgment may appear in the software itself,
   * if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   * "Apache JMeter" must not be used to endorse or promote products
   * derived from this software without prior written permission. For
   * written permission, please contact [EMAIL PROTECTED]
   *
   * 5. Products derived from this software may not be called "Apache",
   * "Apache JMeter", nor may "Apache" appear in their name, without
   * prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
   package org.apache.jmeter.visualizers;
  
  import java.io.*;
  import java.util.*;
  import java.net.*;
  import java.util.Properties;
  
  import javax.mail.*;
  import javax.mail.internet.*;
  import javax.swing.JOptionPane;
  
  import org.apache.log4j.Category;
  
  import org.apache.jmeter.util.*;
  import org.apache.jmeter.gui.util.*;
  import org.apache.jmeter.samplers.*;
  import org.apache.jmeter.testelement.TestElement;
  import org.apache.jmeter.testelement.AbstractTestElement;
  import org.apache.jmeter.visualizers.gui.AbstractVisualizer;
  
  
  /**
   * The model for a MailerVisualizer.
   *
   * @author     <a href="mailto:[EMAIL PROTECTED]";>Wolfram Rittmeyer</a>
   * @version    $Revision: 1.1 $ $Date: 2002/08/21 23:35:48 $
   */
  public class MailerModel extends AbstractTestElement implements Serializable {
  
        private String addressie;
        private String fromAddress;
        private String smtpHost;
        private String failureSubject;
        private String successSubject;
        private long failureCount = 0;
        private long successCount = 0;
        private long failureLimit = 2;
        private long successLimit = 2;
        private boolean failureMsgSent = false;
        private boolean siteDown = false;
        private boolean successMsgSent = false;
  
        private Properties appProperties;
  
        private static final String FROM_KEY = "MailerModel.fromAddress";
        private static final String TO_KEY = "MailerModel.addressie";
        private static final String HOST_KEY = "MailerModel.smtpHost";
        private static final String SUCCESS_KEY = "MailerModel.successSubject";
        private static final String FAILURE_KEY = "MailerModel.failureSubject";
        private static final String FAILURE_LIMIT_KEY = "MailerModel.failureLimit";
        private static final String SUCCESS_LIMIT_KEY = "MailerModel.successLimit";
  
        private static Category logger = 
Category.getInstance("org.apache.jmeter.visualizers.MailerModel");
  
        /** The listener for changes. */
        ModelListener changeListener;
  
        /**
         * Constructs a MailerModel.
         */
        public MailerModel() {
                super();
  
                // Properties connection.
                this.appProperties = JMeterUtils.getJMeterProperties();
  
                // retrieve successLimit from properties
                try {
                        successLimit =  
Long.parseLong(appProperties.getProperty("mailer.successlimit"));
                }
                catch (Exception ex) {
                        // Ignore any garbage
                }
  
                // retrieve failureLimit from properties
                try {
                        failureLimit =  
Long.parseLong(appProperties.getProperty("mailer.failurelimit"));
                }
                catch (Exception ex) {
                        // Ignore any garbage
                }
        }
  
        /**
         * Returns wether there had been more failures than acceptable.
         *
         * @return A boolean value indicating wether the limit of acceptable failures 
has been reached.
         */
        public synchronized boolean isFailing()
        {
                return (failureCount > failureLimit);
        }
  
        /**
         * Gets a Vector of String-objects. Each String is one mail-address
         * of the addresses-String set by <code>setToAddress(str)</code>.
         * The addresses must be seperated by commas. Only String-objects
         * containing a "@" are added to the returned Vector.
         *
         * @return A Vector of String-objects wherein each String represents a 
mail-address.
         */
        public synchronized Vector getAddressVector()
        {
                String theAddressie = getToAddress();
                Vector addressVector = new Vector();
                if (theAddressie != null) {
                        String addressSep = ",";
  
                        StringTokenizer next = new StringTokenizer(theAddressie, 
addressSep);
  
                        while (next.hasMoreTokens())
                        {
                                String theToken = next.nextToken().trim();
  
                                if (theToken.indexOf("@") > 0)
                                {
                                        addressVector.addElement(theToken);
                                }
                        }
                }
                else {
                        return new Vector(0);
                }
  
                return addressVector;
        }
  
  
        /**
         * Adds a SampleResult. If SampleResult represents a change concerning
         * the failure/success of the sampling a message might be send to the
         * addressies according to the settings of <code>successCount</code>
         * and <code>failureCount</code>.
         *
         * @param sample The SampleResult encapsulating informations about the last 
sample.
         */
        public synchronized void add(SampleResult sample)
        {
  
                // -1 is the code for a failed sample.
                //
                if (!sample.isSuccessful())
                {
                        failureCount++;
                }
                else
                {
                        successCount++;
                }
  
                if (this.isFailing() && !siteDown && !failureMsgSent)
                {
                        // Send the mail ...
                        Vector addressVector = getAddressVector();
                        if (addressVector.size() != 0) {
                                try {
                                        sendMail(fromAddress, addressVector, 
failureSubject, "URL Failed: " +
                                                sample.getSampleLabel(), smtpHost);
                                }
                                catch (Exception e) {
                                        log(e.toString());
                                }
                                siteDown = true;
                                failureMsgSent = true;
                                successCount = 0;
                        }
                }
  
                if (siteDown && (sample.getTime() != -1) & !successMsgSent)
                {
                        // Send the mail ...
                        if (successCount > successLimit)
                        {
                                Vector addressVector = getAddressVector();
                                try {
                                        sendMail(fromAddress, addressVector, 
successSubject, "URL Restarted: " +
                                                        sample.getSampleLabel(), 
smtpHost);
                                }
                                catch (Exception e) {
                                        log(e.toString());
                                }
                                siteDown = false;
                                successMsgSent = true;
                        }
                }
  
                if (successMsgSent && failureMsgSent)
                {
                        clear();
                }
                notifyChangeListeners();
        }
  
        /**
         * Resets the state of this object to its default. But: This method does not
         * reset any mail-specific attributes (like sender, mail-subject...)
         * since they are independent of the sampling.
         */
        public synchronized void clear()
        {
                failureCount = 0;
                successCount = 0;
                siteDown = false;
                successMsgSent = false;
                failureMsgSent = false;
                notifyChangeListeners();
        }
  
        /**
         * Returns a String-representation of this object. Returns always
         * "E-Mail-Notification". Might be enhanced in future versions to return
         * some kind of String-representation of the mail-parameters (like
         * sender, addressies, smtpHost...).
         *
         * @return A String-representation of this object.
         */
        public String toString()
        {
                return "E-Mail Notification";
        }
  
        /**
         * Sends a mail with the given parameters using SMTP.
         *
         * @param  from The sender of the mail as shown in the mail-client.
         * @param  vEmails All receivers of the mail. The receivers are seperated by 
commas.
         * @param  subject The subject of the mail.
         * @param  attText The message-body.
         * @param  smtpHost The smtp-server used to send the mail.
         */
        public synchronized void sendMail(String from,
                        Vector vEmails,
                        String subject,
                        String attText,
                        String smtpHost) throws UnknownHostException, 
AddressException, MessagingException
        {
                String host = smtpHost;
                boolean debug = Boolean.valueOf(host).booleanValue();
                InetAddress remote = InetAddress.getByName(host);
  
                InternetAddress[] address = new InternetAddress[vEmails.size()];
                for (int k = 0; k < vEmails.size(); k++)
                {
                        address[k] = new 
InternetAddress(vEmails.elementAt(k).toString());
                }
  
                // create some properties and get the default Session
                Properties props = new Properties();
                props.put("mail.smtp.host", host);
                Session session = Session.getDefaultInstance(props, null);
                session.setDebug(debug);
  
                // create a message
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(from));
                msg.setRecipients(Message.RecipientType.TO, address);
                msg.setSubject(subject);
                msg.setText(attText);
                Transport.send(msg);
        }
  
  
        /**
         * Returns a String for the title of the attributes-panel
         * as set up in the properties-file using the lookup-constant
         * "mailer_attributes_panel".
         *
         * @return  The title of the component.
         */
        public String getAttributesTitle()
        {
                return JMeterUtils.getResString("mailer_attributes_panel");
        }
  
        /**
        * Method used to log a String.
        *
        * @param str String to be logged.
        */
        private static void log(String str) {
                logger.info(str);
        }
  
        //////////////////////////////////////////////////////////////
        //
        // setter/getter - JavaDoc-Comments not needed...
        //
        //////////////////////////////////////////////////////////////
  
        public void setToAddress(String str) {
                this.addressie = str;
        }
  
        public void setFromAddress(String str) {
                this.fromAddress = str;
        }
  
        public void setSmtpHost(String str) {
                this.smtpHost = str;
        }
  
        public void setFailureSubject(String str) {
                this.failureSubject = str;
        }
  
        public void setSuccessSubject(String str) {
                this.successSubject = str;
        }
  
        public void setSuccessLimit(long limit) {
                this.successLimit = limit;
        }
  
        public void setSuccessCount(long count) {
                this.successCount = count;
        }
  
        public void setFailureLimit(long limit) {
                this.failureLimit = limit;
        }
  
        public void setFailureCount(long count) {
                this.failureCount = count;
        }
  
        public String getToAddress() {
                return this.addressie;
        }
  
        public String getFromAddress() {
                return this.fromAddress;
        }
  
        public String getSmtpHost() {
                return this.smtpHost;
        }
  
        public String getFailureSubject() {
                return this.failureSubject;
        }
  
        public String getSuccessSubject() {
                return this.successSubject;
        }
  
        public long getSuccessLimit() {
                return this.successLimit;
        }
  
        public long getSuccessCount() {
                return this.successCount;
        }
  
        public long getFailureLimit() {
                return this.failureLimit;
        }
  
        public long getFailureCount() {
                return this.failureCount;
        }
  
        //////////////////////////////////////////////////////////////
        //
        // Storing and retrieving of model...
        //
        //////////////////////////////////////////////////////////////
  
        /**
         * Stores the attributes of the model as elements of the
         * given TestElement-object.
         *
         * @param element The TestElement to collect the model-attributes.
         */
        public void storeModel(TestElement element) {
                element.setProperty(TO_KEY, getToAddress());
                element.setProperty(FROM_KEY, getFromAddress());
                element.setProperty(HOST_KEY, getSmtpHost());
                element.setProperty(SUCCESS_KEY, getSuccessSubject());
                element.setProperty(FAILURE_KEY, getFailureSubject());
                element.setProperty(FAILURE_LIMIT_KEY, new Long(getFailureLimit()));
                element.setProperty(SUCCESS_LIMIT_KEY, new Long(getSuccessLimit()));
        }
  
        /**
         * Retrieves the attribute of the model as elements of the
         * given TestElement-object.
         *
         * @param element The TestElement to collect the model-attributes.
         */
        public void retrieveModel(TestElement element) {
                try {
                        setToAddress(element.getPropertyAsString(TO_KEY));
                        setFromAddress(element.getPropertyAsString(FROM_KEY));
                        setSmtpHost(element.getPropertyAsString(HOST_KEY));
                        setSuccessSubject(element.getPropertyAsString(SUCCESS_KEY));
                        setFailureSubject(element.getPropertyAsString(FAILURE_KEY));
                        
setFailureLimit(Long.parseLong((String)element.getProperty(FAILURE_LIMIT_KEY)));
                        
setSuccessLimit(Long.parseLong((String)element.getProperty(SUCCESS_LIMIT_KEY)));
                }
                catch (Exception e) {
                        log("Couldn't load MailerVisualizer...");
                }
        }
  
        //////////////////////////////////////////////////////////////
        //
        // Notification of GUI.
        //
        //////////////////////////////////////////////////////////////
  
        /**
         * Adds a ModelListener that is to be notified if model changes.
         *
         * @param listener The callback-object to receive notifications if state 
changes.
         */
        public void addModelListener(ModelListener listener) {
                this.changeListener = listener;
        }
  
        /**
         * Notify the assoziated ModelListener that the model has changed.
         */
        private void notifyChangeListeners() {
                this.changeListener.updateVisualizer();
        }
  
        /**
         * Notify the assoziated ModelListener that the model has changed.
         *
         * @param messageString The message to be displayed.
         */
        private void notifyChangeListenersAboutMessage(String messageString) {
                this.changeListener.displayMessage(messageString, true);
        }
  }
  
  
  
  
  

--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to