/** Base class for SampleSender implementations */
public abstract class AbstractSampleSender implements SampleSender {

  // Note: this is an instance field (and is not transient), so is created by the JMeter client
  // and propagated to the server instance by RMI.
  // [a static field would be recreated on the server, and would pick up the server properties]
  private final boolean isClientConfigured =
      JMeterUtils.getPropDefault("sample_sender_client_configured", true); // $NON-NLS-1$

  /**
   * @return boolean indicates how SampleSender configuration is done, true means use client
   *     properties and send to servers, false means use server configurations
   */
  public boolean isClientConfigured() {
    return isClientConfigured;
  }

  /** */
  public AbstractSampleSender() {
    super();
  }

  @Override
  public void testEnded() {
    // Not used
  }
}
예제 #2
0
  static {
    if (NONPROXY_HOSTS.length() > 0) {
      StringTokenizer s = new StringTokenizer(NONPROXY_HOSTS, "|"); // $NON-NLS-1$
      while (s.hasMoreTokens()) {
        String t = s.nextToken();
        if (t.indexOf('*') == 0) { // e.g. *.apache.org // $NON-NLS-1$
          nonProxyHostSuffix.add(t.substring(1));
        } else {
          nonProxyHostFull.add(t); // e.g. www.apache.org
        }
      }
    }
    nonProxyHostSuffixSize = nonProxyHostSuffix.size();

    InetAddress inet = null;
    String localHostOrIP = JMeterUtils.getPropDefault("httpclient.localaddress", ""); // $NON-NLS-1$
    if (localHostOrIP.length() > 0) {
      try {
        inet = InetAddress.getByName(localHostOrIP);
        log.info("Using localAddress " + inet.getHostAddress());
      } catch (UnknownHostException e) {
        log.warn(e.getLocalizedMessage());
      }
    } else {
      // Get hostname
      localHostOrIP = JMeterUtils.getLocalHostName();
    }
    localAddress = inet;
    localHost = localHostOrIP;
    log.info("Local host = " + localHost);
  }
 /**
  * Checks for the Jmeter properties num_sample_threshold and time_threshold, and assigns defaults
  * if not found.
  */
 private void init() {
   this.numSamplesThreshold =
       JMeterUtils.getPropDefault("num_sample_threshold", DEFAULT_NUM_SAMPLE_THRESHOLD);
   this.timeThreshold = JMeterUtils.getPropDefault("time_threshold", DEFAULT_TIME_THRESHOLD);
 }
/** This is the JMeter server main code. */
public final class RemoteJMeterEngineImpl extends java.rmi.server.UnicastRemoteObject
    implements RemoteJMeterEngine {
  private static final long serialVersionUID = 240L;

  private static final Logger log = LoggingManager.getLoggerForClass();

  static final String JMETER_ENGINE_RMI_NAME = "JMeterEngine"; // $NON-NLS-1$

  private transient JMeterEngine backingEngine;

  private transient Thread ownerThread;

  private static final int DEFAULT_RMI_PORT =
      JMeterUtils.getPropDefault("server.rmi.port", 1099); // $NON-NLS-1$

  private static final int DEFAULT_LOCAL_PORT =
      JMeterUtils.getPropDefault("server.rmi.localport", 0); // $NON-NLS-1$

  static {
    if (DEFAULT_LOCAL_PORT != 0) {
      System.out.println("Using local port: " + DEFAULT_LOCAL_PORT);
    }
  }

  // Should we create our own copy of the RMI registry?
  private static final boolean createServer =
      JMeterUtils.getPropDefault("server.rmi.create", true); // $NON-NLS-1$

  private final Object LOCK = new Object();

  private final int rmiPort;

  private Properties remotelySetProperties;

  private RemoteJMeterEngineImpl(int localPort, int rmiPort) throws RemoteException {
    super(localPort); // Create this object using the specified port (0 means anonymous)
    this.rmiPort = rmiPort;
    System.out.println("Created remote object: " + this.getRef().remoteToString());
  }

  public static void startServer(int rmiPort) throws RemoteException {
    RemoteJMeterEngineImpl engine =
        new RemoteJMeterEngineImpl(DEFAULT_LOCAL_PORT, rmiPort == 0 ? DEFAULT_RMI_PORT : rmiPort);
    engine.init();
  }

  private void init() throws RemoteException {
    log.info("Starting backing engine on " + this.rmiPort);
    InetAddress localHost = null;
    // Bug 47980 - allow override of local hostname
    String host = System.getProperties().getProperty("java.rmi.server.hostname"); // $NON-NLS-1$
    try {
      if (host == null) {
        localHost = InetAddress.getLocalHost();
      } else {
        localHost = InetAddress.getByName(host);
      }
    } catch (UnknownHostException e1) {
      throw new RemoteException("Cannot start. Unable to get local host IP address.", e1);
    }
    log.info("IP address=" + localHost.getHostAddress());
    String hostName = localHost.getHostName();
    // BUG 52469 : Allow loopback address for SSH Tunneling of RMI traffic
    if (localHost.isLoopbackAddress() && host == null) {
      throw new RemoteException("Cannot start. " + hostName + " is a loopback address.");
    }
    if (localHost.isSiteLocalAddress()) {
      // should perhaps be log.warn, but this causes the client-server test to fail
      log.info(
          "IP address is a site-local address; this may cause problems with remote access.\n"
              + "\tCan be overridden by defining the system property 'java.rmi.server.hostname' - see jmeter-server script file");
    }
    log.debug("This = " + this);
    if (createServer) {
      log.info("Creating RMI registry (server.rmi.create=true)");
      try {
        LocateRegistry.createRegistry(this.rmiPort);
      } catch (RemoteException e) {
        String msg = "Problem creating registry: " + e;
        log.warn(msg);
        System.err.println(msg);
        System.err.println("Continuing...");
      }
    }
    try {
      Registry reg = LocateRegistry.getRegistry(this.rmiPort);
      reg.rebind(JMETER_ENGINE_RMI_NAME, this);
      log.info("Bound to registry on port " + this.rmiPort);
    } catch (Exception ex) {
      log.error(
          "rmiregistry needs to be running to start JMeter in server "
              + "mode\n\t"
              + ex.toString());
      // Throw an Exception to ensure caller knows ...
      throw new RemoteException("Cannot start. See server log file.", ex);
    }
  }

  /**
   * Adds a feature to the ThreadGroup attribute of the RemoteJMeterEngineImpl object.
   *
   * @param testTree the feature to be added to the ThreadGroup attribute
   */
  @Override
  public void rconfigure(HashTree testTree, String host, File jmxBase, String scriptName)
      throws RemoteException {
    log.info("Creating JMeter engine on host " + host + " base '" + jmxBase + "'");
    synchronized (LOCK) { // close window where another remote client might jump in
      if (backingEngine != null && backingEngine.isActive()) {
        log.warn("Engine is busy - cannot create JMeter engine");
        throw new IllegalStateException("Engine is busy - please try later");
      }
      ownerThread = Thread.currentThread();
      backingEngine = new StandardJMeterEngine(host);
      backingEngine.configure(testTree); // sets active = true
    }
    FileServer.getFileServer().setScriptName(scriptName);
    FileServer.getFileServer().setBase(jmxBase);
  }

  @Override
  public void rrunTest() throws RemoteException, JMeterEngineException, IllegalStateException {
    log.info("Running test");
    checkOwner("runTest");
    backingEngine.runTest();
  }

  @Override
  public void rreset() throws RemoteException, IllegalStateException {
    // Mail on userlist reported NPE here - looks like only happens if there are network errors, but
    // check anyway
    if (backingEngine != null) {
      log.info("Reset");
      checkOwner("reset");
      backingEngine.reset();
    } else {
      log.warn("Backing engine is null, ignoring reset");
    }
  }

  @Override
  public void rstopTest(boolean now) throws RemoteException {
    if (now) {
      log.info("Stopping test ...");
    } else {
      log.info("Shutting test ...");
    }
    backingEngine.stopTest(now);
    log.info("... stopped");
  }

  /*
   * Called by:
   * - ClientJMeterEngine.exe() which is called on remoteStop
   */
  @Override
  public void rexit() throws RemoteException {
    log.info("Exitting");
    backingEngine.exit();
    // Tidy up any objects we created
    Registry reg = LocateRegistry.getRegistry(this.rmiPort);
    try {
      reg.unbind(JMETER_ENGINE_RMI_NAME);
    } catch (NotBoundException e) {
      log.warn(JMETER_ENGINE_RMI_NAME + " is not bound", e);
    }
    log.info("Unbound from registry");
    // Help with garbage control
    JMeterUtils.helpGC();
  }

  @Override
  public void rsetProperties(Properties p) throws RemoteException, IllegalStateException {
    checkOwner("setProperties");
    if (remotelySetProperties != null) {
      Properties jmeterProperties = JMeterUtils.getJMeterProperties();
      log.info("Cleaning previously set properties " + remotelySetProperties);
      for (Iterator<?> iterator = remotelySetProperties.keySet().iterator(); iterator.hasNext(); ) {
        String key = (String) iterator.next();
        jmeterProperties.remove(key);
      }
    }
    backingEngine.setProperties(p);
    this.remotelySetProperties = p;
  }

  /**
   * Check if the caller owns the engine.
   *
   * @param methodName the name of the method for the log message
   * @throws IllegalStateException if the caller is not the owner.
   */
  private void checkOwner(String methodName) throws IllegalStateException {
    if (ownerThread != null && ownerThread != Thread.currentThread()) {
      String msg = "The engine is not owned by this thread - cannot call " + methodName;
      log.warn(msg);
      throw new IllegalStateException(msg);
    }
  }
}
/** Implements binary length-prefixed binary data. This is used in ISO8583 for example. */
public class LengthPrefixedBinaryTCPClientImpl extends TCPClientDecorator {
  private static final Logger log = LoggingManager.getLoggerForClass();

  private final int lengthPrefixLen =
      JMeterUtils.getPropDefault("tcp.binarylength.prefix.length", 2); // $NON-NLS-1$

  public LengthPrefixedBinaryTCPClientImpl() {
    super(new BinaryTCPClientImpl());
    tcpClient.setEolByte(Byte.MAX_VALUE + 1);
  }

  /** {@inheritDoc} */
  @Override
  public void write(OutputStream os, String s) throws IOException {
    os.write(intToByteArray(s.length() / 2, lengthPrefixLen));
    if (log.isDebugEnabled()) {
      log.debug("Wrote: " + s.length() / 2 + " bytes");
    }
    this.tcpClient.write(os, s);
  }

  /** {@inheritDoc} */
  @Override
  public void write(OutputStream os, InputStream is) throws IOException {
    this.tcpClient.write(os, is);
  }

  /** {@inheritDoc} */
  @Override
  public String read(InputStream is) throws ReadException {
    byte[] msg = new byte[0];
    int msgLen = 0;
    byte[] lengthBuffer = new byte[lengthPrefixLen];
    try {
      if (is.read(lengthBuffer, 0, lengthPrefixLen) == lengthPrefixLen) {
        msgLen = byteArrayToInt(lengthBuffer);
        msg = new byte[msgLen];
        int bytes = JOrphanUtils.read(is, msg, 0, msgLen);
        if (bytes < msgLen) {
          log.warn("Incomplete message read, expected: " + msgLen + " got: " + bytes);
        }
      }

      String buffer = JOrphanUtils.baToHexString(msg);
      if (log.isDebugEnabled()) {
        log.debug("Read: " + msgLen + "\n" + buffer);
      }
      return buffer;
    } catch (IOException e) {
      throw new ReadException("", e, JOrphanUtils.baToHexString(msg));
    }
  }

  /**
   * Not useful, as the byte is never used.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public byte getEolByte() {
    return tcpClient.getEolByte();
  }

  /** {@inheritDoc} */
  @Override
  public void setEolByte(int eolInt) {
    throw new UnsupportedOperationException("Cannot set eomByte for prefixed messages");
  }
}
예제 #6
0
/**
 * Common parent class for HttpClient implementations.
 *
 * <p>Includes system property settings that are handled internally by the Java HTTP implementation,
 * but which need to be explicitly configured in HttpClient implementations.
 */
public abstract class HTTPHCAbstractImpl extends HTTPAbstractImpl {

  private static final Logger log = LoggingManager.getLoggerForClass();

  protected static final String PROXY_HOST = System.getProperty("http.proxyHost", "");

  protected static final String NONPROXY_HOSTS = System.getProperty("http.nonProxyHosts", "");

  protected static final int PROXY_PORT =
      Integer.parseInt(System.getProperty("http.proxyPort", "0"));

  protected static final boolean PROXY_DEFINED = PROXY_HOST.length() > 0 && PROXY_PORT > 0;

  protected static final String PROXY_USER = JMeterUtils.getPropDefault(JMeter.HTTP_PROXY_USER, "");

  protected static final String PROXY_PASS = JMeterUtils.getPropDefault(JMeter.HTTP_PROXY_PASS, "");

  protected static final String PROXY_DOMAIN = JMeterUtils.getPropDefault("http.proxyDomain", "");

  protected static final InetAddress localAddress;

  protected static final String localHost;

  protected static final Set<String> nonProxyHostFull = new HashSet<String>();

  protected static final List<String> nonProxyHostSuffix = new ArrayList<String>();

  protected static final int nonProxyHostSuffixSize;

  protected static final int CPS_HTTP = JMeterUtils.getPropDefault("httpclient.socket.http.cps", 0);

  protected static final int CPS_HTTPS =
      JMeterUtils.getPropDefault("httpclient.socket.https.cps", 0);

  protected static final boolean USE_LOOPBACK =
      JMeterUtils.getPropDefault("httpclient.loopback", false);

  protected static final String HTTP_VERSION =
      JMeterUtils.getPropDefault("httpclient.version", "1.1");

  // -1 means not defined
  protected static final int SO_TIMEOUT = JMeterUtils.getPropDefault("httpclient.timeout", -1);

  // Control reuse of cached SSL Context in subsequent iterations
  protected static final boolean USE_CACHED_SSL_CONTEXT =
      JMeterUtils.getPropDefault("https.use.cached.ssl.context", true); // $NON-NLS-1$

  static {
    if (NONPROXY_HOSTS.length() > 0) {
      StringTokenizer s = new StringTokenizer(NONPROXY_HOSTS, "|"); // $NON-NLS-1$
      while (s.hasMoreTokens()) {
        String t = s.nextToken();
        if (t.indexOf('*') == 0) { // e.g. *.apache.org // $NON-NLS-1$
          nonProxyHostSuffix.add(t.substring(1));
        } else {
          nonProxyHostFull.add(t); // e.g. www.apache.org
        }
      }
    }
    nonProxyHostSuffixSize = nonProxyHostSuffix.size();

    InetAddress inet = null;
    String localHostOrIP = JMeterUtils.getPropDefault("httpclient.localaddress", ""); // $NON-NLS-1$
    if (localHostOrIP.length() > 0) {
      try {
        inet = InetAddress.getByName(localHostOrIP);
        log.info("Using localAddress " + inet.getHostAddress());
      } catch (UnknownHostException e) {
        log.warn(e.getLocalizedMessage());
      }
    } else {
      // Get hostname
      localHostOrIP = JMeterUtils.getLocalHostName();
    }
    localAddress = inet;
    localHost = localHostOrIP;
    log.info("Local host = " + localHost);
  }

  protected HTTPHCAbstractImpl(HTTPSamplerBase testElement) {
    super(testElement);
  }

  protected static boolean isNonProxy(String host) {
    return nonProxyHostFull.contains(host) || isPartialMatch(host);
  }

  protected static boolean isPartialMatch(String host) {
    for (int i = 0; i < nonProxyHostSuffixSize; i++) {
      if (host.endsWith(nonProxyHostSuffix.get(i))) {
        return true;
      }
    }
    return false;
  }

  /**
   * Is a dynamic proxy defined?
   *
   * @param proxyHost the host to check
   * @param proxyPort the port to check
   * @return {@code true} iff both ProxyPort and ProxyHost are defined.
   */
  protected boolean isDynamicProxy(String proxyHost, int proxyPort) {
    return (!JOrphanUtils.isBlank(proxyHost) && proxyPort > 0);
  }

  /**
   * Is a static proxy defined?
   *
   * @param host to check against non-proxy hosts
   * @return {@code true} iff a static proxy has been defined.
   */
  protected static boolean isStaticProxy(String host) {
    return PROXY_DEFINED && !isNonProxy(host);
  }

  /**
   * @param value String value to test
   * @return true if value is null or empty trimmed
   */
  protected static boolean isNullOrEmptyTrimmed(String value) {
    return JOrphanUtils.isBlank(value);
  }
}
/** Synthesis Table-Based Reporting Visualizer for JMeter. */
public class SynthesisReportGui extends AbstractGraphPanelVisualizer
    implements Clearable, ActionListener {

  private static final long serialVersionUID = 240L;

  private static final String pct1Label = JMeterUtils.getPropDefault("aggregate_rpt_pct1", "90");

  private static final Float pct1Value = new Float(Float.parseFloat(pct1Label) / 100);

  protected FilterPanel jPanelFilter;

  private static final Logger log = LoggingManager.getLoggerForClass();

  public static final String WIKIPAGE = "SynthesisReport";

  private static final String USE_GROUP_NAME = "useGroupName"; // $NON-NLS-1$

  private static final String SAVE_HEADERS = "saveHeaders"; // $NON-NLS-1$

  private static final String[] COLUMNS_BEFORE_JM_2_13 = {
    "sampler_label", //$NON-NLS-1$
    "aggregate_report_count", //$NON-NLS-1$
    "average", //$NON-NLS-1$
    "aggregate_report_min", //$NON-NLS-1$
    "aggregate_report_max", //$NON-NLS-1$
    "aggregate_report_90%_line", //$NON-NLS-1$
    "aggregate_report_stddev", //$NON-NLS-1$
    "aggregate_report_error%", //$NON-NLS-1$
    "aggregate_report_rate", //$NON-NLS-1$
    "aggregate_report_bandwidth", //$NON-NLS-1$
    "average_bytes"
  }; //$NON-NLS-1$

  private static final String[] COLUMNS_AFTER_OR_EQUAL_JM_2_13 = {
    "sampler_label", //$NON-NLS-1$
    "aggregate_report_count", //$NON-NLS-1$
    "average", //$NON-NLS-1$
    "aggregate_report_min", //$NON-NLS-1$
    "aggregate_report_max", //$NON-NLS-1$
    "aggregate_report_xx_pct1_line", //$NON-NLS-1$
    "aggregate_report_stddev", //$NON-NLS-1$
    "aggregate_report_error%", //$NON-NLS-1$
    "aggregate_report_rate", //$NON-NLS-1$
    "aggregate_report_bandwidth", //$NON-NLS-1$
    "average_bytes"
  }; //$NON-NLS-1$

  private static final boolean bOldVersion =
      Float.compare(
              Float.parseFloat(JMeterUtils.getJMeterVersion().substring(0, 4)), new Float(2.13))
          < 0;
  private static final String[] COLUMNS =
      bOldVersion ? COLUMNS_BEFORE_JM_2_13 : COLUMNS_AFTER_OR_EQUAL_JM_2_13;

  static final Object[][] COLUMNS_MSG_PARAMETERS = {
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    new Object[] {pct1Label}, // $NON-NLS-1$
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    null, //$NON-NLS-1$
    null
  }; //$NON-NLS-1$

  private final String TOTAL_ROW_LABEL =
      JMeterUtils.getResString("aggregate_report_total_label"); // $NON-NLS-1$

  private JTable myJTable;

  private JScrollPane myScrollPane;

  private final JButton saveTable =
      new JButton(JMeterUtils.getResString("aggregate_graph_save_table")); // $NON-NLS-1$

  private final JCheckBox saveHeaders = // should header be saved with the
      // data?
      new JCheckBox(
          JMeterUtils.getResString("aggregate_graph_save_table_header"), true); // $NON-NLS-1$

  private final JCheckBox useGroupName =
      new JCheckBox(JMeterUtils.getResString("aggregate_graph_use_group_name")); // $NON-NLS-1$

  private transient ObjectTableModel model;

  /** Lock used to protect tableRows update + model update */
  private final transient Object lock = new Object();

  private final Map<String, SamplingStatCalculator> tableRows =
      new ConcurrentHashMap<String, SamplingStatCalculator>();

  public SynthesisReportGui() {
    super();
    model = createObjectTableModel();
    clearData();
    init();
  }

  /**
   * Creates that Table model
   *
   * @return ObjectTableModel
   */
  static ObjectTableModel createObjectTableModel() {
    return new ObjectTableModel(
        COLUMNS,
        SamplingStatCalculator.class,
        new Functor[] {
          new Functor("getLabel"), // $NON-NLS-1$
          new Functor("getCount"), // $NON-NLS-1$
          new Functor("getMeanAsNumber"), // $NON-NLS-1$
          new Functor("getMin"), // $NON-NLS-1$
          new Functor("getMax"), // $NON-NLS-1$
          new Functor(
              "getPercentPoint", //$NON-NLS-1$
              new Object[] {pct1Value}),
          new Functor("getStandardDeviation"), // $NON-NLS-1$
          new Functor("getErrorPercentage"), // $NON-NLS-1$
          new Functor("getRate"), // $NON-NLS-1$
          new Functor("getKBPerSecond"), // $NON-NLS-1$
          new Functor("getAvgPageBytes"), // $NON-NLS-1$
        },
        new Functor[] {null, null, null, null, null, null, null, null, null, null, null},
        new Class[] {
          String.class,
          Long.class,
          Long.class,
          Long.class,
          Long.class,
          Long.class,
          String.class,
          String.class,
          String.class,
          String.class,
          String.class
        });
  }

  // Column renderers
  private static final TableCellRenderer[] RENDERERS =
      new TableCellRenderer[] {
        null, // Label
        null, // count
        null, // Mean
        null, // Min
        null, // Max
        null, // 90%
        new NumberRenderer("#0.00"), // Std Dev. //$NON-NLS-1$
        new NumberRenderer("#0.00%"), // Error %age //$NON-NLS-1$
        new RateRenderer("#.0"), // Throughput //$NON-NLS-1$
        new NumberRenderer("#0.00"), // kB/sec //$NON-NLS-1$
        new NumberRenderer("#.0"), // avg. pageSize //$NON-NLS-1$
      };

  // Column formats
  static final Format[] FORMATS =
      new Format[] {
        null, // Label
        null, // count
        null, // Mean
        null, // Min
        null, // Max
        null, // 90%
        new DecimalFormat("#0.00"), // Std Dev. //$NON-NLS-1$
        new DecimalFormat("#0.00%"), // Error %age //$NON-NLS-1$
        new DecimalFormat("#.0"), // Throughput //$NON-NLS-1$
        new DecimalFormat("#0.00"), // kB/sec //$NON-NLS-1$
        new DecimalFormat("#.0"), // avg. pageSize //$NON-NLS-1$
      };

  @Override
  public String getLabelResource() {
    return this.getClass().getSimpleName(); // $NON-NLS-1$
  }

  @Override
  public String getStaticLabel() {
    return JMeterPluginsUtils.prefixLabel("Synthesis Report (filtered)");
  }

  @Override
  public void add(final SampleResult res) {
    JMeterUtils.runSafe(
        new Runnable() {
          @Override
          public void run() {
            if (isSampleIncluded(res)) {
              SamplingStatCalculator row = null;
              final String sampleLabel = res.getSampleLabel(useGroupName.isSelected());
              synchronized (lock) {
                row = tableRows.get(sampleLabel);
                if (row == null) {
                  row = new SamplingStatCalculator(sampleLabel);
                  tableRows.put(row.getLabel(), row);
                  model.insertRow(row, model.getRowCount() - 1);
                }
              }
              /*
               * Synch is needed because multiple threads can update the
               * counts.
               */
              synchronized (row) {
                row.addSample(res);
              }
              SamplingStatCalculator tot = tableRows.get(TOTAL_ROW_LABEL);
              synchronized (tot) {
                tot.addSample(res);
              }
              model.fireTableDataChanged();
            }
          }
        });
  }

  /** Clears this visualizer and its model, and forces a repaint of the table. */
  @Override
  public void clearData() {
    synchronized (lock) {
      model.clearData();
      tableRows.clear();
      tableRows.put(TOTAL_ROW_LABEL, new SamplingStatCalculator(TOTAL_ROW_LABEL));
      model.addRow(tableRows.get(TOTAL_ROW_LABEL));
    }
  }

  /** Main visualizer setup. */
  private void init() {
    this.setLayout(new BorderLayout());

    // MAIN PANEL
    JPanel mainPanel = new JPanel();
    Border margin = new EmptyBorder(10, 10, 5, 10);

    mainPanel.setBorder(margin);
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    mainPanel.add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE));

    // SortFilterModel mySortedModel =
    // new SortFilterModel(myStatTableModel);
    myJTable = new JTable(model);
    myJTable
        .getTableHeader()
        .setDefaultRenderer(new JMeterHeaderAsPropertyRenderer(COLUMNS_MSG_PARAMETERS));
    myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
    RendererUtils.applyRenderers(myJTable, RENDERERS);
    myScrollPane = new JScrollPane(myJTable);
    this.add(mainPanel, BorderLayout.NORTH);
    this.add(myScrollPane, BorderLayout.CENTER);
    saveTable.addActionListener(this);
    JPanel opts = new JPanel();
    opts.add(useGroupName, BorderLayout.WEST);
    opts.add(saveTable, BorderLayout.CENTER);
    opts.add(saveHeaders, BorderLayout.EAST);
    this.add(opts, BorderLayout.SOUTH);
  }

  /**
   * Invoked when the target of the listener has changed its state. This implementation assumes that
   * the target is the FilePanel, and will update the result collector for the new filename.
   *
   * @param e the event that has occurred
   */
  @Override
  public void stateChanged(ChangeEvent e) {
    log.debug("getting new collector");
    collector = (CorrectedResultCollector) createTestElement();
    if (collector instanceof CorrectedResultCollector) {
      setUpFiltering((CorrectedResultCollector) collector);
    }
    collector.loadExistingFile();
  }

  @Override
  public void modifyTestElement(TestElement c) {
    super.modifyTestElement(c);
    c.setProperty(USE_GROUP_NAME, useGroupName.isSelected(), false);
    c.setProperty(SAVE_HEADERS, saveHeaders.isSelected(), true);
    c.setProperty(
        new StringProperty(
            CorrectedResultCollector.INCLUDE_SAMPLE_LABELS, jPanelFilter.getIncludeSampleLabels()));
    c.setProperty(
        new StringProperty(
            CorrectedResultCollector.EXCLUDE_SAMPLE_LABELS, jPanelFilter.getExcludeSampleLabels()));

    c.setProperty(
        new StringProperty(CorrectedResultCollector.START_OFFSET, jPanelFilter.getStartOffset()));
    c.setProperty(
        new StringProperty(CorrectedResultCollector.END_OFFSET, jPanelFilter.getEndOffset()));

    c.setProperty(
        new BooleanProperty(
            CorrectedResultCollector.INCLUDE_REGEX_CHECKBOX_STATE,
            jPanelFilter.isSelectedRegExpInc()));
    c.setProperty(
        new BooleanProperty(
            CorrectedResultCollector.EXCLUDE_REGEX_CHECKBOX_STATE,
            jPanelFilter.isSelectedRegExpExc()));
  }

  @Override
  public void configure(TestElement el) {
    super.configure(el);
    useGroupName.setSelected(el.getPropertyAsBoolean(USE_GROUP_NAME, false));
    saveHeaders.setSelected(el.getPropertyAsBoolean(SAVE_HEADERS, true));

    jPanelFilter.setIncludeSampleLabels(
        el.getPropertyAsString(CorrectedResultCollector.INCLUDE_SAMPLE_LABELS));
    jPanelFilter.setExcludeSampleLabels(
        el.getPropertyAsString(CorrectedResultCollector.EXCLUDE_SAMPLE_LABELS));

    if (!CorrectedResultCollector.EMPTY_FIELD.equals(
        el.getPropertyAsString(CorrectedResultCollector.START_OFFSET))) {
      jPanelFilter.setStartOffset((el.getPropertyAsLong(CorrectedResultCollector.START_OFFSET)));
    }
    if (!CorrectedResultCollector.EMPTY_FIELD.equals(
        el.getPropertyAsString(CorrectedResultCollector.END_OFFSET))) {
      jPanelFilter.setEndOffset((el.getPropertyAsLong(CorrectedResultCollector.END_OFFSET)));
    }

    jPanelFilter.setSelectedRegExpInc(
        el.getPropertyAsBoolean(CorrectedResultCollector.INCLUDE_REGEX_CHECKBOX_STATE));
    jPanelFilter.setSelectedRegExpExc(
        el.getPropertyAsBoolean(CorrectedResultCollector.EXCLUDE_REGEX_CHECKBOX_STATE));

    if (el instanceof CorrectedResultCollector) {
      setUpFiltering((CorrectedResultCollector) el);
    }
  }

  @Override
  protected Container makeTitlePanel() {
    jPanelFilter = new FilterPanel();
    Container panel = super.makeTitlePanel();
    panel.add(jPanelFilter);
    return panel;
  }

  @Override
  public void clearGui() {
    super.clearGui();
    jPanelFilter.clearGui();
  }

  /**
   * We use this method to get the data, since we are using ObjectTableModel, so the calling
   * getDataVector doesn't work as expected.
   *
   * @param model {@link ObjectTableModel}
   * @param formats Array of {@link Format} array can contain null formatters in this case value is
   *     added as is
   * @return the data from the model
   */
  public static List<List<Object>> getAllTableData(ObjectTableModel model, Format[] formats) {
    List<List<Object>> data = new ArrayList<List<Object>>();
    if (model.getRowCount() > 0) {
      for (int rw = 0; rw < model.getRowCount(); rw++) {
        int cols = model.getColumnCount();
        List<Object> column = new ArrayList<Object>();
        data.add(column);
        for (int idx = 0; idx < cols; idx++) {
          Object val = model.getValueAt(rw, idx);
          if (formats[idx] != null) {
            column.add(formats[idx].format(val));
          } else {
            column.add(val);
          }
        }
      }
    }
    return data;
  }

  @Override
  public void actionPerformed(ActionEvent ev) {
    if (ev.getSource() == saveTable) {
      JFileChooser chooser = FileDialoger.promptToSaveFile("synthesis.csv"); // $NON-NLS-1$
      if (chooser == null) {
        return;
      }
      FileWriter writer = null;
      try {
        writer = new FileWriter(chooser.getSelectedFile()); // TODO
        // Charset ?
        CSVSaveService.saveCSVStats(
            getAllTableData(model, FORMATS),
            writer,
            saveHeaders.isSelected() ? getLabels(COLUMNS) : null);
      } catch (FileNotFoundException e) {
        log.warn(e.getMessage());
      } catch (IOException e) {
        log.warn(e.getMessage());
      } finally {
        JOrphanUtils.closeQuietly(writer);
      }
    }
  }

  /**
   * @param keys I18N keys
   * @return labels
   */
  static String[] getLabels(String[] keys) {
    String[] labels = new String[keys.length];
    for (int i = 0; i < labels.length; i++) {
      labels[i] =
          MessageFormat.format(JMeterUtils.getResString(keys[i]), COLUMNS_MSG_PARAMETERS[i]);
    }
    return labels;
  }

  @Override
  public String getWikiPage() {
    return WIKIPAGE;
  }

  @Override
  public GraphPanelChart getGraphPanelChart() {
    return new FakeGraphPanelChart();
  }

  @Override
  protected JSettingsPanel createSettingsPanel() {
    return new JSettingsPanel(this, 0);
  }

  private class FakeGraphPanelChart extends GraphPanelChart {

    public FakeGraphPanelChart() {
      super(false);
    }

    @Override
    public void saveGraphToCSV(File file) throws IOException {
      log.info("Saving CSV to " + file.getAbsolutePath());

      FileWriter writer = null;
      try {
        writer = new FileWriter(file);
        CSVSaveService.saveCSVStats(
            getAllTableData(model, FORMATS),
            writer,
            saveHeaders.isSelected() ? getLabels(COLUMNS) : null);
      } catch (FileNotFoundException e) {
        log.warn(e.getMessage());
      } catch (IOException e) {
        log.warn(e.getMessage());
      } finally {
        try {
          writer.close();
        } catch (IOException ex) {
          log.warn("There was problem closing file stream", ex);
        }
      }
    }

    @Override
    public void saveGraphToPNG(File file, int w, int h) throws IOException {
      throw new UnsupportedOperationException("This plugin type cannot be saved as image");
    }
  }

  /** Renders items in a JTable by converting from resource names. */
  private class JMeterHeaderAsPropertyRenderer extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 240L;
    private Object[][] columnsMsgParameters;

    /** */
    public JMeterHeaderAsPropertyRenderer() {
      this(null);
    }

    /** @param columnsMsgParameters Optional parameters of i18n keys */
    public JMeterHeaderAsPropertyRenderer(Object[][] columnsMsgParameters) {
      super();
      this.columnsMsgParameters = columnsMsgParameters;
    }

    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      if (table != null) {
        JTableHeader header = table.getTableHeader();
        if (header != null) {
          setForeground(header.getForeground());
          setBackground(header.getBackground());
          setFont(header.getFont());
        }
        setText(getText(value, row, column));
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(SwingConstants.CENTER);
      }
      return this;
    }

    /**
     * Get the text for the value as the translation of the resource name.
     *
     * @param value value for which to get the translation
     * @param column index which column message parameters should be used
     * @param row not used
     * @return the text
     */
    protected String getText(Object value, int row, int column) {
      if (value == null) {
        return "";
      }
      if (columnsMsgParameters != null && columnsMsgParameters[column] != null) {
        return MessageFormat.format(
            JMeterUtils.getResString(value.toString()), columnsMsgParameters[column]);
      } else {
        return JMeterUtils.getResString(value.toString());
      }
    }
  }
}
 public AWSCollector() {
   // TODO: document it
   interval = JMeterUtils.getPropDefault("jmeterPlugin.awsmon.interval", 1000);
 }
 static {
   autoGenerateFiles =
       (JMeterUtils.getPropDefault("forceAWSMonFile", "false")).trim().equalsIgnoreCase("true");
 }
예제 #10
0
  public boolean runTestPlan(String testPlanFilename) {

    jmeterResults = "";
    createJmeterEngine();
    File f = new File(testPlanFilename);
    if (!f.exists() || !f.isFile()) {
      jmeterResults += "Could not open " + testPlanFilename;
      System.out.println(jmeterResults);
      return false;
    }

    FileInputStream reader = null;
    try {
      reader = new FileInputStream(new File(testPlanFilename));
      currentHashTree = SaveService.loadTree(reader);
      // store log file in ./FitNesseRoot/files/testResults/testPlanFilename.log
      String logFile =
          new File(jmeterLogPath, (new File(testPlanFilename).getName() + ".log"))
              .getCanonicalPath();
      lastJmeterLog = logFile;

      @SuppressWarnings("deprecation") // Deliberate use of deprecated ctor
      JMeterTreeModel treeModel =
          new JMeterTreeModel(new Object()); // Create non-GUI version to avoid headless problems
      JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
      treeModel.addSubTree(currentHashTree, root);

      // Hack to resolve ModuleControllers in non GUI mode
      SearchByClass<ReplaceableController> replaceableControllers =
          new SearchByClass<ReplaceableController>(ReplaceableController.class);
      currentHashTree.traverse(replaceableControllers);
      Collection<ReplaceableController> replaceableControllersRes =
          replaceableControllers.getSearchResults();
      for (Iterator<ReplaceableController> iter = replaceableControllersRes.iterator();
          iter.hasNext(); ) {
        ReplaceableController replaceableController = iter.next();
        replaceableController.resolveReplacementSubTree(root);
      }

      // Remove the disabled items
      // For GUI runs this is done in Start.java
      JMeter.convertSubTree(currentHashTree);

      Summariser summer = null;
      String summariserName =
          JMeterUtils.getPropDefault("summariser.name", "summary"); // $NON-NLS-1$
      if (summariserName.length() > 0) {
        // log.info("Creating summariser <" + summariserName + ">");
        // println("Creating summariser <" + summariserName + ">");
        summer = new Summariser(summariserName);
      }

      if (logFile != null) {
        ResultCollector logger = new ResultCollector(summer);
        logger.setFilename(logFile);
        currentHashTree.add(currentHashTree.getArray()[0], logger);
      } else {
        // only add Summariser if it can not be shared with the ResultCollector
        if (summer != null) {
          currentHashTree.add(currentHashTree.getArray()[0], summer);
        }
      }

      // Used for remote notification of threads start/stop,see BUG 54152
      // Summariser uses this feature to compute correctly number of threads
      // when NON GUI mode is used
      currentHashTree.add(currentHashTree.getArray()[0], new RemoteThreadsListenerTestElement());

      jEngine.configure(currentHashTree);
      jEngine.runTest();
      // reader.close();
      JOrphanUtils.closeQuietly(reader);
      Util.waitForFileToExists(logFile, 5); // wait up to 5 seconds for file to exist
      String logStr = Util.fileToString(logFile);
      // logStr = logStr.replaceAll("\n", "<br/>\n");
      jmeterResults += logStr;
      jmeterResults += "Test " + testPlanFilename + " completed.";
      System.out.println("Test " + testPlanFilename + " completed.");

    } catch (Exception e) {
      e.printStackTrace();
      jmeterResults += "\r\nException: " + e.getMessage();
      return false;
    }
    return true;
  }
/**
 * TCPClient implementation. Reads data until the defined EOM byte is reached. If there is no EOM
 * byte defined, then reads until the end of the stream is reached. The EOM byte is defined by the
 * property "tcp.BinaryTCPClient.eomByte".
 *
 * <p>Input data is assumed to be in hex, and is converted to binary
 */
public class BinaryTCPClientImpl extends AbstractTCPClient {
  private static final Logger log = LoggingManager.getLoggerForClass();

  private static final int eomInt =
      JMeterUtils.getPropDefault("tcp.BinaryTCPClient.eomByte", 1000); // $NON_NLS-1$

  public BinaryTCPClientImpl() {
    super();
    setEolByte(eomInt);
    if (useEolByte) {
      log.info("Using eomByte=" + eolByte);
    }
  }

  /**
   * Convert hex string to binary byte array.
   *
   * @param hexEncodedBinary - hex-encoded binary string
   * @return Byte array containing binary representation of input hex-encoded string
   * @throws IllegalArgumentException if string is not an even number of hex digits
   */
  public static final byte[] hexStringToByteArray(String hexEncodedBinary) {
    if (hexEncodedBinary.length() % 2 == 0) {
      char[] sc = hexEncodedBinary.toCharArray();
      byte[] ba = new byte[sc.length / 2];

      for (int i = 0; i < ba.length; i++) {
        int nibble0 = Character.digit(sc[i * 2], 16);
        int nibble1 = Character.digit(sc[i * 2 + 1], 16);
        if (nibble0 == -1 || nibble1 == -1) {
          throw new IllegalArgumentException(
              "Hex-encoded binary string contains an invalid hex digit in '"
                  + sc[i * 2]
                  + sc[i * 2 + 1]
                  + "'");
        }
        ba[i] = (byte) ((nibble0 << 4) | (nibble1));
      }

      return ba;
    } else {
      throw new IllegalArgumentException(
          "Hex-encoded binary string contains an uneven no. of digits");
    }
  }

  /**
   * Input (hex) string is converted to binary and written to the output stream.
   *
   * @param os output stream
   * @param hexEncodedBinary hex-encoded binary
   */
  public void write(OutputStream os, String hexEncodedBinary) throws IOException {
    os.write(hexStringToByteArray(hexEncodedBinary));
    os.flush();
    if (log.isDebugEnabled()) {
      log.debug("Wrote: " + hexEncodedBinary);
    }
  }

  /** {@inheritDoc} */
  public void write(OutputStream os, InputStream is) {
    throw new UnsupportedOperationException("Method not supported for Length-Prefixed data.");
  }

  /**
   * Reads data until the defined EOM byte is reached. If there is no EOM byte defined, then reads
   * until the end of the stream is reached. Response data is converted to hex-encoded binary
   *
   * @return hex-encoded binary string
   * @throws ReadException
   */
  public String read(InputStream is) throws ReadException {
    ByteArrayOutputStream w = new ByteArrayOutputStream();
    try {
      byte[] buffer = new byte[4096];
      int x = 0;
      while ((x = is.read(buffer)) > -1) {
        w.write(buffer, 0, x);
        if (useEolByte && (buffer[x - 1] == eolByte)) {
          break;
        }
      }

      IOUtils.closeQuietly(w); // For completeness
      final String hexString = JOrphanUtils.baToHexString(w.toByteArray());
      if (log.isDebugEnabled()) {
        log.debug("Read: " + w.size() + "\n" + hexString);
      }
      return hexString;
    } catch (IOException e) {
      throw new ReadException("", e, JOrphanUtils.baToHexString(w.toByteArray()));
    }
  }
}