List of usage examples for java.lang Long parseLong
public static long parseLong(String s) throws NumberFormatException
From source file:com.xiangzhurui.util.ftp.FTPClientExample.java
public static void main(String[] args) throws UnknownHostException { boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;//from w w w. ja va2s. c om boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false, mlsd = false, mdtm = false, saveUnparseable = false; boolean lenient = false; long keepAliveTimeout = -1; int controlKeepAliveReplyTimeout = -1; int minParams = 5; // listings require 3 params String protocol = null; // SSL protocol String doCommand = null; String trustmgr = null; String proxyHost = null; int proxyPort = 80; String proxyUser = null; String proxyPassword = null; String username = null; String password = null; String encoding = null; String serverTimeZoneId = null; String displayTimeZoneId = null; String serverType = null; String defaultDateFormat = null; String recentDateFormat = null; int base = 0; for (base = 0; base < args.length; base++) { if (args[base].equals("-s")) { storeFile = true; } else if (args[base].equals("-a")) { localActive = true; } else if (args[base].equals("-A")) { username = "anonymous"; password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName(); } else if (args[base].equals("-b")) { binaryTransfer = true; } else if (args[base].equals("-c")) { doCommand = args[++base]; minParams = 3; } else if (args[base].equals("-d")) { mlsd = true; minParams = 3; } else if (args[base].equals("-e")) { useEpsvWithIPv4 = true; } else if (args[base].equals("-E")) { encoding = args[++base]; } else if (args[base].equals("-f")) { feat = true; minParams = 3; } else if (args[base].equals("-h")) { hidden = true; } else if (args[base].equals("-k")) { keepAliveTimeout = Long.parseLong(args[++base]); } else if (args[base].equals("-l")) { listFiles = true; minParams = 3; } else if (args[base].equals("-m")) { mdtm = true; minParams = 3; } else if (args[base].equals("-L")) { lenient = true; } else if (args[base].equals("-n")) { listNames = true; minParams = 3; } else if (args[base].equals("-p")) { protocol = args[++base]; } else if (args[base].equals("-S")) { serverType = args[++base]; } else if (args[base].equals("-t")) { mlst = true; minParams = 3; } else if (args[base].equals("-U")) { saveUnparseable = true; } else if (args[base].equals("-w")) { controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]); } else if (args[base].equals("-T")) { trustmgr = args[++base]; } else if (args[base].equals("-y")) { defaultDateFormat = args[++base]; } else if (args[base].equals("-Y")) { recentDateFormat = args[++base]; } else if (args[base].equals("-Z")) { serverTimeZoneId = args[++base]; } else if (args[base].equals("-z")) { displayTimeZoneId = args[++base]; } else if (args[base].equals("-PrH")) { proxyHost = args[++base]; String[] parts = proxyHost.split(":"); if (parts.length == 2) { proxyHost = parts[0]; proxyPort = Integer.parseInt(parts[1]); } } else if (args[base].equals("-PrU")) { proxyUser = args[++base]; } else if (args[base].equals("-PrP")) { proxyPassword = args[++base]; } else if (args[base].equals("-#")) { printHash = true; } else { break; } } int remain = args.length - base; if (username != null) { minParams -= 2; } if (remain < minParams) // server, user, pass, remote, local [protocol] { if (args.length > 0) { System.err.println("Actual Parameters: " + Arrays.toString(args)); } System.err.println(USAGE); System.exit(1); } String server = args[base++]; int port = 0; String[] parts = server.split(":"); if (parts.length == 2) { server = parts[0]; port = Integer.parseInt(parts[1]); } if (username == null) { username = args[base++]; password = args[base++]; } String remote = null; if (args.length - base > 0) { remote = args[base++]; } String local = null; if (args.length - base > 0) { local = args[base++]; } final FTPClient ftp; if (protocol == null) { if (proxyHost != null) { System.out.println("Using HTTP proxy server: " + proxyHost); ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword); } else { ftp = new FTPClient(); } } else { FTPSClient ftps; if (protocol.equals("true")) { ftps = new FTPSClient(true); } else if (protocol.equals("false")) { ftps = new FTPSClient(false); } else { String[] prot = protocol.split(","); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(protocol); } else { // protocol,true|false ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } ftp = ftps; if ("all".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(trustmgr)) { ftps.setTrustManager(null); } } if (printHash) { ftp.setCopyStreamListener(createListener()); } if (keepAliveTimeout >= 0) { ftp.setControlKeepAliveTimeout(keepAliveTimeout); } if (controlKeepAliveReplyTimeout >= 0) { ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } if (encoding != null) { ftp.setControlEncoding(encoding); } ftp.setListHiddenFiles(hidden); // suppress login details ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); final FTPClientConfig config; if (serverType != null) { config = new FTPClientConfig(serverType); } else { config = new FTPClientConfig(); } config.setUnparseableEntries(saveUnparseable); if (defaultDateFormat != null) { config.setDefaultDateFormatStr(defaultDateFormat); } if (recentDateFormat != null) { config.setRecentDateFormatStr(recentDateFormat); } ftp.configure(config); try { int reply; if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemType()); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { // in theory this should not be necessary as servers should // default to ASCII // but they don't all do so - see NET-500 ftp.setFileType(FTP.ASCII_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. if (localActive) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4(useEpsvWithIPv4); if (storeFile) { InputStream input; input = new FileInputStream(local); ftp.storeFile(remote, input); input.close(); } // Allow multiple list types for single invocation else if (listFiles || mlsd || mdtm || mlst || listNames) { if (mlsd) { for (FTPFile f : ftp.mlistDir(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString(displayTimeZoneId)); } } if (mdtm) { FTPFile f = ftp.mdtmFile(remote); System.out.println(f.getRawListing()); System.out.println(f.toFormattedString(displayTimeZoneId)); } if (mlst) { FTPFile f = ftp.mlistFile(remote); if (f != null) { System.out.println(f.toFormattedString(displayTimeZoneId)); } } if (listNames) { for (String s : ftp.listNames(remote)) { System.out.println(s); } } // Do this last because it changes the client if (listFiles) { if (lenient || serverTimeZoneId != null) { config.setLenientFutureDates(lenient); if (serverTimeZoneId != null) { config.setServerTimeZoneId(serverTimeZoneId); } ftp.configure(config); } for (FTPFile f : ftp.listFiles(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString(displayTimeZoneId)); } } } else if (feat) { // boolean feature check if (remote != null) { // See if the command is present if (ftp.hasFeature(remote)) { System.out.println("Has feature: " + remote); } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " was not detected"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } // Strings feature check String[] features = ftp.featureValues(remote); if (features != null) { for (String f : features) { System.out.println("FEAT " + remote + "=" + f + "."); } } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " is not present"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } } else { if (ftp.features()) { // Command listener has already printed the output } else { System.out.println("Failed: " + ftp.getReplyString()); } } } else if (doCommand != null) { if (ftp.doCommand(doCommand, remote)) { // Command listener has already printed the output // for(String s : com.xzr.practice.util.ftp.getReplyStrings()) { // System.out.println(s); // } } else { System.out.println("Failed: " + ftp.getReplyString()); } } else { OutputStream output; output = new FileOutputStream(local); ftp.retrieveFile(remote, output); output.close(); } ftp.noop(); // check that control connection is working OK ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }
From source file:de.unisb.cs.st.javaslicer.slicing.Slicer.java
public static void main(String[] args) throws InterruptedException { Options options = createOptions();// w w w . j av a2s . c om CommandLineParser parser = new GnuParser(); CommandLine cmdLine; try { cmdLine = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing the command line arguments: " + e.getMessage()); return; } if (cmdLine.hasOption('h')) { printHelp(options, System.out); System.exit(0); } String[] additionalArgs = cmdLine.getArgs(); if (additionalArgs.length != 2) { printHelp(options, System.err); System.exit(-1); } // ?? 1. ? 2.? File traceFile = new File(additionalArgs[0]); String slicingCriterionString = additionalArgs[1]; Long threadId = null; if (cmdLine.hasOption('t')) { // the interesting thread id for slicing try { threadId = Long.parseLong(cmdLine.getOptionValue('t')); } catch (NumberFormatException e) { System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t')); System.exit(-1); } } TraceResult trace; try { trace = TraceResult.readFrom(traceFile); } catch (IOException e) { System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e); System.exit(-1); return; } List<SlicingCriterion> sc = null; // a list contains the instruction's info corresponds to the slicing criterion //slicingCriterionString get from additionalArgs[1] try { sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses()); } catch (IllegalArgumentException e) { System.err.println("Error parsing slicing criterion: " + e.getMessage()); System.exit(-1); return; } List<ThreadId> threads = trace.getThreads(); // the threads that generate the traces if (threads.size() == 0) { System.err.println("The trace file contains no tracing information."); System.exit(-1); } // threadID is used to mark the interesting thread ThreadId tracing = null; for (ThreadId t : threads) { if (threadId == null) { if ("main".equals(t.getThreadName()) && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId())) tracing = t; } else if (t.getJavaThreadId() == threadId.longValue()) { tracing = t; } } if (tracing == null) { System.err.println(threadId == null ? "Couldn't find the main thread." : "The thread you specified was not found."); System.exit(-1); return; } long startTime = System.nanoTime(); Slicer slicer = new Slicer(trace); if (cmdLine.hasOption("progress")) // the parameter process indicates that we need to monitor the process of slicing slicer.addProgressMonitor(new ConsoleProgressMonitor()); boolean multithreaded; if (cmdLine.hasOption("multithreaded")) { String multithreadedStr = cmdLine.getOptionValue("multithreaded"); multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr)); } else { multithreaded = Runtime.getRuntime().availableProcessors() > 1; } boolean warnUntracedMethods = cmdLine.hasOption("warn-untraced"); // give some warns when encounters untraced functions //sliceInstructionCollector implements the interface slice visitor, which travel the dependence graph SliceInstructionsCollector collector = new SliceInstructionsCollector(); // the collector is used to collect the instructions in the dependence graph according to the slice criterion. slicer.addSliceVisitor(collector); // zhushi by yhb if (warnUntracedMethods) slicer.addUntracedCallVisitor(new PrintUniqueUntracedMethods()); // the user need the untraced function info, so add untraced call visitor slicer.process(tracing, sc, multithreaded); //----------------------the key process of slicing!!! Set<InstructionInstance> slice = collector.getDynamicSlice(); // return the slice result from the collector long endTime = System.nanoTime(); Instruction[] sliceArray = slice.toArray(new Instruction[slice.size()]); // convert the set to array Arrays.sort(sliceArray); // in order to ensure the sequence of dynamic execution // show the slicing result System.out.println("The dynamic slice for criterion " + sc + ":"); for (Instruction insn : sliceArray) { System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(), insn.getMethod().getName(), insn.getLineNumber(), insn.toString()); } System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceArray.length); System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime)); }
From source file:com.sociesc.findasmartphonespark.Main.java
public static void main(String[] args) { String apiPrefix = "api/v1/"; //setIpAddress("192.168.56.1"); setPort(9010);//from w w w . j av a 2 s . com try { Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados"); DatabaseUtils.seedDatabase(); } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } Dao<User> userDao = new Dao(User.class); get(apiPrefix + "/hello/:name", (request, response) -> { ObjectMapper objectMapper = new ObjectMapper(); /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>(); for (int i = 0; i < 10; i++) { AccessPoint ap = new AccessPoint(); ap.setBSSID("AP" + i); ap.setSSID("00:00:00:0" + i); ap.setRSSI(-50 + i); ap.setSala("Sala" + i); arrayAp.add(ap); //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI()); } String retornoJson = rwJson.writeJson(arrayAp);*/ //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol"))); ArrayList<AccessPoint> arrayAp = null; try { arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return arrayAp.get(0).getBSSID(); //return "Hello: " + request.params(":name"); //return arrayAp[0].get; }); post(apiPrefix + "/findUser/:data", (request, response) -> { String userId = request.params(":data"); ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString()); /*JsonObject json = new JsonObject(); try { json = JsonObject.readFrom(request.params(":data")); } catch (Exception ex) { System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); }*/ try { for (int i = 0; i < aps.size(); i++) { System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID() + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala()); } } catch (Exception ex) { System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); //json.add("error", ex.getMessage()); response.status(500); return ex.getMessage(); } return userId.toString(); }); /*post(apiPrefix + "/findUser/", (request, response) ->{ JsonObject json = new JsonObject(); // Informaes do roteador/AP String[] BSSID; // basic service set identifier - nome da conexo String[] SSID; // service set identifier - identificador nico da conexo int[] RSSI; // received signal strength indicator - potencia do sinal (-87 a -32) String sala; String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject wifiJson = reqJson.get("wifi").asObject(); System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size()); RSSI = new int[wifiJson.size()]; BSSID = new String[wifiJson.size()]; SSID = new String[wifiJson.size()]; try{ for (int i = 0; i < wifiJson.size(); i++) { // recebe informaes das conexes encontradas BSSID[i] = wifiJson.get("BSSID").asString(); SSID[i] = wifiJson.get("SSID").asString(); RSSI[i] = wifiJson.get("RSSI").asInt(); } return json.toString(); }catch(Exception ex){ System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); });*/ get(apiPrefix + "/users", (request, response) -> { JsonObject json = new JsonObject(); request.params(); try { List<User> users = userDao.findAll(); JsonArray usersJson = new JsonArray(); for (User u : users) { JsonObject uJson = new JsonObject(); uJson.add("id", u.getId()); uJson.add("name", u.getName()); uJson.add("email", u.getEmail()); usersJson.add(uJson); } json.add("users", usersJson); } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); /*get(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try{ User user = userDao.findById(userId); if(user == null){ json.add("error", "user not found"); response.status(404); return json.toString(); } JsonObject userJson = new JsonObject(); userJson.add("id", user.getId()); userJson.add("name", user.getName()); userJson.add("email", user.getEmail()); json.add("user", userJson); return json.toString(); }catch(Exception ex){ Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); });*/ delete(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try { userDao.removeById(userId); json.add("message", "user removed"); response.status(200); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); put(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try { String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject userJson = reqJson.get("user").asObject(); String name = userJson.get("name") != null ? userJson.get("name").asString() : null; String email = userJson.get("email") != null ? userJson.get("email").asString() : null; String password = userJson.get("password") != null ? userJson.get("password").asString() : null; User user = userDao.findById(userId); if (name != null) user.setName(name); if (email != null) user.setEmail(email); if (password != null) { String passwordDigest = DatabaseUtils.criptPass(password); user.setPasswordDigest(passwordDigest); } userDao.update(user); JsonObject resUserJson = new JsonObject(); resUserJson.add("id", user.getId()); resUserJson.add("name", user.getName()); resUserJson.add("email", user.getEmail()); json.add("user", resUserJson); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); post(apiPrefix + "/users", (request, response) -> { JsonObject json = new JsonObject(); try { String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject userJson = reqJson.get("user").asObject(); User user = new User(); user.setName(userJson.get("name").asString()); user.setEmail(userJson.get("email").asString()); user.setPasswordDigest(DatabaseUtils.criptPass("tempPass")); userDao.create(user); JsonObject resUserJson = new JsonObject(); resUserJson.add("id", user.getId()); resUserJson.add("name", user.getName()); resUserJson.add("email", user.getEmail()); resUserJson.add("passwordDigest", user.getPasswordDigest()); json.add("user", resUserJson); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); }
From source file:com.mgmtp.perfload.perfmon.PerfMon.java
public static void main(final String[] args) { CommandLine cmd = parseArgs(args);//from ww w . j a v a2 s. c o m if (cmd != null) { final Sigar sigar = new Sigar(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { sigar.close(); } }); if (cmd.hasOption('s')) { shutdown(sigar); return; } long interval = Long.parseLong(cmd.getOptionValue('i', "5")); String fileName = cmd.getOptionValue('f'); boolean java = cmd.hasOption('j'); boolean tcp = cmd.hasOption('t'); boolean netstat = cmd.hasOption('n'); OutputHandler outputHandler = fileName != null ? new FileOutputHandler(fileName) : new ConsoleOutputHandler(); try { outputHandler.open(); // Initialize Sigar libraries in order to fail fast. // Lazy initialization would cause perfMon to keep running logging errors all the time. // See https://github.com/mgm-tp/perfload/issues/3 Sigar.load(); SigarProxy sigarProxy = SigarProxyCache.newInstance(sigar); List<BasePerfMonCommand> commands = createCommandsList(java, tcp, netstat); final PerfMon perfMon = new PerfMon(sigarProxy, interval, commands, outputHandler); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { perfMon.runShutdownHook(); } }); perfMon.writeHeader(); perfMon.scheduleInformationGathering(); } catch (IOException ex) { LOG.error("Error opening output file: " + fileName, ex); } catch (SigarException ex) { LOG.error(ex.getMessage(), ex); } } }
From source file:com.splout.db.dnode.TCPStreamer.java
/** * This main method can be used for testing the TCP interface directly to a * local DNode. Will ask for protocol input from Stdin and print output to * Stdout// w w w. ja va 2 s. c om */ public static void main(String[] args) throws UnknownHostException, IOException, SerializationException { SploutConfiguration config = SploutConfiguration.get(); Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT)); DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); DataOutputStream outToServer = new DataOutputStream( new BufferedOutputStream(clientSocket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter tablespace: "); String tablespace = reader.readLine(); System.out.println("Enter version number: "); long versionNumber = Long.parseLong(reader.readLine()); System.out.println("Enter partition: "); int partition = Integer.parseInt(reader.readLine()); System.out.println("Enter query: "); String query = reader.readLine(); outToServer.writeUTF(tablespace); outToServer.writeLong(versionNumber); outToServer.writeInt(partition); outToServer.writeUTF(query); outToServer.flush(); byte[] buffer = new byte[0]; boolean read; do { read = false; int nBytes = inFromServer.readInt(); if (nBytes > 0) { buffer = new byte[nBytes]; int inRead = inFromServer.read(buffer); if (inRead > 0) { Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class); read = true; System.out.println(Arrays.toString(res)); } } } while (read); clientSocket.close(); }
From source file:com.yahoo.pulsar.testclient.PerformanceReader.java
public static void main(String[] args) throws Exception { final Arguments arguments = new Arguments(); JCommander jc = new JCommander(arguments); jc.setProgramName("pulsar-perf-reader"); try {// w ww . j av a 2s . c o m jc.parse(args); } catch (ParameterException e) { System.out.println(e.getMessage()); jc.usage(); System.exit(-1); } if (arguments.help) { jc.usage(); System.exit(-1); } if (arguments.topic.size() != 1) { System.out.println("Only one topic name is allowed"); jc.usage(); System.exit(-1); } if (arguments.confFile != null) { Properties prop = new Properties(System.getProperties()); prop.load(new FileInputStream(arguments.confFile)); if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("brokerServiceUrl"); } if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("webServiceUrl"); } // fallback to previous-version serviceUrl property to maintain backward-compatibility if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/"); } if (arguments.authPluginClassName == null) { arguments.authPluginClassName = prop.getProperty("authPlugin", null); } if (arguments.authParams == null) { arguments.authParams = prop.getProperty("authParams", null); } } // Dump config variables ObjectMapper m = new ObjectMapper(); ObjectWriter w = m.writerWithDefaultPrettyPrinter(); log.info("Starting Pulsar performance reader with config: {}", w.writeValueAsString(arguments)); final DestinationName prefixTopicName = DestinationName.get(arguments.topic.get(0)); final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null; ReaderListener listener = (reader, msg) -> { messagesReceived.increment(); bytesReceived.add(msg.getData().length); if (limiter != null) { limiter.acquire(); } }; EventLoopGroup eventLoopGroup; if (SystemUtils.IS_OS_LINUX) { eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new DefaultThreadFactory("pulsar-perf-reader")); } else { eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-reader")); } ClientConfiguration clientConf = new ClientConfiguration(); clientConf.setConnectionsPerBroker(arguments.maxConnections); clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS); if (isNotBlank(arguments.authPluginClassName)) { clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams); } PulsarClient pulsarClient = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup); List<CompletableFuture<Reader>> futures = Lists.newArrayList(); ReaderConfiguration readerConfig = new ReaderConfiguration(); readerConfig.setReaderListener(listener); readerConfig.setReceiverQueueSize(arguments.receiverQueueSize); MessageId startMessageId; if ("earliest".equals(arguments.startMessageId)) { startMessageId = MessageId.earliest; } else if ("latest".equals(arguments.startMessageId)) { startMessageId = MessageId.latest; } else { String[] parts = arguments.startMessageId.split(":"); startMessageId = new MessageIdImpl(Long.parseLong(parts[0]), Long.parseLong(parts[1]), -1); } for (int i = 0; i < arguments.numDestinations; i++) { final DestinationName destinationName = (arguments.numDestinations == 1) ? prefixTopicName : DestinationName.get(String.format("%s-%d", prefixTopicName, i)); futures.add(pulsarClient.createReaderAsync(destinationName.toString(), startMessageId, readerConfig)); } FutureUtil.waitForAll(futures).get(); log.info("Start reading from {} topics", arguments.numDestinations); long oldTime = System.nanoTime(); while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { break; } long now = System.nanoTime(); double elapsed = (now - oldTime) / 1e9; double rate = messagesReceived.sumThenReset() / elapsed; double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024; log.info("Read throughput: {} msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput)); oldTime = now; } pulsarClient.close(); }
From source file:org.objectrepository.MessageConsumerDaemon.java
/** * main//from w w w . j a va2s. c o m * <p/> * Accepts one folder as argument: -messageQueues * That folder ought to contain one or more folders ( or symbolic links ) to the files * The folder has the format: [foldername] or [foldername].[maxTasks] * MaxTasks is to indicate the total number of jobs being able to run. * * long * * @param argv */ public static void main(String[] argv) { if (instance == null) { final Properties properties = new Properties(); if (argv.length > 0) { for (int i = 0; i < argv.length; i += 2) { try { properties.put(argv[i], argv[i + 1]); } catch (ArrayIndexOutOfBoundsException arr) { System.out.println("Missing value after parameter " + argv[i]); System.exit(-1); } } } else { log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n" + "The queues is a folder that contains symbolic links to the startup scripts."); System.exit(-1); } if (log.isInfoEnabled()) { log.info("Arguments set: "); for (String key : properties.stringPropertyNames()) { log.info("'" + key + "'='" + properties.getProperty(key) + "'"); } } if (!properties.containsKey("-messageQueues")) { log.fatal("Expected case sensitive parameter: -messageQueues"); System.exit(-1); } final File messageQueues = new File((String) properties.get("-messageQueues")); if (!messageQueues.exists()) { log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath()); System.exit(-1); } if (messageQueues.isFile()) { log.fatal( "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath()); System.exit(-1); } long heartbeatInterval = 600000; if (properties.containsKey("-heartbeatInterval")) { heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval")); } String identifier = null; if (properties.containsKey("-id")) { identifier = (String) properties.get("-id"); } else if (properties.containsKey("-identifier")) { identifier = (String) properties.get("-identifier"); } final File[] files = messageQueues.listFiles(); final String[] scriptNames = (properties.containsKey("-startup")) ? new String[] { properties.getProperty("-startup") } : new String[] { "/startup.sh", "\\startup.bat" }; final List<Queue> queues = new ArrayList<Queue>(); for (File file : files) { final String name = file.getName(); final String[] split = name.split("\\.", 2); final String queueName = split[0]; for (String scriptName : scriptNames) { final String shellScript = file.getAbsolutePath() + scriptName; final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]); log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask); if (new File(shellScript).exists()) { final Queue queue = new Queue(queueName, shellScript, false); queue.setCorePoolSize(1); queue.setMaxPoolSize(maxTask); queue.setQueueCapacity(1); queues.add(queue); break; } else { log.warn("... skipping, because no startup script found at " + shellScript); } } } if (queues.size() == 0) { log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath()); System.exit(-1); } // Add the system queue queues.add(new Queue("Connection", null, true)); getInstance(queues, identifier, heartbeatInterval).run(); } System.exit(0); }
From source file:com.cloud.test.stress.TestClientWithAPI.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8092"; String devPort = "8080"; String apiUrl = "/client/api"; try {//from w w w.j a v a 2 s . co m // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-dp")) { devPort = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-a")) { accountName = iter.next(); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever // cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-u")) { numOfUsers = Integer.parseInt(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } if (arg.equals("-w")) { wait = Integer.parseInt(iter.next()); } if (arg.equals("-z")) { zoneId = iter.next(); } if (arg.equals("-snapshot")) { snapshot_test = "yes"; } if (arg.equals("-so")) { serviceOfferingId = iter.next(); } if (arg.equals("-do")) { diskOfferingId = iter.next(); } if (arg.equals("-no")) { networkOfferingId = iter.next(); } if (arg.equals("-pass")) { vmPassword = iter.next(); } if (arg.equals("-url")) { downloadUrl = iter.next(); } } final String server = host + ":" + port + "/"; final String developerServer = host + ":" + devPort + apiUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); if (numOfUsers > 0) { s_logger.info("Pre-generating users for test of size : " + numOfUsers); users = new String[numOfUsers]; Random ran = new Random(); for (int i = 0; i < numOfUsers; i++) { users[i] = Math.abs(ran.nextInt()) + "-user"; } } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { @Override public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); if (users != null) { username = users[Math.abs(ran.nextInt()) % numOfUsers]; } else { username = Math.abs(ran.nextInt()) + "-user"; } NDC.push(username); s_logger.info("Starting test for the user " + username); int response = executeDeployment(server, developerServer, username, snapshot_test); boolean success = false; String reason = null; if (response == 200) { success = true; if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 // seconds so // the windows VM // can boot up and do a sys prep. if (accountName == null) { s_logger.info("Begin Linux SSH test for account " + _account.get()); reason = sshTest(_linuxIP.get(), _linuxPassword.get(), snapshot_test); } if (reason == null) { s_logger.info( "Linux SSH test successful for account " + _account.get()); s_logger.info("Begin WindowsSSH test for account " + _account.get()); reason = sshTest(_linuxIP.get(), _linuxPassword.get(), snapshot_test); // reason = sshWinTest(_windowsIP.get()); } // release the linux IP now... _linuxIP.set(null); // release the Windows IP now _windowsIP.set(null); } // sleep for 3 min before getting the latest network stat // s_logger.info("Sleeping for 5 min before getting the lates network stat for the account"); // Thread.sleep(300000); // verify that network stat is correct for the user; if it's not - stop all the resources // for the user // if ((reason == null) && (getNetworkStat(server) == false) ) { // s_logger.error("Stopping all the resources for the account " + _account.get() + // " as network stat is incorrect"); // int stopResponseCode = executeStop( // server, developerServer, // username, false); // s_logger // .info("stop command finished with response code: " // + stopResponseCode); // success = false; // since the SSH test // // } else if (reason == null) { if (internet) { s_logger.info( "Windows SSH test successful for account " + _account.get()); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (usageIterator >= numThreads) { int eventsAndBillingResponseCode = executeEventsAndBilling(server, developerServer); s_logger.info( "events and usage records command finished with response code: " + eventsAndBillingResponseCode); usageIterator = 1; } else { s_logger.info( "Skipping events and usage records for this user: usageIterator " + usageIterator + " and number of Threads " + numThreads); usageIterator++; } if ((users == null) && (accountName == null)) { s_logger.info("Sending cleanup command"); int cleanupResponseCode = executeCleanup(server, developerServer, username); s_logger.info("cleanup command finished with response code: " + cleanupResponseCode); success = (cleanupResponseCode == 200); } else { s_logger.info("Sending stop DomR / destroy VM command"); int stopResponseCode = executeStop(server, developerServer, username, true); s_logger.info("stop(destroy) command finished with response code: " + stopResponseCode); success = (stopResponseCode == 200); } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("SSH test failed for account " + _account.get() + "with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username, false); s_logger.info( "stop command finished with response code: " + stopResponseCode); success = false; // since the SSH test // failed, mark the // whole test as // failure } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username, true); s_logger.info("stop command finished with response code: " + stopResponseCode); success = false; // since the deploy test // failed, mark the // whole test as failure } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); Thread.sleep(wait); } catch (Exception e) { s_logger.warn("Error in thread", e); try { int stopResponseCode = executeStop(server, developerServer, username, true); s_logger.info("stop response code: " + stopResponseCode); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:com.xn.interfacetest.service.impl.RelationSuitCaseServiceImpl.java
public static void main(String[] s) { Long a = 1L; String b = "1"; System.out.println(Long.parseLong(b) == a); }
From source file:esg.gateway.client.ESGAccessLogClient.java
public static void main(String[] args) { String serviceHost = null;/*w w w. j av a2 s .com*/ long startTime = 0; long endTime = Long.MAX_VALUE; try { serviceHost = args[0]; startTime = Long.parseLong(args[1]); endTime = Long.parseLong(args[2]); } catch (Throwable t) { log.error(t.getMessage()); } try { ESGAccessLogClient client = new ESGAccessLogClient(); if (client.setEndpoint(serviceHost).ping()) { List<String[]> results = null; results = client.fetchAccessLogData(startTime, endTime); System.out.println("---results:[" + (results.size() - 1) + "]---"); for (String[] record : results) { StringBuilder sb = new StringBuilder(); for (String column : record) { sb.append("[" + column + "] "); } System.out.println(sb.toString()); } } System.out.println("-----------------"); } catch (Throwable t) { log.error(t); t.printStackTrace(); } }