List of usage examples for java.net URL getHost
public String getHost()
From source file:com.ebay.spine.Launcher.java
public static void main(String[] args) throws Exception { // not using the default parsing for the hub. Creating a simple one from the default. GridHubConfiguration config = new GridHubConfiguration(); // adding the VNC capable servlet. List<String> servlets = new ArrayList<String>(); servlets.add("web.ConsoleVNC"); config.setServlets(servlets);/* w ww . j a va2 s . c om*/ // capabilities are dynamic for VMs. config.setThrowOnCapabilityNotPresent(false); // forcing the host from command line param as the hub gets confused by all the VMWare network interfaces. for (int i = 0; i < args.length; i++) { if (args[i].startsWith("hubhost=")) { config.setHost(args[i].replace("hubhost=", "")); } } Hub h = new Hub(config); h.start(); // and the nodes. // load the node templates. Map<String, JSONObject> templatesByNameMap = getTemplates("eugrid.json"); // get the template to use for each VM Map<String, String> vmsMapping = getVMtoTemplateMapping("nodes.properties"); // register each node using its template. for (String id : vmsMapping.keySet()) { String templateName = vmsMapping.get(id); JSONObject request = templatesByNameMap.get(templateName); request.getJSONObject("configuration").put("vm", id); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", "http://" + hub + "/grid/register/"); r.setEntity(new StringEntity(request.toString())); DefaultHttpClient client = new DefaultHttpClient(); URL hubURL = new URL("http://" + hub); HttpHost host = new HttpHost(hubURL.getHost(), hubURL.getPort()); HttpResponse response = client.execute(host, r); } }
From source file:GetURLParts.java
public static void main(String args[]) { try {/*from w w w .j av a 2s . c o m*/ URL u = new URL("http://www.java2s.com"); System.out.println("The URL is " + u); System.out.println("The protocol part is " + u.getProtocol()); System.out.println("The host part is " + u.getHost()); System.out.println("The port part is " + u.getPort()); System.out.println("The file part is " + u.getFile()); System.out.println("The ref part is " + u.getRef()); } // end try catch (MalformedURLException e) { System.err.println("not a URL I understand."); } }
From source file:com.xx_dev.speed_test.SpeedTestClient.java
public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); try {//from w ww . ja v a 2 s.c o m URL url = new URL(args[0]); boolean isSSL = false; String host = url.getHost(); int port = 80; if (StringUtils.equals(url.getProtocol(), "https")) { port = 443; isSSL = true; } if (url.getPort() > 0) { port = url.getPort(); } String path = url.getPath(); if (StringUtils.isNotBlank(url.getQuery())) { path += "?" + url.getQuery(); } PrintWriter resultPrintWriter = null; if (StringUtils.isNotBlank(args[1])) { String resultFile = args[1]; resultPrintWriter = new PrintWriter( new OutputStreamWriter(new FileOutputStream(resultFile, false), "UTF-8")); } Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .handler(new SpeedTestHttpClientChannelInitializer(isSSL, resultPrintWriter)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); //request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); if (resultPrintWriter != null) { resultPrintWriter.close(); } } catch (InterruptedException e) { logger.error(e.getMessage(), e); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } finally { group.shutdownGracefully(); } }
From source file:de.jwi.ftp.FTPUploader.java
public static void main(String[] args) throws Exception { URL url = new URL("ftp://ftp:none@localhost/tmp"); String protocol = url.getProtocol(); String host = url.getHost(); String userInfo = url.getUserInfo(); String path = url.getPath();// w ww . ja va 2s. c om String file = url.getFile(); File f = new File("D:/temp/out"); List l = new ArrayList(); l.add(f); String s = upload(url, l); System.out.println(s); int x = 5; }
From source file:Main.java
public static void main(String[] args) throws Exception { URL url = new URL(args[0]); System.out.println("URL is " + url.toString()); System.out.println("protocol is " + url.getProtocol()); System.out.println("authority is " + url.getAuthority()); System.out.println("file name is " + url.getFile()); System.out.println("host is " + url.getHost()); System.out.println("path is " + url.getPath()); System.out.println("port is " + url.getPort()); System.out.println("default port is " + url.getDefaultPort()); System.out.println("query is " + url.getQuery()); System.out.println("ref is " + url.getRef()); }
From source file:dk.qabi.imapfs.IMAPMount.java
public static void main(String[] args) throws MessagingException, MalformedURLException { if (args.length < 2) { System.out.println("[Error]: Must specify a mounting point"); System.out.println();// w w w . j a va2s . c om System.out.println("[Usage]: imapfsmnt <mounting point>"); System.exit(-1); } final String urlSpec = args[0]; final URL url = new URL(null, urlSpec, new IMAPStreamHandler()); final String mountpoint = args[1]; String[] fs_args = new String[4]; fs_args[0] = "-f"; fs_args[1] = "-s"; fs_args[2] = mountpoint; fs_args[3] = "-ovolname=" + url.getHost() + ",fssubtype=7"; Filesystem imapfs = new LoggingFilesystem(new IMAPFileSystem(url), LogFactory.getLog("dk.qabi.imapfs")); File m = new File(mountpoint); if (!m.exists()) m.mkdirs(); try { FuseMount.mount(fs_args, imapfs); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.hortonworks.registries.storage.tool.sql.TablesInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH) .desc("Root directory of script path").build()); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH) .desc("Mysql client jar url to download").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CREATE.toString()) .desc("Run sql migrations from scatch").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.DROP.toString()) .desc("Drop all the tables in the target database").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CHECK_CONNECTION.toString()) .desc("Check the connection for configured data source").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.MIGRATE.toString()) .desc("Execute schema migration from last check point").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.INFO.toString()) .desc("Show the status of the schema migration compared to the target database").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.VALIDATE.toString()) .desc("Validate the target database changes with the migration scripts").build()); options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.REPAIR.toString()).desc( "Repairs the DATABASE_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script") .build());/*from ww w. j ava 2 s .co m*/ options.addOption(Option.builder().hasArg(false).longOpt(DISABLE_VALIDATE_ON_MIGRATE) .desc("Disable flyway validation checks while running migrate").build()); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) { usage(options); System.exit(1); } boolean isSchemaMigrationOptionSpecified = false; SchemaMigrationOption schemaMigrationOptionSpecified = null; for (SchemaMigrationOption schemaMigrationOption : SchemaMigrationOption.values()) { if (commandLine.hasOption(schemaMigrationOption.toString())) { if (isSchemaMigrationOptionSpecified) { System.out.println( "Only one operation can be execute at once, please select one of 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection'."); System.exit(1); } isSchemaMigrationOptionSpecified = true; schemaMigrationOptionSpecified = schemaMigrationOption; } } if (!isSchemaMigrationOptionSpecified) { System.out.println( "One of the option 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection' must be specified to execute."); System.exit(1); } String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH); String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH); StorageProviderConfiguration storageProperties; Map<String, Object> conf; try { conf = Utils.readConfig(confFilePath); StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader(); storageProperties = confReader.readStorageConfig(conf); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } String bootstrapDirPath = null; try { bootstrapDirPath = System.getProperty("bootstrap.dir"); Proxy proxy = Proxy.NO_PROXY; String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL); String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME); String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD); if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) { URL url = new URL(httpProxyUrl); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort())); if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) { Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername, httpProxyPassword)); } } MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy); } catch (Exception e) { System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } boolean disableValidateOnMigrate = commandLine.hasOption(DISABLE_VALIDATE_ON_MIGRATE); if (disableValidateOnMigrate) { System.out.println("Disabling validation on schema migrate"); } SchemaMigrationHelper schemaMigrationHelper = new SchemaMigrationHelper( SchemaFlywayFactory.get(storageProperties, scriptRootPath, !disableValidateOnMigrate)); try { schemaMigrationHelper.execute(schemaMigrationOptionSpecified); System.out .println(String.format("\"%s\" option successful", schemaMigrationOptionSpecified.toString())); } catch (Exception e) { System.err.println( String.format("\"%s\" option failed : %s", schemaMigrationOptionSpecified.toString(), e)); System.exit(1); } }
From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH) .desc("Mysql client jar url to download").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL) .desc("JDBC url to connect DBMS via admin.").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER) .desc("Admin user name: should be able to create and grant privileges.").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD) .desc("Admin user's password: should be able to create and grant privileges.").build()); options.addOption(// w w w .j av a 2 s . com Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build()); options.addOption( Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build()); options.addOption( Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build()); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL, OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD, OPTION_TARGET_DATABASE }; boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt)); if (optNotFound) { usage(options); System.exit(1); } String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH); Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine); if (!adminOptionsOptional.isPresent()) { usage(options); System.exit(1); } AdminOptions adminOptions = adminOptionsOptional.get(); Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine); if (!targetOptionsOptional.isPresent()) { usage(options); System.exit(1); } TargetOptions targetOptions = targetOptionsOptional.get(); DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl()); Map<String, Object> conf; try { conf = Utils.readConfig(confFilePath); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } String bootstrapDirPath = null; try { bootstrapDirPath = System.getProperty("bootstrap.dir"); Proxy proxy = Proxy.NO_PROXY; String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL); String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME); String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD); if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) { URL url = new URL(httpProxyUrl); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort())); if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) { Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername, httpProxyPassword)); } } StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get( adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(), adminOptions.getDatabaseType()); MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy); } catch (Exception e) { System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } try (Connection conn = getConnectionViaAdmin(adminOptions)) { DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn); UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn); String database = targetOptions.getDatabase(); String username = targetOptions.getUsername(); createDatabase(databaseCreator, database); createUser(targetOptions, userCreator, username); grantPrivileges(databaseCreator, database, username); } }
From source file:com.webkruscht.wmt.DownloadFiles.java
/** * @param args/*from www. ja v a 2 s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { WebmasterTools wmt; String filename; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String today = sdf.format(date); getProperties(); Options options = getOptions(args); try { wmt = new WebmasterTools(username, password); for (SitesEntry entry : wmt.getUserSites()) { // only process verified sites if (entry.getVerified()) { // get download paths for site JSONObject data = wmt.getDownloadList(entry); if (data != null) { for (String prop : props) { String path = (String) data.get("TOP_QUERIES"); path += "&prop=" + prop; URL url = new URL(entry.getTitle().getPlainText()); if (options.getStartdate() != null) { path += "&db=" + options.getStartdate(); path += "&de=" + options.getEnddate(); filename = String.format("%s-%s-%s-%s-%s.csv", url.getHost(), options.getStartdate(), options.getEnddate(), prop, "TopQueries"); } else { filename = String.format("%s-%s-%s-%s.csv", url.getHost(), today, prop, "TopQueries"); } OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(filePath + filename), "UTF-8"); wmt.downloadData(path, out); out.close(); } String path = (String) data.get("TOP_PAGES"); URL url = new URL(entry.getTitle().getPlainText()); filename = String.format("%s-%s-%s.csv", url.getHost(), today, "TopQueries"); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath + filename), "UTF-8"); wmt.downloadData(path, out); out.close(); } } } } catch (Exception e) { e.printStackTrace(); throw e; } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { ParserGetter kit = new ParserGetter(); HTMLEditorKit.Parser parser = kit.getParser(); URL u = new URL("http://www.java2s.com"); InputStream in = u.openStream(); InputStreamReader r = new InputStreamReader(in); String remoteFileName = u.getFile(); if (remoteFileName.endsWith("/")) { remoteFileName += "index.html"; }/*ww w . j a va 2 s . com*/ if (remoteFileName.startsWith("/")) { remoteFileName = remoteFileName.substring(1); } File localDirectory = new File(u.getHost()); while (remoteFileName.indexOf('/') > -1) { String part = remoteFileName.substring(0, remoteFileName.indexOf('/')); remoteFileName = remoteFileName.substring(remoteFileName.indexOf('/') + 1); localDirectory = new File(localDirectory, part); } if (localDirectory.mkdirs()) { File output = new File(localDirectory, remoteFileName); FileWriter out = new FileWriter(output); HTMLEditorKit.ParserCallback callback = new PageSaver(out, u); parser.parse(r, callback, false); } }