Ejemplo n.º 1
0
  private List<MatchResult> processMatches(
      Pattern pattern, String regex, SampleResult result, int matchNumber, JMeterVariables vars) {
    if (log.isDebugEnabled()) {
      log.debug("Regex = " + regex);
    }

    Perl5Matcher matcher = JMeterUtils.getMatcher();
    List<MatchResult> matches = new ArrayList<MatchResult>();
    int found = 0;

    if (isScopeVariable()) {
      String inputString = vars.get(getVariableName());
      if (inputString == null) {
        log.warn(
            "No variable '"
                + getVariableName()
                + "' found to process by RegexExtractor '"
                + getName()
                + "', skipping processing");
        return Collections.emptyList();
      }
      matchStrings(matchNumber, matcher, pattern, matches, found, inputString);
    } else {
      List<SampleResult> sampleList = getSampleList(result);
      for (SampleResult sr : sampleList) {
        String inputString = getInputString(sr);
        found = matchStrings(matchNumber, matcher, pattern, matches, found, inputString);
        if (matchNumber > 0 && found == matchNumber) { // no need to process further
          break;
        }
      }
    }
    return matches;
  }
 /**
  * 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);
   }
 }
  private void updateAgent() {

    // We need to write the agent to the db,
    // We'll potentially need to retry due to possible database locking
    // so we use the JPAAgentUpdater that already knows
    // how to do this
    try {
      // initial agent parameters
      final TestJobAgentWorker lAgent = mAgentProvider.get();

      LOGGER.info("Successfully retrieved agent " + lAgent);

      if (lAgent.getProcessID() != null) {
        LOGGER.info(
            "Process succsesfully retrieved "
                + lAgent.getProcessID()
                + ". Stopping agent update thread");

        mAgentUpdateThread.interrupt();
        return;
      }

      LOGGER.info("PID not yet set, retrieving and updating");
      configureAgentInitialParameters(lAgent);
      LOGGER.info("Updating agent");

      mAgentUpdater.write(lAgent);
    } catch (Exception e) {
      LOGGER.error("Couldn't write the agent", e);
    }
  }
  private void resolveInstallByDependency() {
    // resolve dependencies
    boolean hasModifications = true;
    while (hasModifications) {
      log.debug("Check install dependencies: " + additions);
      hasModifications = false;
      for (Plugin plugin : additions) {
        for (String pluginID : plugin.getDepends()) {
          Plugin depend = getPluginByID(pluginID);

          if (!depend.isInstalled() || deletions.contains(depend)) {
            if (!additions.contains(depend)) {
              log.debug("Add to install: " + depend);
              additions.add(depend);
              hasModifications = true;
            }
          }
        }

        if (hasModifications) {
          break; // prevent ConcurrentModificationException
        }
      }
    }
  }
Ejemplo n.º 5
0
 @Override
 public void mousePressed(MouseEvent e) {
   // Get the Main Frame.
   ReportMainFrame mainFrame = ReportGuiPackage.getInstance().getMainFrame();
   // Close any Main Menu that is open
   mainFrame.closeMenu();
   int selRow = tree.getRowForLocation(e.getX(), e.getY());
   if (tree.getPathForLocation(e.getX(), e.getY()) != null) {
     log.debug("mouse pressed, updating currentPath");
     currentPath = tree.getPathForLocation(e.getX(), e.getY());
   }
   if (selRow != -1) {
     // updateMainMenu(((JMeterGUIComponent)
     // getCurrentNode().getUserObject()).createPopupMenu());
     if (isRightClick(e)) {
       if (tree.getSelectionCount() < 2) {
         tree.setSelectionPath(currentPath);
       }
       if (getCurrentNode() != null) {
         log.debug("About to display pop-up");
         displayPopUp(e);
       }
     }
   }
 }
Ejemplo n.º 6
0
 /**
  * Do any initialization required by this client.
  *
  * <p>There is none, as it is done in runTest() in order to be able to vary the data for each
  * sample.
  *
  * @param context the context to run with. This provides access to initialization parameters.
  */
 @Override
 public void setupTest(JavaSamplerContext context) {
   if (LOG.isDebugEnabled()) {
     LOG.debug(whoAmI() + "\tsetupTest()");
     listParameters(context);
   }
 }
Ejemplo n.º 7
0
 @Override
 public void testEnded() {
   if (log.isDebugEnabled()) {
     log.debug(getTitle() + " testEnded");
   }
   ((MongoDB) getThreadContext().getVariables().getObject(getSource())).clear();
 }
Ejemplo n.º 8
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);
  }
  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);
    }
  }
  private void resolveDeleteByDependency() {
    // delete by depend
    boolean hasModifications = true;
    while (hasModifications) {
      log.debug("Check uninstall dependencies");
      hasModifications = false;
      for (Plugin plugin : deletions) {
        if (!additions.contains(plugin)) {
          for (Plugin dep : getDependants(plugin)) {
            if (!deletions.contains(dep) && dep.isInstalled()) {
              log.debug("Add to deletions: " + dep);
              deletions.add(dep);
              hasModifications = true;
            }
            if (additions.contains(dep)) {
              log.debug("Remove from additions: " + dep);
              additions.remove(dep);
              hasModifications = true;
            }
          }
        }

        if (hasModifications) {
          break; // prevent ConcurrentModificationException
        }
      }
    }
  }
Ejemplo n.º 11
0
 /**
  * parseLine calls the other parse methods to parse the given text.
  *
  * @param line
  */
 protected int parseLine(String line, TestElement el) {
   int count = 0;
   // we clean the line to get
   // rid of extra stuff
   String cleanedLine = this.cleanURL(line);
   log.debug("parsing line: " + line);
   // now we set request method
   el.setProperty(HTTPSamplerBase.METHOD, RMETHOD);
   if (FILTER != null) {
     log.debug("filter is not null");
     if (!FILTER.isFiltered(line, el)) {
       log.debug("line was not filtered");
       // increment the current count
       count++;
       // we filter the line first, before we try
       // to separate the URL into file and
       // parameters.
       line = FILTER.filter(cleanedLine);
       if (line != null) {
         createUrl(line, el);
       }
     } else {
       log.debug("Line was filtered");
     }
   } else {
     log.debug("filter was null");
     // increment the current count
     count++;
     // in the case when the filter is not set, we
     // parse all the lines
     createUrl(cleanedLine, el);
   }
   return count;
 }
  private void resolveDeleteLibs() {
    for (Plugin plugin : deletions) {
      if (additions.contains(plugin)) { // skip upgrades
        continue;
      }

      Map<String, String> libs = plugin.getLibs(plugin.getInstalledVersion());
      for (String lib : libs.keySet()) {
        if (Plugin.getLibInstallPath(lib) != null) {
          libDeletions.add(lib);
        } else {
          log.warn("Did not find library to uninstall it: " + lib);
        }
      }
    }

    for (Plugin plugin : allPlugins.keySet()) {
      if (additions.contains(plugin) || (plugin.isInstalled() && !deletions.contains(plugin))) {
        String ver =
            additions.contains(plugin)
                ? plugin.getCandidateVersion()
                : plugin.getInstalledVersion();
        // log.debug("Affects " + plugin + " v" + ver);
        Map<String, String> libs = plugin.getLibs(ver);
        for (String lib : libs.keySet()) {
          if (libDeletions.contains(lib)) {
            log.debug("Won't delete lib " + lib + " since it is used by " + plugin);
            libDeletions.remove(lib);
          }
        }
      }
    }
  }
 /** {@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);
 }
 @Override
 public void run() {
   try {
     supplyActiveThreads();
   } catch (InterruptedException e) {
     log.debug("Interrupted", e);
   }
   log.debug("Thread starter has done its job");
 }
 @Override
 public void process() {
   if (log.isDebugEnabled()) {
     log.debug(Thread.currentThread().getName() + " process " + isPerIteration()); // $NON-NLS-1$
   }
   if (!isPerIteration()) {
     setValues();
   }
 }
Ejemplo n.º 16
0
 /** Tests that JMeterVariables contain inputVal_<count>, if not we can stop iterating */
 private boolean endOfArguments() {
   JMeterContext context = getThreadContext();
   String inputVariable = getInputVal() + getSeparator() + (loopCount + 1);
   if (context.getVariables().getObject(inputVariable) != null) {
     log.debug("ForEach resultstring eofArgs= false");
     return false;
   }
   log.debug("ForEach resultstring eofArgs= true");
   return true;
 }
 /** @see LoopIterationListener#iterationStart(LoopIterationEvent) */
 @Override
 public void iterationStart(LoopIterationEvent event) {
   if (log.isDebugEnabled()) {
     log.debug(
         Thread.currentThread().getName() + " iteration start " + isPerIteration()); // $NON-NLS-1$
   }
   if (isPerIteration()) {
     setValues();
   }
 }
 @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");
 }
Ejemplo n.º 19
0
  /**
   * Perform a single sample.<br>
   * In this case, this method will simply sleep for some amount of time.
   *
   * <p>This method returns a <code>SampleResult</code> object.
   *
   * <pre>
   *
   *  The following fields are always set:
   *  - responseCode (default &quot;&quot;)
   *  - responseMessage (default &quot;&quot;)
   *  - label (set from LABEL_NAME parameter if it exists, else element name)
   *  - success (default true)
   *
   * </pre>
   *
   * The following fields are set from the user-defined parameters, if supplied:
   *
   * <pre>
   * -samplerData - responseData
   * </pre>
   *
   * @see org.apache.jmeter.samplers.SampleResult#sampleStart()
   * @see org.apache.jmeter.samplers.SampleResult#sampleEnd()
   * @see org.apache.jmeter.samplers.SampleResult#setSuccessful(boolean)
   * @see org.apache.jmeter.samplers.SampleResult#setSampleLabel(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseCode(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseMessage(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseData(byte [])
   * @see org.apache.jmeter.samplers.SampleResult#setDataType(String)
   * @param context the context to run with. This provides access to initialization parameters.
   * @return a SampleResult giving the results of this sample.
   */
  @Override
  public SampleResult runTest(JavaSamplerContext context) {
    setupValues(context);

    SampleResult results = new SampleResult();

    results.setResponseCode(responseCode);
    results.setResponseMessage(responseMessage);
    results.setSampleLabel(label);

    if (samplerData != null && samplerData.length() > 0) {
      results.setSamplerData(samplerData);
    }

    if (resultData != null && resultData.length() > 0) {
      results.setResponseData(resultData, null);
      results.setDataType(SampleResult.TEXT);
    }

    // Record sample start time.
    results.sampleStart();

    long sleep = sleepTime;
    if (sleepTime > 0 && sleepMask > 0) { // / Only do the calculation if
      // it is needed
      long start = System.currentTimeMillis();
      // Generate a random-ish offset value using the current time.
      sleep = sleepTime + (start % sleepMask);
    }

    try {
      // Execute the sample. In this case sleep for the
      // specified time, if any
      if (sleep > 0) {
        TimeUnit.MILLISECONDS.sleep(sleep);
      }
      results.setSuccessful(success);
    } catch (InterruptedException e) {
      LOG.warn("JavaTest: interrupted.");
      results.setSuccessful(true);
    } catch (Exception e) {
      LOG.error("JavaTest: error during sample", e);
      results.setSuccessful(false);
    } finally {
      // Record end time and populate the results.
      results.sampleEnd();
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(whoAmI() + "\trunTest()" + "\tTime:\t" + results.getTime());
      listParameters(context);
    }

    return results;
  }
Ejemplo n.º 20
0
  /** {@inheritDoc} */
  @Override
  public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
      throws InvalidVariableException {

    if (bshInterpreter == null) // did we find BeanShell?
    {
      throw new InvalidVariableException("BeanShell not found");
    }

    JMeterContext jmctx = JMeterContextService.getContext();
    JMeterVariables vars = jmctx.getVariables();

    String script = ((CompoundVariable) values[0]).execute();
    String varName = ""; // $NON-NLS-1$
    if (values.length > 1) {
      varName = ((CompoundVariable) values[1]).execute().trim();
    }

    String resultStr = ""; // $NON-NLS-1$

    log.debug("Script=" + script);

    try {

      // Pass in some variables
      if (currentSampler != null) {
        bshInterpreter.set("Sampler", currentSampler); // $NON-NLS-1$
      }

      if (previousResult != null) {
        bshInterpreter.set("SampleResult", previousResult); // $NON-NLS-1$
      }

      // Allow access to context and variables directly
      bshInterpreter.set("ctx", jmctx); // $NON-NLS-1$
      bshInterpreter.set("vars", vars); // $NON-NLS-1$
      bshInterpreter.set("props", JMeterUtils.getJMeterProperties()); // $NON-NLS-1$
      bshInterpreter.set("threadName", Thread.currentThread().getName()); // $NON-NLS-1$

      // Execute the script
      Object bshOut = bshInterpreter.eval(script);
      if (bshOut != null) {
        resultStr = bshOut.toString();
      }
      if (vars != null && varName.length() > 0) { // vars will be null on TestPlan
        vars.put(varName, resultStr);
      }
    } catch (Exception ex) // Mainly for bsh.EvalError
    {
      log.warn("Error running BSH script", ex);
    }

    log.debug("Output=" + resultStr);
    return resultStr;
  }
Ejemplo n.º 21
0
 public static String encrypt(byte[] key, Map<String, Object> req) {
   String request = JsonUtil.toJson(req).toString();
   byte[] hex = null;
   try {
     hex = DESUtil.ecbEncrypt(key, request.getBytes(), 2);
   } catch (GeneralSecurityException e) {
     logger.error(e.getMessage());
     logger.error(e.getStackTrace().toString());
   }
   return BytesUtil.bytesToHex(hex);
 }
Ejemplo n.º 22
0
 /** {@inheritDoc} */
 @Override
 public void testEnded() {
   if (purgeQueue()) {
     log.info("Purging queue " + getQueue());
     try {
       channel.queuePurge(getQueue());
     } catch (IOException e) {
       log.error("Failed to purge queue " + getQueue(), e);
     }
   }
 }
Ejemplo n.º 23
0
 public static boolean checkSign(
     String qstring, String signature, String securityKey, String charset) {
   logger.debug("Request signature: " + signature);
   if (null == signature) {
     return false;
   }
   String generateSignature = md5(qstring + md5(securityKey, charset), charset);
   logger.debug("request to be signatured: " + qstring);
   logger.debug("Generate signature: " + generateSignature);
   return signature.equals(generateSignature);
 }
Ejemplo n.º 24
0
 public SampleResult runTest(JavaSamplerContext arg0) {
   log.info("<<<发送地址:" + conf.getBaseUri() + conf.getApiUri());
   log.info("<<<发送数据:" + sb.toString());
   try {
     HttpSend.doPost(conf, headMsg, sb.toString(), log);
   } catch (Exception e) {
     log.info("ERROR...", e);
   }
   results.setSuccessful(true);
   return results;
 }
 @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");
   }
 }
Ejemplo n.º 26
0
  public static boolean checkSign(Map<String, String> req, String securityKey) {
    String signature = (String) req.get("signature");
    logger.debug("Request signature: " + signature);
    if (null == signature) {
      return false;
    }

    Map<String, String> filterReq = paraRailwayFilter(req);
    String generateSignature = buildSignature(filterReq, securityKey);
    logger.debug("Generate signature: " + generateSignature);
    return signature.equals(generateSignature);
  }
  /** disconnect from the server */
  public static void disconnect(DirContext dirContext) {
    if (dirContext == null) {
      log.info("Cannot disconnect null context");
      return;
    }

    try {
      dirContext.close();
    } catch (NamingException e) {
      log.warn("Ldap client disconnect - ", e);
    }
  }
Ejemplo n.º 28
0
 /**
  * Compile a string into a function or SimpleVariable.
  *
  * <p>Called by {@link #compileString(String)} when that has detected "${".
  *
  * <p>Calls {@link CompoundVariable#getNamedFunction(String)} if it detects: '(' - start of
  * parameter list '}' - end of function call
  *
  * @param reader points to input after the "${"
  * @return the function or variable object (or a String)
  */
 Object makeFunction(StringReader reader) throws InvalidVariableException {
   char[] current = new char[1];
   char previous = ' '; // TODO - why use space?
   StringBuilder buffer = new StringBuilder();
   Object function;
   try {
     while (reader.read(current) == 1) {
       if (current[0] == '\\') {
         if (reader.read(current) == 0) {
           break;
         }
         previous = ' ';
         buffer.append(current[0]);
         continue;
       } else if (current[0] == '(' && previous != ' ') {
         String funcName = buffer.toString();
         function = CompoundVariable.getNamedFunction(funcName);
         if (function instanceof Function) {
           ((Function) function).setParameters(parseParams(reader));
           if (reader.read(current) == 0 || current[0] != '}') {
             reader.reset(); // set to start of string
             char[] cb = new char[100];
             reader.read(cb); // return deliberately ignored
             throw new InvalidVariableException(
                 "Expected } after " + funcName + " function call in " + new String(cb));
           }
           if (function instanceof TestListener) {
             StandardJMeterEngine.register((TestListener) function);
           }
           return function;
         } else { // Function does not exist, so treat as per missing variable
           buffer.append(current[0]);
         }
         continue;
       } else if (current[0] == '}') { // variable, or function with no parameter list
         function = CompoundVariable.getNamedFunction(buffer.toString());
         if (function instanceof Function) { // ensure that setParameters() is called.
           ((Function) function).setParameters(new LinkedList<CompoundVariable>());
         }
         buffer.setLength(0);
         return function;
       } else {
         buffer.append(current[0]);
         previous = current[0];
       }
     }
   } catch (IOException e) {
     log.error("Error parsing function: " + buffer.toString(), e);
     return null;
   }
   log.warn("Probably an invalid function string: " + buffer.toString());
   return buffer.toString();
 }
 private void shutdownConnectors() {
   log.debug("Shutting down connectors");
   Iterator<Object> it = connectors.keySet().iterator();
   while (it.hasNext()) {
     Object key = it.next();
     final AWSMonAgentConnector conn = connectors.get(key);
     log.debug("Shutting down " + conn.toString());
     // Fix ConcurrentModificationException if more than one host
     // connectors.remove(key);
     it.remove();
     conn.disconnect();
   }
 }
Ejemplo n.º 30
0
 /**
  * close() will stop the connection first. Then it closes the subscriber, session and connection.
  */
 public void close() { // called from threadFinished() thread
   log.debug("close()");
   try {
     if (CONN != null) {
       CONN.stop();
     }
   } catch (JMSException e) {
     log.error(e.getMessage());
   }
   Utils.close(SUBSCRIBER, log);
   Utils.close(SESSION, log);
   Utils.close(CONN, log);
 }