List of usage examples for java.net InetAddress getLocalHost
public static InetAddress getLocalHost() throws UnknownHostException
From source file:simauthenticator.SimAuthenticator.java
/** * @param args the command line arguments *//*from w ww .j a va 2 s .co m*/ public static void main(String[] args) throws Exception { cliOpts = new Options(); cliOpts.addOption("U", "url", true, "Connection URL"); cliOpts.addOption("u", "user", true, "User name"); cliOpts.addOption("p", "password", true, "User password"); cliOpts.addOption("d", "domain", true, "Domain name"); cliOpts.addOption("v", "verbose", false, "Verbose output"); cliOpts.addOption("k", "keystore", true, "KeyStore path"); cliOpts.addOption("K", "keystorepass", true, "KeyStore password"); cliOpts.addOption("h", "help", false, "Print help info"); CommandLineParser clip = new GnuParser(); cmd = clip.parse(cliOpts, args); if (cmd.hasOption("help")) { help(); return; } else { boolean valid = init(args); if (!valid) { return; } } HttpClientContext clientContext = HttpClientContext.create(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] keystorePassword = passwk.toCharArray(); FileInputStream kfis = null; try { kfis = new FileInputStream(keyStorePath); ks.load(kfis, keystorePassword); } finally { if (kfis != null) { kfis.close(); } } SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext) .setSSLSocketFactory(sslsf).setUserAgent(userAgent); ; cookieStore = new BasicCookieStore(); /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details"); cookie.setVersion(0); cookie.setDomain(".astelit.ukr"); cookie.setPath("/"); cookieStore.addCookie(cookie);*/ CloseableHttpClient client = httpClientBuilder.build(); try { NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(), domain); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setCookieStore(cookieStore); HttpGet httpget = new HttpGet(eventUrl); if (verbose) { System.out.println("executing request " + httpget.getRequestLine()); } HttpResponse response = client.execute(httpget, context); HttpEntity entity = response.getEntity(); HttpPost httppost = new HttpPost(eventUrl); List<Cookie> cookies = cookieStore.getCookies(); if (verbose) { System.out.println("----------------------------------------------"); System.out.println(response.getStatusLine()); System.out.print("Initial set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("usernameInput", usern)); nvps.add(new BasicNameValuePair("passwordInput", passwu)); nvps.add(new BasicNameValuePair("domainInput", domain)); //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern)); //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu)); if (entity != null && verbose) { System.out.println("Responce content length: " + entity.getContentLength()); } //System.out.println(EntityUtils.toString(entity)); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse afterPostResponse = client.execute(httppost, context); HttpEntity afterPostEntity = afterPostResponse.getEntity(); cookies = cookieStore.getCookies(); if (entity != null && verbose) { System.out.println("----------------------------------------------"); System.out.println(afterPostResponse.getStatusLine()); System.out.println("Responce content length: " + afterPostEntity.getContentLength()); System.out.print("After POST set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } System.out.println(EntityUtils.toString(afterPostEntity)); EntityUtils.consume(entity); EntityUtils.consume(afterPostEntity); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.netscape.cmstools.OCSPClient.java
public static void main(String args[]) throws Exception { Options options = createOptions();//from www. j a v a 2 s. c om CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String hostname = cmd.getOptionValue("h", InetAddress.getLocalHost().getCanonicalHostName()); int port = Integer.parseInt(cmd.getOptionValue("p", "8080")); String path = cmd.getOptionValue("t", "/ocsp/ee/ocsp"); String caNickname = cmd.getOptionValue("c", "CA Signing Certificate"); int times = Integer.parseInt(cmd.getOptionValue("n", "1")); String input = cmd.getOptionValue("input"); String serial = cmd.getOptionValue("serial"); String output = cmd.getOptionValue("output"); if (times < 1) { printError("Invalid number of submissions"); System.exit(1); } try { if (verbose) System.out.println("Initializing security database"); CryptoManager.initialize(databaseDir); String url = "http://" + hostname + ":" + port + path; OCSPProcessor processor = new OCSPProcessor(); processor.setVerbose(verbose); OCSPRequest request; if (serial != null) { if (verbose) System.out.println("Creating request for serial number " + serial); BigInteger serialNumber = new BigInteger(serial); request = processor.createRequest(caNickname, serialNumber); } else if (input != null) { if (verbose) System.out.println("Loading request from " + input); try (FileInputStream in = new FileInputStream(input)) { byte[] data = new byte[in.available()]; in.read(data); request = processor.createRequest(data); } } else { throw new Exception("Missing serial number or input file."); } OCSPResponse response = null; for (int i = 0; i < times; i++) { if (verbose) System.out.println("Submitting OCSP request"); response = processor.submitRequest(url, request); ResponseBytes bytes = response.getResponseBytes(); BasicOCSPResponse basic = (BasicOCSPResponse) BasicOCSPResponse.getTemplate() .decode(new ByteArrayInputStream(bytes.getResponse().toByteArray())); ResponseData rd = basic.getResponseData(); for (int j = 0; j < rd.getResponseCount(); j++) { SingleResponse sr = rd.getResponseAt(j); if (sr == null) { throw new Exception("No OCSP Response data."); } System.out.println("CertID.serialNumber=" + sr.getCertID().getSerialNumber()); CertStatus status = sr.getCertStatus(); if (status instanceof GoodInfo) { System.out.println("CertStatus=Good"); } else if (status instanceof UnknownInfo) { System.out.println("CertStatus=Unknown"); } else if (status instanceof RevokedInfo) { System.out.println("CertStatus=Revoked"); } } } if (output != null) { if (verbose) System.out.println("Storing response into " + output); try (FileOutputStream out = new FileOutputStream(output)) { ByteArrayOutputStream os = new ByteArrayOutputStream(); response.encode(os); out.write(os.toByteArray()); } System.out.println("Success: Output " + output); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e); System.exit(1); } }
From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java
public static void main(String[] args) throws UnknownHostException, Exception { // MY CODE/*from w w w . j av a 2 s . co m*/ if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) { return; } ; // MY CODE -- END boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false, hidden = false; boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false, mlsd = 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; 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(); } // Always use binary transfer // 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("-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("-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("-t")) { mlst = true; minParams = 3; } 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("-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] { 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); } ftp.setListHiddenFiles(hidden); // suppress login details ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); 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); // MY CODE byte[] bytes = IOUtils.toByteArray(input); InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes)); // MY CODE -- END ftp.storeFile(remote, encrypted); input.close(); } else if (listFiles) { if (lenient) { FTPClientConfig config = new FTPClientConfig(); config.setLenientFutureDates(true); ftp.configure(config); } for (FTPFile f : ftp.listFiles(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlsd) { for (FTPFile f : ftp.mlistDir(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlst) { FTPFile f = ftp.mlistFile(remote); if (f != null) { System.out.println(f.toFormattedString()); } } else if (listNames) { for (String s : ftp.listNames(remote)) { System.out.println(s); } } 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 : ftp.getReplyStrings()) { // System.out.println(s); // } } else { System.out.println("Failed: " + ftp.getReplyString()); } } else { OutputStream output; output = new FileOutputStream(local); // MY CODE ByteArrayOutputStream remoteFile = new ByteArrayOutputStream(); //InputStream byteIn = new ByteArrayInputStream(buf); ftp.retrieveFile(remote, remoteFile); remoteFile.flush(); Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray()); if (opt.isPresent()) { output.write(opt.get()); } remoteFile.close(); // MY CODE -- END 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:com.yahoo.storm.yarn.MasterServer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { LOG.info("Starting the AM!!!!"); Options opts = new Options(); opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used " + "unless for testing purposes"); CommandLine cl = new GnuParser().parse(opts, args); ApplicationAttemptId appAttemptID;//from ww w . j av a 2 s . com Map<String, String> envs = System.getenv(); if (cl.hasOption("app_attempt_id")) { String appIdStr = cl.getOptionValue("app_attempt_id", ""); appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr); } else if (envs.containsKey(ApplicationConstants.Environment.CONTAINER_ID.name())) { ContainerId containerId = ConverterUtils .toContainerId(envs.get(ApplicationConstants.Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); LOG.info("appAttemptID from env:" + appAttemptID.toString()); } else { LOG.error("appAttemptID is not specified for storm master"); throw new Exception("appAttemptID is not specified for storm master"); } @SuppressWarnings("rawtypes") Map storm_conf = Config.readStormConfig(null); Util.rmNulls(storm_conf); YarnConfiguration hadoopConf = new YarnConfiguration(); final String host = InetAddress.getLocalHost().getHostName(); storm_conf.put("nimbus.host", host); StormAMRMClient rmClient = new StormAMRMClient(appAttemptID, storm_conf, hadoopConf); rmClient.init(hadoopConf); rmClient.start(); BlockingQueue<Container> launcherQueue = new LinkedBlockingQueue<Container>(); MasterServer server = new MasterServer(storm_conf, rmClient); try { final int port = Utils.getInt(storm_conf.get(Config.MASTER_THRIFT_PORT)); final String target = host + ":" + port; InetSocketAddress addr = NetUtils.createSocketAddr(target); RegisterApplicationMasterResponse resp = rmClient.registerApplicationMaster(addr.getHostName(), port, null); LOG.info("Got a registration response " + resp); LOG.info("Max Capability " + resp.getMaximumResourceCapability()); rmClient.setMaxResource(resp.getMaximumResourceCapability()); LOG.info("Starting HB thread"); server.initAndStartHeartbeat(rmClient, launcherQueue, (Integer) storm_conf.get(Config.MASTER_HEARTBEAT_INTERVAL_MILLIS)); LOG.info("Starting launcher"); initAndStartLauncher(rmClient, launcherQueue); rmClient.startAllSupervisors(); LOG.info("Starting Master Thrift Server"); server.serve(); LOG.info("StormAMRMClient::unregisterApplicationMaster"); rmClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "AllDone", null); } finally { if (server.isServing()) { LOG.info("Stop Master Thrift Server"); server.stop(); } LOG.info("Stop RM client"); rmClient.stop(); } System.exit(0); }
From source file:demo.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 ww . j a v a 2 s . co m 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]; System.out.println("protocal:" + protocol); } 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]); System.out.println("server:" + server); System.out.println("port:" + port); } if (username == null) { username = args[base++]; password = args[base++]; System.out.println("username:" + username); System.out.println("password:" + password); } 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 : 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: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 ww .j av a 2 s . co m 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:com.cws.esolutions.security.main.UserManagementUtility.java
public static final void main(final String[] args) { final String methodName = UserManagementUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {//from w w w . ja va 2s. c o m DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", (Object) args); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(UserManagementUtility.CNAME, options, true); return; } try { CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } if ((commandLine.hasOption("configFile")) && (!(StringUtils.isBlank(commandLine.getOptionValue("configFile"))))) { SecurityServiceInitializer.initializeService(commandLine.getOptionValue("configFile"), UserManagementUtility.LOG_CONFIG, true); } else { SecurityServiceInitializer.initializeService(UserManagementUtility.SEC_CONFIG, UserManagementUtility.LOG_CONFIG, true); } AccountControlResponse response = null; final UserAccount userAccount = new UserAccount(); final RequestHostInfo reqInfo = new RequestHostInfo(); final SecurityConfigurationData secConfigData = UserManagementUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); try { reqInfo.setHostAddress(InetAddress.getLocalHost().getHostAddress()); reqInfo.setHostName(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException uhx) { reqInfo.setHostAddress("127.0.0.1"); reqInfo.setHostName("localhost"); } if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RequestHostInfo reqInfo: {}", reqInfo); } AccountControlRequest request = new AccountControlRequest(); request.setApplicationId(secConfig.getApplicationId()); request.setApplicationName(secConfig.getApplicationName()); request.setHostInfo(reqInfo); request.setRequestor(secConfig.getSvcAccount()); if (DEBUG) { DEBUGGER.debug("AccountControlRequest request: {}", request); } if (commandLine.hasOption("search")) { if (StringUtils.isEmpty(commandLine.getOptionValue("search"))) { throw new ParseException("No entry option was provided. Cannot continue."); } userAccount.setEmailAddr(commandLine.getOptionValue("search")); if (DEBUG) { DEBUGGER.debug("UserAccount userAccount: {}", userAccount); } request.setUserAccount(userAccount); if (DEBUG) { DEBUGGER.debug("AccountControlRequest: {}", request); } response = processor.searchAccounts(request); } else if (commandLine.hasOption("load")) { if (StringUtils.isEmpty(commandLine.getOptionValue("load"))) { throw new ParseException("No entry option was provided. Cannot continue."); } userAccount.setGuid(commandLine.getOptionValue("load")); request.setUserAccount(userAccount); if (DEBUG) { DEBUGGER.debug("AccountControlRequest: {}", request); } response = processor.loadUserAccount(request); } if (DEBUG) { DEBUGGER.debug("AccountControlResponse response: {}", response); } if ((response != null) && (response.getRequestStatus() == SecurityRequestStatus.SUCCESS)) { UserAccount account = response.getUserAccount(); if (DEBUG) { DEBUGGER.debug("UserAccount: {}", account); } System.out.println(account); } } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.err.println("An error occurred during processing: " + ssx.getMessage()); } }
From source file:com.jivesoftware.os.amza.deployable.Main.java
public static void main(String[] args) throws Exception { try {// ww w. ja v a 2 s . c o m if (args.length == 0) { System.out.println("Usage:"); System.out.println(""); System.out.println( " java -jar amza.jar <hostName> (manual cluster discovery)"); System.out.println(" or "); System.out.println( " java -jar amza.jar <hostName> <clusterName> (manual cluster discovery)"); System.out.println(" or "); System.out.println( " java -jar amza.jar <hostName> <clusterName> <peers> (automatic cluster discovery)"); System.out.println(""); System.out.println("Overridable properties:"); System.out.println(""); System.out.println(" -Damza.logicalName=<logicalName>"); System.out.println(" -Dhost.datacenter=<datacenterId>"); System.out.println(" -Dhost.rack=<rackId>"); System.out.println(""); System.out.println(" -Damza.port=1175"); System.out.println(" (change the port used to interact with other nodes.) "); System.out.println(""); System.out.println(" -Damza.id=<writerId>"); System.out.println(" -Damza.working.dirs=<workingDirs>"); System.out.println(" -Damza.system.ring.size=<systemRingSize>"); System.out.println(" -Damza.leap.cache.max.capacity=1000000"); System.out.println(""); System.out.println(" Only applicable if you have specified a <clusterName>."); System.out.println(" -Damza.discovery.group=225.4.5.6"); System.out.println(" -Damza.discovery.port=1223"); System.out.println(""); System.out.println("Example:"); System.out.println("java -jar amza.jar " + InetAddress.getLocalHost().getHostName() + " dev"); System.out.println(""); System.exit(1); } else { new Main().run(args); } } catch (Exception x) { x.printStackTrace(); System.exit(1); } }
From source file:edu.berkeley.sparrow.examples.BBackend.java
public static void main(String[] args) throws IOException, TException { ipAddress = InetAddress.getLocalHost().toString(); OptionParser parser = new OptionParser(); parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class); parser.accepts("help", "print help statement"); OptionSet options = parser.parse(args); if (options.has("help")) { parser.printHelpOn(System.out); System.exit(-1);/*from w w w. ja va 2s.c o m*/ } // Logger configuration: log to the console BasicConfigurator.configure(); Configuration conf = new PropertiesConfiguration(); if (options.has("c")) { String configFile = (String) options.valueOf("c"); try { conf = new PropertiesConfiguration(configFile); } catch (ConfigurationException e) { } } // Start backend server LOG.setLevel(Level.toLevel(conf.getString(LOG_LEVEL, DEFAULT_LOG_LEVEL))); LOG.debug("debug logging on"); int listenPort = conf.getInt(LISTEN_PORT, DEFAULT_LISTEN_PORT); int nodeMonitorPort = conf.getInt(NODE_MONITOR_PORT, NodeMonitorThrift.DEFAULT_NM_THRIFT_PORT); batchingDelay = conf.getLong(BATCHING_DELAY, DEFAULT_BATCHING_DELAY); String nodeMonitorHost = conf.getString(NODE_MONITOR_HOST, DEFAULT_NODE_MONITOR_HOST); int workerThread = conf.getInt(WORKER_THREADS, DEFAULT_WORKER_THREADS); appClientAdress = InetAddress.getByName(conf.getString(APP_CLIENT_IP)); appClientPortNumber = conf.getInt(APP_CLIENT_PORT_NUMBER, DEFAULT_APP_CLIENT_PORT_NUMBER); executor = Executors.newFixedThreadPool(workerThread); // Starting logging of results resultLog = new SynchronizedWrite("ResultsBackend.txt"); Thread resultLogTh = new Thread(resultLog); resultLogTh.start(); BBackend protoBackend = new BBackend(); BackendService.Processor<BackendService.Iface> processor = new BackendService.Processor<BackendService.Iface>( protoBackend); TServers.launchSingleThreadThriftServer(listenPort, processor); protoBackend.initialize(listenPort, nodeMonitorHost, nodeMonitorPort); }
From source file:Main.java
public static String getLocalhostAddress() throws UnknownHostException { InetAddress address = InetAddress.getLocalHost(); return address.getHostAddress().toString(); }