khammond    01/10/07 08:33:17

  Added:       src/org/apache/jmeter/protocol/http/sampler
                        MultipartFormSamplerFull.java
  Log:
  New file to add retrieve images functionality for multipart form request.
  
  Revision  Changes    Path
  1.1                  
jakarta-jmeter/src/org/apache/jmeter/protocol/http/sampler/MultipartFormSamplerFull.java
  
  Index: MultipartFormSamplerFull.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.protocol.http.sampler;
  
  import java.io.*;
  import java.net.*;
  import java.util.*;
  import javax.swing.ImageIcon;
  
  import org.apache.jmeter.protocol.http.config.UrlConfig;
  import org.apache.jmeter.protocol.http.config.MultipartUrlConfig;
  import org.apache.jmeter.samplers.Entry;
  import org.apache.jmeter.config.Argument;
  import org.apache.jmeter.samplers.SampleResult;
  
  import org.apache.log4j.*;
  
  // required to use to tidy parser
  import java.io.*;
  import org.w3c.dom.*;
  import org.w3c.tidy.Tidy;
  import org.xml.sax.SAXException;
  
  /**
   * Title:        JMeter
   * Description:
   * Copyright:    Copyright (c) 2000
   * Company:      Apache
   * @author Michael Stover
   * @version 1.0
   */
  
  // NOTES [khammond 2001.Oct.7]
  // I created this class to enable JMeter to retrieve images for a multipart 
  // form submission.
  
  public class MultipartFormSamplerFull extends MultipartFormSampler
  {
        public final static String RESULT_LIST = "httpSamplerFull.RESULT_LIST";
        public final static String IMAGE = "httpSamplerFull.IMAGE";
        public final static String TOTAL_TIME = "httpSamplerFull.TOTAL_TIME";
  
        protected static Category catClass = 
Category.getInstance(MultipartFormSamplerFull.class.getName());
        protected static String utfEncodingName;
        protected static String HTTP = "http://";;
        protected URL baseUrl;
  
        public MultipartFormSamplerFull()
        {
                super();
        }
  
        /**
         * Samples the <code>Entry</code> passed in and stores the result in 
         * <code>SampleResult</code>
         *
         * @param entry an entry to be sampled
         * @param redirected  whether redirection is turned on
         * @return      resuls of the sampling
         */
        public SampleResult sample(Entry e)
        {
                System.out.println("***************MultipartFormSamplerFull: sample");
                catClass.debug("Start : sample2");
                long totalTime = (long)0;
                SampleResult res = super.sample(e);
                String displayName = (String)res.getValue(SampleResult.SAMPLE_LABEL);
                res.putValue(SampleResult.DISPLAY_NAME, displayName);
                List loadBinaryList = new ArrayList();
                if (catClass.isDebugEnabled())
                {
                        catClass.debug("sample2 : main page loading time - " + 
res.getTime());
                }
                totalTime += res.getTime();
                Document html = null;
                try
                {
                        baseUrl = new 
URL((String)res.getValue(SampleResult.SAMPLE_LABEL));
                        if (catClass.isDebugEnabled())
                        {
                                catClass.debug("sample2 : baseUrl - " + 
baseUrl.toString());
                        }
  
                        // now use parser to look for image tags
                        html = 
(Document)getDOM((String)res.getValue(SampleResult.TEXT_RESPONSE));
                }
                catch(SAXException exception)
                {
                        catClass.error("sample2 : Error parsing document - " + 
exception);
                        catClass.error("sample2 : Setting SampleResult SUCCESS value 
to false");
                        res.putValue(SampleResult.TEXT_RESPONSE, exception.toString());
                        res.putValue(RESPONSE_CODE, NON_HTTP_RESPONSE_CODE);
                        res.putValue(RESPONSE_MESSAGE, NON_HTTP_RESPONSE_MESSAGE);
                        res.putValue(SampleResult.SUCCESS, new Boolean(false));
                }
                catch(MalformedURLException exception)
                {
                        catClass.error("sample2 : Error creating URL - " + exception);
                        catClass.error("sample2 : Setting SampleResult SUCCESS value 
to false");
                        res.putValue(SampleResult.TEXT_RESPONSE, exception.toString());
                        res.putValue(RESPONSE_CODE, NON_HTTP_RESPONSE_CODE);
                        res.putValue(RESPONSE_MESSAGE, NON_HTTP_RESPONSE_MESSAGE);
                        res.putValue(SampleResult.SUCCESS, new Boolean(false));
                }
  
                // sample result to store image from <img...> tags
                SampleResult imgRes = null;
                NodeList nodeList = html.getElementsByTagName("img");
                for(int i = 0; i < nodeList.getLength(); i++)
                {
                        imgRes = new SampleResult();
                        try
                        {
                                Node tempNode = nodeList.item(i);
                                if(catClass.isDebugEnabled())
                                {
                                        catClass.debug("sample2 : Image tags - " + 
tempNode);
                                }
  
                                // get the url of those images
                                NamedNodeMap nnm = tempNode.getAttributes();
                                Node namedItem = nnm.getNamedItem("src");
                                String imgUrlStr = namedItem.getNodeValue();
  
                                // set the baseUrl and imgUrl so that if error occurs
                                // due to MalformedException then at least the values 
will be
                                // visible to the user to aid correction
                                imgRes.putValue(SampleResult.DISPLAY_NAME, baseUrl + 
"," + imgUrlStr);
  
                                // download those images
                                URL imgUrl = new URL(baseUrl, imgUrlStr);
                                if (catClass.isDebugEnabled())
                                {
                                        catClass.debug("sample2 : Image url without 
baseUrl - " + imgUrlStr);
                                        catClass.debug("sample2 : Image url with 
baseUrl - " + imgUrl);
                                }
  
                                imgRes.putValue(SampleResult.DISPLAY_NAME, 
imgUrl.toString());
                                loadBinary(imgUrl, e, imgRes);
                                ImageIcon image = new ImageIcon(imgUrl, 
imgUrl.toString());
                                imgRes.putValue(IMAGE, image);
                                totalTime += imgRes.getTime();
                                imgRes.remove(SampleResult.TEXT_RESPONSE);
                        }
                        catch(IOException exception)
                        {
                                catClass.error("sample2 : Error reading from URL - " + 
exception);
                                catClass.error("sample2 : Setting SampleResult SUCCESS 
value to false");
                                imgRes.putValue(SampleResult.TEXT_RESPONSE, 
exception.toString());
                                imgRes.putValue(RESPONSE_CODE, NON_HTTP_RESPONSE_CODE);
                                imgRes.putValue(RESPONSE_MESSAGE, 
NON_HTTP_RESPONSE_MESSAGE);
                                imgRes.putValue(SampleResult.SUCCESS, new 
Boolean(false));
                        }
  
                        loadBinaryList.add(imgRes);
                }
  
                SampleResult appRes = null;
  
                // use parser to look for applet tags
                nodeList = html.getElementsByTagName("applet");
                for(int i = 0; i < nodeList.getLength(); i++)
                {
                        appRes = new SampleResult();
                        try
                        {
                                Node tempNode = nodeList.item(i);
                                if(catClass.isDebugEnabled())
                                {
                                        catClass.debug("sample2 : Applet tags - " + 
tempNode);
                                }
  
                                // get the url of those applets
                                NamedNodeMap nnm = tempNode.getAttributes();
                                Node namedItem = nnm.getNamedItem("code");
                                String appletUrlStr = namedItem.getNodeValue() + 
".class";
  
                                // set the baseUrl and imgUrl so that if error occurs
                                // due to MalformedException then at least the values 
will be
                                // visible to the user to aid correction
                                appRes.putValue(SampleResult.DISPLAY_NAME, baseUrl + 
"," + appletUrlStr);
  
                                // download those applet
                                URL appletUrl = new URL(baseUrl, appletUrlStr);
  
                                if(catClass.isDebugEnabled())
                                {
                                        catClass.debug("sample2 : Applet url without 
baseUrl - " + appletUrlStr);
                                        catClass.debug("sample2 : Applet url with 
baseUrl - " + appletUrl);
                                }
  
                                appRes.putValue(SampleResult.DISPLAY_NAME, 
appletUrl.toString());
                                appRes.putValue(SampleResult.TEXT_RESPONSE, 
loadBinary(appletUrl, e, appRes));
                                totalTime += appRes.getTime();
                        }
                        catch(IOException exception)
                        {
                                catClass.error("sample2 : Error reading from URL - " + 
exception);
                                catClass.error("sample2 : Setting SampleResult SUCCESS 
value to false");
                                appRes.putValue(SampleResult.TEXT_RESPONSE, 
exception.toString());
                                appRes.putValue(RESPONSE_CODE, NON_HTTP_RESPONSE_CODE);
                                appRes.putValue(RESPONSE_MESSAGE, 
NON_HTTP_RESPONSE_MESSAGE);
                                appRes.putValue(SampleResult.SUCCESS, new 
Boolean(false));
                        }
  
                        loadBinaryList.add(appRes);
                }
  
                // use parser to look for input tags with image types as well
                nodeList = html.getElementsByTagName("input");
                for(int i = 0; i < nodeList.getLength(); i++)
                {
                        try
                        {
                                Node tempNode = nodeList.item(i);
                                if(catClass.isDebugEnabled())
                                {
                                        catClass.debug("sample2 : Input tags - " + 
tempNode);
                                }
  
                                // get the url of those images
                                NamedNodeMap nnm = tempNode.getAttributes();
                                Node namedItem = nnm.getNamedItem("type");
                                String inputType = namedItem.getNodeValue();
                                if(catClass.isDebugEnabled())
                                {
                                        catClass.debug("sample2 : Input type - " + 
inputType);
                                }
  
                                if(inputType != null && 
inputType.equalsIgnoreCase("image"))
                                {
                                        imgRes = new SampleResult();
                                        namedItem = nnm.getNamedItem("src");
                                        String imgUrlStr = namedItem.getNodeValue();
  
                                        // set the baseUrl and imgUrl so that if error 
occurs
                                        // due to MalformedException then at least the 
values will be
                                        // visible to the user to aid correction
                                        imgRes.putValue(SampleResult.DISPLAY_NAME, 
baseUrl + "," + imgUrlStr);
  
                                        // download those images
                                        URL imgUrl = new URL(baseUrl, imgUrlStr);
                                        if(catClass.isDebugEnabled())
                                        {
                                                catClass.debug("sample2 : Image url 
without baseUrl - " + imgUrlStr);
                                                catClass.debug("sample2 : Image url 
with baseUrl - " + imgUrl);
                                        }
  
                                        loadBinary(imgUrl, e, imgRes);
                                        ImageIcon image = new ImageIcon(imgUrl, 
imgUrl.toString());
                                        imgRes.putValue(IMAGE, image);
                                        imgRes.putValue(SampleResult.DISPLAY_NAME, 
imgUrl.toString());
                                        totalTime += imgRes.getTime();
                                        imgRes.remove(SampleResult.TEXT_RESPONSE);
                                }
                        }
                        catch(IOException exception)
                        {
                                catClass.error("sample2 : Error reading from URL - " + 
exception);
                                catClass.error("sample2 : Setting SampleResult SUCCESS 
value to false");
                                imgRes.putValue(SampleResult.TEXT_RESPONSE, 
exception.toString());
                                imgRes.putValue(RESPONSE_CODE, NON_HTTP_RESPONSE_CODE);
                                imgRes.putValue(RESPONSE_MESSAGE, 
NON_HTTP_RESPONSE_MESSAGE);
                                imgRes.putValue(SampleResult.SUCCESS, new 
Boolean(false));
                        }
  
                        loadBinaryList.add(imgRes);
                }
  
                res.putValue(RESULT_LIST, loadBinaryList);
  
                if(catClass.isDebugEnabled())
                {
                        catClass.debug("sample2 : total time - " + totalTime);
                }
  
                res.putValue(TOTAL_TIME, new Long(totalTime));
                catClass.debug("End : sample2");
  
                return res;
        }
  
        /**
         * Download the binaries from given <code>URL</code>
         *
         * @param url           <code>URL</code> from where binary is to be downloaded
         * @param e             <code>Entry</code> being sampled
         * @param res           <code>SampleResult</code> to store sampling results
         * @return      binary downloaded
         */
        protected String loadBinary(URL url, Entry e, SampleResult res) 
                throws IOException
        {
                catClass.debug("Start : loadBinary1");
                String ret = null;
  
                // Create a dummy UrlConfig and set only the method.  Set the method to
                // GET.  Pass this UrlConfig to setupConnection() 'cos it uses 
UrlConfig
                // to determine the HTTP method to get the url.  In this case, we are
                // loading binaries so the method has to be GET.
                UrlConfig urlConfig = new UrlConfig();
                urlConfig.setMethod(UrlConfig.GET);
                HttpURLConnection conn = null;
                try
                {
                        conn = setupConnection(url, urlConfig, e);
                        conn.connect();
                }
                catch(IOException exception)
                {
                        // don't do anything 'cos persumably the connection will 
return the
                        // correct http response codes
                        if(catClass.isDebugEnabled())
                        {
                                catClass.debug("loadBinary1 : error in setupConnection 
" + exception);
                        }
                }
  
                long time = System.currentTimeMillis();
  
                if(catClass.isDebugEnabled())
                {
                        catClass.debug("loadBinary1 : start sampling time - " + time);
                }
  
                int errorLevel = getErrorLevel(conn, res);
  
                if (errorLevel == 2)
                {
                        ret = readResponse(conn);
                        res.putValue(SampleResult.SUCCESS, new Boolean(true));
                        long endTime = System.currentTimeMillis();
                        if(catClass.isDebugEnabled())
                        {
                                catClass.debug("loadBinary1 : end sampling time - " + 
endTime);
                        }
  
                        res.setTime(endTime - time);
                }
                else
                {
                        res.putValue(SampleResult.SUCCESS, new Boolean(false));
                        int responseCode = ((HttpURLConnection)conn).getResponseCode();
                        String responseMessage = 
((HttpURLConnection)conn).getResponseMessage();
                        catClass.error("loadBinary1 : failed response code - " + 
responseCode);
                        catClass.error("loadBinary1 : failed response message - " + 
                        responseMessage);
                }
  
                if(catClass.isDebugEnabled())
                {
                        catClass.debug("loadBinary1 : binary - " + ret.substring(0,5));
                        catClass.debug("loadBinary1 : loadTime - " + res.getTime());
                }
  
                catClass.debug("End : loadBinary1");
  
                return ret;
        }
  
        /**
         * Get the response code of the URL connection and divide it by 100 thus
         * returning 2(for 2xx response codes), 3(for 3xx reponse codes), etc
         *
         * @param conn          <code>HttpURLConnection</code> of URL request
         * @param res           where all results of sampling will be stored
         * @return              HTTP response code divided by 100
         */
        protected int getErrorLevel(HttpURLConnection conn, SampleResult res)
        {
                catClass.debug("Start : getErrorLevel1");
                int errorLevel = 2;
  
                try
                {
                        int responseCode = ((HttpURLConnection) 
conn).getResponseCode();
                        String responseMessage = ((HttpURLConnection) 
conn).getResponseMessage();
                        errorLevel = responseCode/100;
                        res.putValue(RESPONSE_CODE, String.valueOf(responseCode));
                        res.putValue(RESPONSE_MESSAGE, responseMessage);
  
                        if(catClass.isDebugEnabled())
                        {
                                catClass.debug("getErrorLevel1 : responseCode - " + 
responseCode);
                                catClass.debug("getErrorLevel1 : responseMessage - " + 
                                responseMessage);
                        }
                }
                catch (Exception e2)
                {
                        System.out.println("getErrorLevel1 : " + 
conn.getHeaderField(0));
                        System.out.println("getErrorLevel1 : " + 
conn.getHeaderFieldKey(0));
                        catClass.error("getErrorLevel1 : " + 
                                "Error getting response code for HttpUrlConnection - " 
+ e2);
                        catClass.error("getErrorLevel1 : " + 
                                "Setting SampleResult SUCCESS value to false");
                        res.putValue(SampleResult.TEXT_RESPONSE, e2.toString());
                        res.putValue(RESPONSE_CODE, NON_HTTP_RESPONSE_CODE);
                        res.putValue(RESPONSE_MESSAGE, NON_HTTP_RESPONSE_MESSAGE);
                        res.putValue(SampleResult.SUCCESS, new Boolean(false));
                }
  
                catClass.debug("End : getErrorLevel1");
  
                return errorLevel;
        }
  
        /**
         * Returns <code>tidy</code> as HTML parser
         *
         * @return      a <code>tidy</code> HTML parser
         */
        protected static Tidy getParser()
        {
                catClass.debug("Start : getParser1");
                Tidy tidy = new Tidy();
                tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
                tidy.setQuiet(true);
  
                if(catClass.isDebugEnabled())
                {
                        catClass.debug("getParser1 : tidy parser created - " + tidy);
                }
  
                catClass.debug("End : getParser1");
  
                return tidy;
        }
  
        /**
         * Returns a node representing a whole xml given an xml document
         *
         * @param text  an xml document
         * @return      a node representing a whole xml
         */
        protected static Node getDOM(String text) throws SAXException
        {
                catClass.debug("Start : getDOM1");
  
                try
                {
                        Node node = getParser().parseDOM(new 
                        ByteArrayInputStream(text.getBytes(getUTFEncodingName())), 
null);
  
                        if(catClass.isDebugEnabled())
                        {
                                catClass.debug("node : " + node);
                        }
  
                        catClass.debug("End : getDOM1");
  
                        return node;
                }
                catch(UnsupportedEncodingException e)
                {
                        catClass.error("getDOM1 : Unsupported encoding exception - " + 
e);
                        catClass.debug("End : getDOM1");
                        throw new RuntimeException("UTF-8 encoding failed");
                }
        }
  
        /**
         * Returns the encoding type which is different for different jdks
         * even though the mean the same thing i.e. UTF8 or UTF-8
         *
         * @return      either UTF8 or UTF-8 depending on the jdk version
         */
        protected static String getUTFEncodingName()
        {
                catClass.debug("Start : getUTFEncodingName1");
  
                if (utfEncodingName == null)
                {
                        String versionNum = System.getProperty( "java.version" );
                        if(catClass.isDebugEnabled())
                        {
                                catClass.debug("getUTFEncodingName1 : versionNum - " + 
versionNum);
                        }
  
                        if (versionNum.startsWith( "1.1" ))
                        {
                                utfEncodingName = "UTF8";
                        }
                        else
                        {
                                utfEncodingName = "UTF-8";
                        }
                }
  
                if(catClass.isDebugEnabled())
                {
                        catClass.debug("getUTFEncodingName1 : Returning 
utfEncodingName - " + 
                                utfEncodingName);
                }
  
                catClass.debug("End : getUTFEncodingName1");
  
                return utfEncodingName;
        }
  }
  
  
  

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

Reply via email to