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); }
/* (non-Javadoc) * @see com.microstrategy.mfloadtest.jdbcwriter.BaseTestListener#testEnded() */ @Override public void testEnded() { // this can only come from 1 thread final Timestamp lTimeStamp = new Timestamp(new Date().getTime()); // do unconditionally mTrendLineTimer.cancel(); try { final TestJobAgentWorker lAgent = mAgentProvider.get(); lAgent.setEndTimestamp(lTimeStamp); lAgent.setLastNumberOfActiveThreads(0l); mAgentUpdater.write(lAgent); mSWriter.flush(); mSWriter.close(); mAgentUpdateThread.interrupt(); } catch (Exception e) { LOGGER.error("testEnded", e); throw new RuntimeException("testEnded", e); } }
/** * The method is responsible for reading each line, and breaking out of the while loop if a set * number of lines is given. * * @param breader */ protected int parse(BufferedReader breader, TestElement el, int parseCount) { int actualCount = 0; String line = null; try { // read one line at a time using // BufferedReader line = breader.readLine(); while (line != null) { if (line.length() > 0) { actualCount += this.parseLine(line, el); } // we check the count to see if we have exceeded // the number of lines to parse. There's no way // to know where to stop in the file. Therefore // we use break to escape the while loop when // we've reached the count. if (parseCount != -1 && actualCount >= parseCount) { break; } line = breader.readLine(); } if (line == null) { breader.close(); breader = null; this.READER = null; // this.READER = new BufferedReader(new // FileReader(this.SOURCE)); // parse(this.READER,el); } } catch (IOException ioe) { log.error("Error reading log file", ioe); } return actualCount; }
/** * 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(); }
public static byte[] encryptDataBytes(PublicKey publicKey, byte[] data) { try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider()); cipher.init(1, publicKey); int blockSize = cipher.getBlockSize(); int outputSize = cipher.getOutputSize(data.length); int leavedSize = data.length % blockSize; int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize; byte[] raw = new byte[outputSize * blocksSize]; int i = 0; while (data.length - i * blockSize > 0) { if (data.length - i * blockSize > blockSize) cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize); else { cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize); } i++; } return raw; } catch (Exception e) { logger.error(e.getMessage()); return null; } }
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); } }
/** Returns last line of output from the command */ public SampleResult sample(Entry e) { SampleResult res = new SampleResult(); res.setSampleLabel( getName() + ":(" + getUsername() + "@" + getHostname() + ":" + getPort() + ")"); // Set up sampler return types res.setSamplerData(action + " " + source); res.setDataType(SampleResult.TEXT); res.setContentType("text/plain"); String response; if (getSession() == null) { connect(); } try { if (getSession() == null) { log.error( "Failed to connect to server with credentials " + getUsername() + "@" + getHostname() + ":" + getPort() + " pw=" + getPassword()); throw new NullPointerException("Failed to connect to server: " + getFailureReason()); } response = doFileTransfer(getSession(), source, destination, res); res.setResponseData(response.getBytes()); res.setSuccessful(true); res.setResponseMessageOK(); } catch (JSchException e1) { res.setSuccessful(false); res.setResponseCode("JSchException"); res.setResponseMessage(e1.getMessage()); } catch (SftpException e1) { res.setSuccessful(false); res.setResponseCode("SftpException"); res.setResponseMessage(e1.getMessage()); } catch (IOException e1) { res.setSuccessful(false); res.setResponseCode("IOException"); res.setResponseMessage(e1.getMessage()); } catch (NullPointerException e1) { res.setSuccessful(false); res.setResponseCode("Connection Failed"); res.setResponseMessage(e1.getMessage()); } finally { // Try a disconnect/sesson = null here instead of in finalize. disconnect(); setSession(null); } return res; }
public FocusRequester(Component comp) { this.comp = comp; try { SwingUtilities.invokeLater(this); } catch (Exception e) { log.error("", e); // $NON-NLS-1$ } }
public RegexFunction() { valueIndex = between = name = ""; try { templatePattern = compiler.compile("\\$(\\d+)\\$"); } catch (MalformedPatternException e) { log.error("", e); } }
public static String encryptData(String data, String encoding, PublicKey key) { try { byte[] encryptedData = encryptDataBytes(key, data.getBytes(encoding)); return new String(base64Encode(encryptedData), encoding); } catch (Exception e) { logger.error(e.getMessage()); } return ""; }
public static PublicKey getEncryptCertPublicKey() { try { if (null == encryptCert) initEncryptCert(); return encryptCert.getPublicKey(); } catch (Exception e) { logger.error(e.getMessage()); } return null; }
private boolean isFirstElementGroup(String rawData) { try { Pattern pattern = compiler.compile("^\\$\\d+\\$"); return new Perl5Matcher().contains(rawData, pattern); } catch (MalformedPatternException e) { log.error("", e); return false; } }
@Override protected AndroidDriver createBrowser() { try { return new AndroidDriver(new URL(getAndroidDriverUrl()), createCapabilities()); } catch (MalformedURLException e) { LOGGER.error("MalformedURLException thrown for invalid URL: " + getAndroidDriverUrl()); return null; } }
@Override public synchronized void process() { if (file == null) { log.info("Creating file object: " + getFileName()); try { file = new FileInputStream(getFileName()).getChannel(); } catch (FileNotFoundException ex) { log.error(getFileName(), ex); return; } } String rawData; try { rawData = readNextChunk(getNextChunkSize()); } catch (EndOfFileException ex) { if (getRewindOnEOF()) { if (log.isDebugEnabled()) { log.debug("Rewind file"); } try { file.position(0); } catch (IOException ex1) { log.error("Cannot rewind", ex1); } process(); return; } else { log.info("End of file reached: " + getFileName()); if (JMeterContextService.getContext().getThread() != null) { JMeterContextService.getContext().getThread().stop(); } throw new RuntimeEOFException("End of file reached", ex); } } catch (IOException ex) { log.error("Error reading next chunk", ex); throw new RuntimeException("Error reading next chunk", ex); } final JMeterVariables vars = JMeterContextService.getContext().getVariables(); if (vars != null) { vars.put(getVarName(), rawData); } }
public static String encryptPin(String pin, String pan, String encoding) { byte[] pinBlock = pin2PinBlockWithPan(pin, pan); try { byte[] result = encryptDataBytes(getEncryptCertPublicKey(), pinBlock); return new String(base64Encode(result), encoding); } catch (Exception e) { logger.error(e.getMessage()); } return ""; }
@Override public void threadFinished() { try { if (channel != null) { channel.close(); } } catch (IOException ex) { log.error("Cannot close channel", ex); } }
/** * ********************************************************** !ToDo (Method description) * * @param body !ToDo (Parameter description) * ********************************************************* */ public void setText(String body) { try { Writer writer = new FileWriter(this); writer.write(body); writer.flush(); writer.close(); } catch (IOException ioe) { log.error("", ioe); } }
/** * 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 "") * - responseMessage (default "") * - 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; }
public static void initEncryptCert() { CertificateFactory cf = null; FileInputStream in = null; try { cf = CertificateFactory.getInstance("X.509"); in = new FileInputStream(UPMPConstant.encryptCertPath); encryptCert = (X509Certificate) cf.generateCertificate(in); } catch (CertificateException e) { logger.error(e.getMessage()); } catch (FileNotFoundException e) { logger.error(e.getMessage()); } finally { if (null != in) try { in.close(); } catch (IOException e) { logger.error(e.getMessage()); } } }
@Override public void generateErrorSample(String label, String errorMsg) { AWSMonSampleResult res = new AWSMonSampleResult(); res.setSampleLabel(label); res.setValue(-1L); res.setResponseMessage(errorMsg); res.setSuccessful(false); SampleEvent e = new SampleEvent(res, AWSMON); super.sampleOccurred(e); log.error("AWSmon plugin error: " + errorMsg); }
/** {@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); } } }
@Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (java.awt.Desktop.isDesktopSupported()) { try { java.awt.Desktop.getDesktop().browse(e.getURL().toURI()); } catch (Exception ex) { log.error("Error opening URL in browser:" + e.getURL()); } } } }
/** * 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(); }
// 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); }
/** * 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); }
private void processConnectors() { Iterator<Object> it = connectors.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); AWSMonAgentConnector connector = connectors.get(key); try { connector.generateSamples(this); } catch (IOException e) { log.error(e.getMessage()); connectors.put(key, new UnavailableAgentConnector(e)); } } }
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); } }
/** * parse the entire file. * * @return boolean success/failure */ public int parse(TestElement el, int parseCount) { if (this.SOURCE == null) { this.SOURCE = new File(this.FILENAME); } try { if (this.READER == null) { this.READER = getReader(this.SOURCE); } return parse(this.READER, el, parseCount); } catch (Exception exception) { log.error("Problem creating samples", exception); } return -1; // indicate that an error occured }
/** * 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); } }
/** * Compile a general string into a list of elements for a CompoundVariable. * * <p>Calls {@link #makeFunction(StringReader)} if it detects an unescaped "${". * * <p>Removes escapes from '$', ',' and '\'. * * @param value string containing the function / variable references (if any) * @return list of Strings or Objects representing functions */ LinkedList<Object> compileString(String value) throws InvalidVariableException { StringReader reader = new StringReader(value); LinkedList<Object> result = new LinkedList<Object>(); StringBuilder buffer = new StringBuilder(); char previous = ' '; // TODO - why use space? char[] current = new char[1]; try { while (reader.read(current) == 1) { if (current[0] == '\\') { // Handle escapes previous = current[0]; if (reader.read(current) == 0) { break; } // Keep the '\' unless it is one of the escapable chars '$' ',' or '\' // N.B. This method is used to parse function parameters, so must treat ',' as special if (current[0] != '$' && current[0] != ',' && current[0] != '\\') { buffer.append(previous); // i.e. '\\' } previous = ' '; buffer.append(current[0]); continue; } else if (current[0] == '{' && previous == '$') { // found "${" buffer.deleteCharAt(buffer.length() - 1); if (buffer.length() > 0) { // save leading text result.add(buffer.toString()); buffer.setLength(0); } result.add(makeFunction(reader)); previous = ' '; } else { buffer.append(current[0]); previous = current[0]; } } if (buffer.length() > 0) { result.add(buffer.toString()); } } catch (IOException e) { log.error("Error parsing function: " + value, e); result.clear(); result.add(value); } if (result.size() == 0) { result.add(""); } return result; }