protected void initManager(ScriptEngineManager sem) {
    final String label = getName();
    final String fileName = getFilename();
    final String scriptParameters = getParameters();
    // Use actual class name for log
    final Logger logger = LoggingManager.getLoggerForShortName(getClass().getName());

    sem.put("log", logger);
    sem.put("Label", label);
    sem.put("FileName", fileName);
    sem.put("Parameters", scriptParameters);
    String[] args = JOrphanUtils.split(scriptParameters, " "); // $NON-NLS-1$
    sem.put("args", args);
    // Add variables for access to context and variables
    JMeterContext jmctx = JMeterContextService.getContext();
    sem.put("ctx", jmctx);
    JMeterVariables vars = jmctx.getVariables();
    sem.put("vars", vars);
    Properties props = JMeterUtils.getJMeterProperties();
    sem.put("props", props);
    // For use in debugging:
    sem.put("OUT", System.out);

    // Most subclasses will need these:
    Sampler sampler = jmctx.getCurrentSampler();
    sem.put("sampler", sampler);
    SampleResult prev = jmctx.getPreviousResult();
    sem.put("prev", prev);
  }
  protected void initManager(BSFManager mgr) throws BSFException {
    final String label = getName();
    final String fileName = getFilename();
    final String scriptParameters = getParameters();
    // Use actual class name for log
    final Logger logger = LoggingManager.getLoggerForShortName(getClass().getName());
    mgr.declareBean("log", logger, Logger.class); // $NON-NLS-1$
    mgr.declareBean("Label", label, String.class); // $NON-NLS-1$
    mgr.declareBean("FileName", fileName, String.class); // $NON-NLS-1$
    mgr.declareBean("Parameters", scriptParameters, String.class); // $NON-NLS-1$
    String[] args = JOrphanUtils.split(scriptParameters, " "); // $NON-NLS-1$
    mgr.declareBean("args", args, args.getClass()); // $NON-NLS-1$
    // Add variables for access to context and variables
    JMeterContext jmctx = JMeterContextService.getContext();
    JMeterVariables vars = jmctx.getVariables();
    Properties props = JMeterUtils.getJMeterProperties();

    mgr.declareBean("ctx", jmctx, jmctx.getClass()); // $NON-NLS-1$
    mgr.declareBean("vars", vars, vars.getClass()); // $NON-NLS-1$
    mgr.declareBean("props", props, props.getClass()); // $NON-NLS-1$
    // For use in debugging:
    mgr.declareBean("OUT", System.out, PrintStream.class); // $NON-NLS-1$

    // Most subclasses will need these:
    Sampler sampler = jmctx.getCurrentSampler();
    mgr.declareBean("sampler", sampler, Sampler.class);
    SampleResult prev = jmctx.getPreviousResult();
    mgr.declareBean("prev", prev, SampleResult.class);
  }
  private synchronized String readNextChunk(int capacity) throws IOException {
    if (capacity == 0) {
      throw new EndOfFileException("Zero chunk size, possibly end of file reached.");
    }

    ByteBuffer buf = ByteBuffer.allocateDirect(capacity);
    byte[] dst = new byte[capacity];

    int cnt = file.read(buf);
    // log.debug("Read " + cnt);
    if (cnt != capacity) {
      throw new IOException(
          "Expected chunk size (" + capacity + ") differs from read bytes count (" + cnt + ")");
    }

    buf.flip();
    buf.get(dst);
    if (log.isDebugEnabled()) {
      log.debug("Chunk : " + new String(dst));
    }

    if (isHexEncode()) {
      return JOrphanUtils.baToHexString(dst);
    } else {
      return new String(dst, binaryCharset);
    }
  }
Пример #4
0
  /**
   * Read the whole file content and return it as a string.
   *
   * @return the content of the file
   */
  public String getText() {
    String lineEnd = System.getProperty("line.separator"); // $NON-NLS-1$
    StringBuilder sb = new StringBuilder();
    Reader reader = null;
    BufferedReader br = null;
    try {
      if (encoding == null) {
        reader = new FileReader(this);
      } else {
        reader = new InputStreamReader(new FileInputStream(this), encoding);
      }
      br = new BufferedReader(reader);
      String line = "NOTNULL"; // $NON-NLS-1$
      while (line != null) {
        line = br.readLine();
        if (line != null) {
          sb.append(line + lineEnd);
        }
      }
    } catch (IOException ioe) {
      log.error("", ioe); // $NON-NLS-1$
    } finally {
      JOrphanUtils.closeQuietly(br); // closes reader as well
    }

    return sb.toString();
  }
Пример #5
0
  /**
   * Converts (X)HTML response to DOM object Tree. This version cares of charset of response.
   *
   * @param unicodeData
   * @return
   */
  private Document parseResponse(String unicodeData, XPathExtractor extractor)
      throws UnsupportedEncodingException, IOException, ParserConfigurationException, SAXException,
          TidyException {
    // TODO: validate contentType for reasonable types?

    // NOTE: responseData encoding is server specific
    //       Therefore we do byte -> unicode -> byte conversion
    //       to ensure UTF-8 encoding as required by XPathUtil
    // convert unicode String -> UTF-8 bytes
    byte[] utf8data = unicodeData.getBytes("UTF-8"); // $NON-NLS-1$
    ByteArrayInputStream in = new ByteArrayInputStream(utf8data);
    boolean isXML = JOrphanUtils.isXML(utf8data);
    // this method assumes UTF-8 input data
    return XPathUtil.makeDocument(
        in,
        false,
        false,
        extractor.useNameSpace(),
        extractor.isTolerant(),
        extractor.isQuiet(),
        extractor.showWarnings(),
        extractor.reportErrors(),
        isXML,
        extractor.isDownloadDTDs());
  }
Пример #6
0
  private NodeList load()
      throws IOException, FileNotFoundException, ParserConfigurationException, SAXException,
          TransformerException {
    InputStream fis = null;
    NodeList nl = null;
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

      fis = new FileInputStream(fileName);
      nl = XPathAPI.selectNodeList(builder.parse(fis), xpath);
      log.debug("found " + nl.getLength());

    } catch (FileNotFoundException e) {
      log.warn(e.toString());
      throw e;
    } catch (IOException e) {
      log.warn(e.toString());
      throw e;
    } catch (ParserConfigurationException e) {
      log.warn(e.toString());
      throw e;
    } catch (SAXException e) {
      log.warn(e.toString());
      throw e;
    } catch (TransformerException e) {
      log.warn(e.toString());
      throw e;
    } finally {
      JOrphanUtils.closeQuietly(fis);
    }
    return nl;
  }
Пример #7
0
  // package protected so can be accessed by test class
  static String baMD5Hex(byte ba[]) {
    byte[] md5Result = {};

    try {
      MessageDigest md;
      md = MessageDigest.getInstance("MD5");
      md5Result = md.digest(ba);
    } catch (NoSuchAlgorithmException e) {
      log.error("", e);
    }
    return JOrphanUtils.baToHexString(md5Result);
  }
  /**
   * 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()));
    }
  }
  /**
   * Listen on the daemon port and handle incoming requests. This method will not exit until {@link
   * #stopServer()} is called or an error occurs.
   */
  @Override
  public void run() {
    except = null;
    running = true;
    ServerSocket mainSocket = null;

    try {
      log.info("Creating HttpMirror ... on port " + daemonPort);
      mainSocket = new ServerSocket(daemonPort);
      mainSocket.setSoTimeout(ACCEPT_TIMEOUT);
      log.info("HttpMirror up and running!");

      while (running) {
        try {
          // Listen on main socket
          Socket clientSocket = mainSocket.accept();
          if (running) {
            // Pass request to new thread
            HttpMirrorThread thd = new HttpMirrorThread(clientSocket);
            log.debug("Starting new Mirror thread");
            thd.start();
          } else {
            log.warn("Server not running");
            JOrphanUtils.closeQuietly(clientSocket);
          }
        } catch (InterruptedIOException e) {
          // Timeout occurred. Ignore, and keep looping until we're
          // told to stop running.
        }
      }
      log.info("HttpMirror Server stopped");
    } catch (Exception e) {
      except = e;
      log.warn("HttpMirror Server stopped", e);
    } finally {
      JOrphanUtils.closeQuietly(mainSocket);
    }
  }
Пример #10
0
 /** creates a string representation of this cookie */
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder(80);
   sb.append(getDomain());
   // flag - if all machines within a given domain can access the variable.
   // (from http://www.cookiecentral.com/faq/ 3.5)
   sb.append(TAB).append("TRUE");
   sb.append(TAB).append(getPath());
   sb.append(TAB).append(JOrphanUtils.booleanToSTRING(getSecure()));
   sb.append(TAB).append(getExpires());
   sb.append(TAB).append(getName());
   sb.append(TAB).append(getValue());
   return sb.toString();
 }
 @Test
 public void testEncode_withFlagsMac() throws UnsupportedEncodingException {
   System.out.println("encode f");
   // stackowerflow.com
   String data = "stackowerflow.com. A IN\n\r7\n\r-7";
   DNSJavaDecoder instance = new DNSJavaDecoder();
   ByteBuffer result = instance.encode(data);
   String exp = "3f3c000000010000000000000d737461636b6f776572666c6f7703636f6d0000010001";
   String res =
       JOrphanUtils.baToHexString(JMeterPluginsUtils.byteBufferToString(result).getBytes("cp866"));
   System.out.println(exp);
   System.out.println(res);
   assertEquals(exp.substring(8), res.substring(res.length() - exp.length() + 8));
 }
  /** {@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));
    }
  }
Пример #13
0
 /**
  * Create the file with the given string as content -- or replace it's content with the given
  * string if the file already existed.
  *
  * @param body New content for the file.
  */
 public void setText(String body) {
   Writer writer = null;
   try {
     if (encoding == null) {
       writer = new FileWriter(this);
     } else {
       writer = new OutputStreamWriter(new FileOutputStream(this), encoding);
     }
     writer.write(body);
     writer.flush();
   } catch (IOException ioe) {
     log.error("", ioe);
   } finally {
     JOrphanUtils.closeQuietly(writer);
   }
 }
  public String getQueryString(String contentEncoding) {
    // Check if the sampler has a specified content encoding
    if (JOrphanUtils.isBlank(contentEncoding)) {
      // We use the encoding which should be used according to the HTTP spec, which is UTF-8
      contentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
    }
    StringBuilder buf = new StringBuilder();
    PropertyIterator iter = getQueryStringParameters().iterator();
    boolean first = true;
    while (iter.hasNext()) {
      HTTPArgument item = null;
      Object objectValue = iter.next().getObjectValue();
      try {
        item = (HTTPArgument) objectValue;
      } catch (ClassCastException e) {
        item = new HTTPArgument((Argument) objectValue);
      }
      final String encodedName = item.getEncodedName();
      if (encodedName.length() == 0) {
        continue; // Skip parameters with a blank name (allows use of optional variables in
                  // parameter lists)
      }
      if (!first) {
        buf.append(QRY_SEP);
      } else {
        first = false;
      }
      buf.append(encodedName);
      if (item.getMetaData() == null) {
        buf.append(ARG_VAL_SEP);
      } else {
        buf.append(item.getMetaData());
      }

      // Encode the parameter value in the specified content encoding
      try {
        buf.append(item.getEncodedValue(contentEncoding));
      } catch (UnsupportedEncodingException e) {
        log.warn(
            "Unable to encode parameter in encoding "
                + contentEncoding
                + ", parameter value not included in query string");
      }
    }
    return buf.toString();
  }
 @Override
 public void actionPerformed(ActionEvent ev) {
   if (ev.getSource() == saveTable) {
     JFileChooser chooser = FileDialoger.promptToSaveFile("summary.csv"); // $NON-NLS-1$
     if (chooser == null) {
       return;
     }
     FileWriter writer = null;
     try {
       writer = new FileWriter(chooser.getSelectedFile());
       CSVSaveService.saveCSVStats(model, writer, saveHeaders.isSelected());
     } catch (FileNotFoundException e) {
       log.warn(e.getMessage());
     } catch (IOException e) {
       log.warn(e.getMessage());
     } finally {
       JOrphanUtils.closeQuietly(writer);
     }
   }
 }
 @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);
     }
   }
 }
 @Override
 public void actionPerformed(ActionEvent event) {
   boolean forceReloadData = false;
   final Object eventSource = event.getSource();
   if (eventSource == displayButton) {
     actionMakeGraph();
   } else if (eventSource == saveGraph) {
     saveGraphToFile = true;
     try {
       ActionRouter.getInstance()
           .getAction(ActionNames.SAVE_GRAPHICS, SaveGraphics.class.getName())
           .doAction(new ActionEvent(this, 1, ActionNames.SAVE_GRAPHICS));
     } catch (Exception e) {
       log.error(e.getMessage());
     }
   } else if (eventSource == saveTable) {
     JFileChooser chooser = FileDialoger.promptToSaveFile("statistics.csv"); // $NON-NLS-1$
     if (chooser == null) {
       return;
     }
     FileWriter writer = null;
     try {
       writer = new FileWriter(chooser.getSelectedFile()); // TODO Charset ?
       CSVSaveService.saveCSVStats(
           getAllTableData(), writer, saveHeaders.isSelected() ? COLUMNS : null);
     } catch (FileNotFoundException e) {
       log.warn(e.getMessage());
     } catch (IOException e) {
       log.warn(e.getMessage());
     } finally {
       JOrphanUtils.closeQuietly(writer);
     }
   } else if (eventSource == chooseForeColor) {
     Color color =
         JColorChooser.showDialog(
             null,
             JMeterUtils.getResString("aggregate_graph_choose_color"), // $NON-NLS-1$
             colorBarGraph);
     if (color != null) {
       colorForeGraph = color;
     }
   } else if (eventSource == syncWithName) {
     graphTitle.setText(namePanel.getName());
   } else if (eventSource == dynamicGraphSize) {
     // if use dynamic graph size is checked, we disable the dimension fields
     if (dynamicGraphSize.isSelected()) {
       graphWidth.setEnabled(false);
       graphHeight.setEnabled(false);
     } else {
       graphWidth.setEnabled(true);
       graphHeight.setEnabled(true);
     }
   } else if (eventSource == columnSelection) {
     if (columnSelection.isSelected()) {
       columnMatchLabel.setEnabled(true);
       applyFilterBtn.setEnabled(true);
       caseChkBox.setEnabled(true);
       regexpChkBox.setEnabled(true);
     } else {
       columnMatchLabel.setEnabled(false);
       applyFilterBtn.setEnabled(false);
       caseChkBox.setEnabled(false);
       regexpChkBox.setEnabled(false);
       // Force reload data
       forceReloadData = true;
     }
   }
   // Not 'else if' because forceReloadData
   if (eventSource == applyFilterBtn || forceReloadData) {
     if (columnSelection.isSelected()
         && columnMatchLabel.getText() != null
         && columnMatchLabel.getText().length() > 0) {
       pattern = createPattern(columnMatchLabel.getText());
     } else if (forceReloadData) {
       pattern = null;
       matcher = null;
     }
     if (getFile() != null && getFile().length() > 0) {
       clearData();
       FilePanel filePanel = (FilePanel) getFilePanel();
       filePanel.actionPerformed(event);
     }
   } else if (eventSource instanceof JButton) {
     // Changing color for column
     JButton btn = ((JButton) eventSource);
     if (btn.getName() != null) {
       try {
         BarGraph bar = eltList.get(Integer.parseInt(btn.getName()));
         Color color = JColorChooser.showDialog(null, bar.getLabel(), bar.getBackColor());
         if (color != null) {
           bar.setBackColor(color);
           btn.setBackground(bar.getBackColor());
         }
       } catch (NumberFormatException nfe) {
       } // nothing to do
     }
   }
 }
Пример #18
0
 /**
  * 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);
 }
Пример #19
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;
  }
Пример #20
0
 /**
  * @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);
 }