List of usage examples for java.net URL getUserInfo
public String getUserInfo()
From source file:Main.java
public static void main(String args[]) throws Exception { URL u = new URL("http://www.java2s.com:80/index.html"); System.out.println("The URL is " + u); System.out.println("The user info is " + u.getUserInfo()); }
From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionTool.java
public static void main(String[] args) throws Exception { final Options options = new Options(); final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); @SuppressWarnings("unchecked") List<String> arguments = (List<String>) cmd.getArgList(); if (arguments.size() < 1) { usage(options, cmd);/*from www . j a v a 2s.co m*/ System.exit(1); } String urlString = arguments.remove(0).replaceFirst("vmware", "http"); // Internal trick to avoid confusions. URL url = new URL(urlString); // Parse vmware-config.xml and retrieve the credentials to avoid initialize Spring if (url.getUserInfo() == null) { File cfg = new File(ConfigFileConstants.getFilePathString(), "vmware-config.xml"); if (cfg.exists()) { String username = null; String password = null; VmwareConfig config = JaxbUtils.unmarshal(VmwareConfig.class, cfg); for (VmwareServer srv : config.getVmwareServerCollection()) { if (srv.getHostname().equals(url.getHost())) { username = srv.getUsername(); password = srv.getPassword(); } } if (username == null || password == null) { throw new IllegalArgumentException( "Can't retrieve credentials for " + url.getHost() + " from " + cfg); } int i = urlString.lastIndexOf("//"); if (i > 0) { urlString = urlString.substring(0, i + 2) + username + ':' + password + '@' + urlString.substring(i + 2); } url = new URL(urlString); } } VmwareRequisitionUrlConnection c = new VmwareRequisitionUrlConnection(url) { @Override protected Requisition getExistingRequisition() { // This is not elegant but it is necessary to avoid booting Spring File req = new File(ConfigFileConstants.getFilePathString(), "imports" + File.separator + m_foreignSource + ".xml"); if (req.exists()) { return JaxbUtils.unmarshal(Requisition.class, req); } return null; } }; c.connect(); InputStream is = c.getInputStream(); if (is == null) { System.err.println("Couldn't generate requisition from " + urlString); System.exit(1); } else { System.out.println(IOUtils.toString(is, "UTF-8")); } }
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();//from w w w .j a va2 s. c om String userInfo = url.getUserInfo(); String path = url.getPath(); 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:io.amient.kafka.metrics.DiscoveryTool.java
public static void main(String[] args) throws IOException { OptionParser parser = new OptionParser(); parser.accepts("help", "Print usage help"); OptionSpec<String> zookeeper = parser.accepts("zookeeper", "Address of the seed zookeeper server") .withRequiredArg().required(); OptionSpec<String> dashboard = parser .accepts("dashboard", "Grafana dashboard name to be used in all generated configs") .withRequiredArg().required(); OptionSpec<String> dashboardPath = parser .accepts("dashboard-path", "Grafana location, i.e. `./instance/.data/grafana/dashboards`") .withRequiredArg();/*w ww . ja v a 2 s .c o m*/ OptionSpec<String> topic = parser.accepts("topic", "Name of the metrics topic to consume measurements from") .withRequiredArg(); OptionSpec<String> influxdb = parser .accepts("influxdb", "InfluxDB connect URL (including user and password)").withRequiredArg(); OptionSpec<String> interval = parser.accepts("interval", "JMX scanning interval in seconds") .withRequiredArg().defaultsTo("10"); //TODO --influxdb-database (DEFAULT_DATABASE) //TODO --dashboard-datasource (DEFAULT_DATASOURCE) if (args.length == 0 || args[0] == "-h" || args[0] == "--help") { parser.printHelpOn(System.err); System.exit(0); } OptionSet opts = parser.parse(args); try { DiscoveryTool tool = new DiscoveryTool(opts.valueOf(zookeeper)); try { List<String> topics = tool.getKafkaTopics(); List<Broker> brokers = tool.getKafkaBrokers(); int interval_s = Integer.parseInt(opts.valueOf(interval)); if (opts.has(dashboard) && opts.has(dashboardPath)) { tool.generateDashboard(opts.valueOf(dashboard), brokers, topics, DEFAULT_DATASOURCE, opts.valueOf(dashboardPath), interval_s).save(); } if (opts.has(topic)) { //producer/reporter settings System.out.println("kafka.metrics.topic=" + opts.valueOf(topic)); System.out.println("kafka.metrics.polling.interval=" + interval_s + "s"); //TODO --producer-bootstrap for truly non-intrusive agent deployment, // i.e. when producing to a different cluster from the one being discovered System.out.println("kafka.metrics.bootstrap.servers=" + brokers.get(0).hostPort()); //consumer settings System.out.println("consumer.topic=" + opts.valueOf(topic)); System.out.println("consumer.zookeeper.connect=" + opts.valueOf(zookeeper)); System.out.println("consumer.group.id=kafka-metrics-" + opts.valueOf(dashboard)); } if (!opts.has(influxdb) || !opts.has(topic)) { tool.generateScannerConfig(brokers, opts.valueOf(dashboard), interval_s).list(System.out); } if (opts.has(influxdb)) { URL url = new URL(opts.valueOf(influxdb)); System.out.println("influxdb.database=" + DEFAULT_DATABASE); System.out.println("influxdb.url=" + url.toString()); if (url.getUserInfo() != null) { System.out.println("influxdb.username=" + url.getUserInfo().split(":")[0]); if (url.getUserInfo().contains(":")) { System.out.println("influxdb.password=" + url.getUserInfo().split(":")[1]); } } } System.out.flush(); } catch (IOException e) { e.printStackTrace(); System.exit(3); } finally { tool.close(); } } catch (Exception e) { e.printStackTrace(); System.exit(2); } }
From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java
public static void main(String[] args) { if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) { System.err.println("PokerFace requires at least Java v8 to run."); return;//from w w w . j a v a 2 s. c om } // Configure the command line options parser Options options = new Options(); options.addOption("h", false, "help"); options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https."); options.addOption("keystore", true, "Filepath for PokerFace certificate keystore."); options.addOption("storepass", true, "The store password of the keystore."); options.addOption("keypass", true, "The key password of the keystore."); options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target options.addOption("servercpu", true, "Number of cores the server should use."); options.addOption("targetcpu", true, "Number of cores the http targets should use."); options.addOption("trustany", false, "Ignore certificate identity errors from target servers."); options.addOption("files", true, "Filepath to a directory of static files."); options.addOption("config", true, "Path for XML Configuration file."); options.addOption("scripts", true, "Filepath for root scripts directory."); options.addOption("library", true, "JavaScript library to load into global context."); options.addOption("watch", false, "Dynamically watch scripts directory for changes."); options.addOption("dynamicTargetScripting", false, "WARNING! This option allows scripts to redirect requests to *any* other remote server."); CommandLine cmdLine = null; // parse the command line. try { CommandLineParser parser = new PosixParser(); cmdLine = parser.parse(options, args); if (args.length == 0 || cmdLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(PokerFaceApp.class.getSimpleName(), options); return; } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); return; } catch (Exception ex) { ex.printStackTrace(System.err); return; } XMLConfiguration config = new XMLConfiguration(); try { if (cmdLine.hasOption("config")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("config")); if (!Files.exists(tmp)) throw new FileNotFoundException("Configuration file does not exist."); if (Files.isDirectory(tmp)) throw new FileNotFoundException("'config' path is not a file."); // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it. config.setEntityResolver(new DefaultEntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { InputSource retVal = super.resolveEntity(publicId, systemId); if ((retVal == null) && (systemId != null)) { try { URL entityURL; if (systemId.endsWith("/PokerFace_v1Config.xsd")) entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd"); else entityURL = new URL(systemId); URLConnection connection = entityURL.openConnection(); connection.setUseCaches(false); InputStream stream = connection.getInputStream(); retVal = new InputSource(stream); retVal.setSystemId(entityURL.toExternalForm()); } catch (Throwable e) { return retVal; } } return retVal; } }); config.setSchemaValidation(true); config.setURL(tmp.toUri().toURL()); config.load(); if (cmdLine.hasOption("listen")) System.out.println("IGNORING 'listen' option because a configuration file was supplied."); if (cmdLine.hasOption("target")) System.out.println("IGNORING 'target' option(s) because a configuration file was supplied."); if (cmdLine.hasOption("scripts")) System.out.println("IGNORING 'scripts' option because a configuration file was supplied."); if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option(s) because a configuration file was supplied."); } else { String[] serverStrs; String[] addr = { null }; String[] port = { null }; serverStrs = cmdLine.getOptionValues("listen"); if (serverStrs == null) throw new MissingOptionException("No listening addresses specified specified"); for (int i = 0; i < serverStrs.length; i++) { String addrStr; String alias = null; String protocol = null; Boolean https = null; int addrPos = serverStrs[i].indexOf('='); if (addrPos >= 0) { if (addrPos < 2) throw new IllegalArgumentException("Invalid http argument."); else if (addrPos + 1 >= serverStrs[i].length()) throw new IllegalArgumentException("Invalid http argument."); addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length()); String[] types = serverStrs[i].substring(0, addrPos).split(","); for (String type : types) { if (type.equalsIgnoreCase("http")) break; else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure")) https = true; else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl")) protocol = type.toUpperCase(); else alias = type; } } else addrStr = serverStrs[i]; ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80); config.addProperty("server.listen(" + i + ")[@address]", addr[0]); config.addProperty("server.listen(" + i + ")[@port]", port[0]); if (alias != null) config.addProperty("server.listen(" + i + ")[@alias]", alias); if (protocol != null) config.addProperty("server.listen(" + i + ")[@protocol]", protocol); if (https != null) config.addProperty("server.listen(" + i + ")[@secure]", https); } String servercpu = cmdLine.getOptionValue("servercpu"); if (servercpu != null) config.setProperty("server[@cpu]", servercpu); String clientcpu = cmdLine.getOptionValue("targetcpu"); if (clientcpu != null) config.setProperty("targets[@cpu]", clientcpu); // Configure static files if (cmdLine.hasOption("files")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("files")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri()); } // Configure scripting if (cmdLine.hasOption("scripts")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri()); config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch")); String[] libraries = cmdLine.getOptionValues("library"); if (libraries != null) { for (int i = 0; i < libraries.length; i++) { Path lib = Utils.MakePath(libraries[i]); if (!Files.exists(lib)) throw new FileNotFoundException( "Script library does not exist [" + libraries[i] + "]."); if (Files.isDirectory(lib)) throw new FileNotFoundException( "Script library is not a file [" + libraries[i] + "]."); config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri()); } } } else if (cmdLine.hasOption("watch")) System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified."); else if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option as no 'scripts' directory was specified."); } String keyStorePath = cmdLine.getOptionValue("keystore"); if (keyStorePath != null) config.setProperty("keystore", keyStorePath); String keypass = cmdLine.getOptionValue("keypass"); if (keypass != null) config.setProperty("keypass", keypass); String storepass = cmdLine.getOptionValue("storepass"); if (storepass != null) config.setProperty("storepass", keypass); if (cmdLine.hasOption("trustany")) config.setProperty("targets[@trustAny]", true); config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting")); String[] targetStrs = cmdLine.getOptionValues("target"); if (targetStrs != null) { for (int i = 0; i < targetStrs.length; i++) { int uriPos = targetStrs[i].indexOf('='); if (uriPos < 2) throw new IllegalArgumentException("Invalid target argument."); else if (uriPos + 1 >= targetStrs[i].length()) throw new IllegalArgumentException("Invalid target argument."); String patternStr = targetStrs[i].substring(0, uriPos); String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length()); String alias; try { URL url = new URL(urlStr); alias = url.getUserInfo(); String scheme = url.getProtocol(); if ((!"http".equals(scheme)) && (!"https".equals(scheme))) throw new IllegalArgumentException("Invalid target uri scheme."); int port = url.getPort(); if (port < 0) port = url.getDefaultPort(); urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath(); String ref = url.getRef(); if (ref != null) urlStr += "#" + ref; } catch (MalformedURLException ex) { throw new IllegalArgumentException("Malformed target uri"); } config.addProperty("targets.target(" + i + ")[@pattern]", patternStr); config.addProperty("targets.target(" + i + ")[@url]", urlStr); if (alias != null) config.addProperty("targets.target(" + i + ")[@alias]", alias); } } // config.save(System.out); } catch (Throwable e) { e.printStackTrace(System.err); return; } // If we get here, we have a possibly valid configuration. try { final PokerFace p = new PokerFace(); p.config(config); if (p.start()) { PokerFace.Logger.warn("Started!"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { PokerFace.Logger.warn("Initiating shutdown..."); p.stop(); PokerFace.Logger.warn("Shutdown completed!"); } catch (Throwable e) { PokerFace.Logger.error("Failed to shutdown cleanly!"); e.printStackTrace(System.err); } } }); } else { PokerFace.Logger.error("Failed to start!"); System.exit(-1); } } catch (Throwable e) { e.printStackTrace(System.err); } }
From source file:Main.java
static void setBasicAuthentication(HttpURLConnection conn, URL url) { String userInfo = url.getUserInfo(); if (userInfo != null && userInfo.length() > 0) { String authString = Base64.encodeToString(userInfo.getBytes(), Base64.DEFAULT); conn.setRequestProperty("Authorization", "Basic " + authString); }/*from w w w .ja v a2s. c o m*/ }
From source file:Main.java
private static String escapeUrlString(String urlString) throws MalformedURLException, URISyntaxException { URL url = new URL(urlString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); return uri.toURL().toString(); }
From source file:uk.ac.ucl.cs.cmic.giftcloud.restserver.PasswordAuthenticationWrapper.java
static Optional<PasswordAuthentication> getPasswordAuthenticationFromURL(final URL url) { final String userInfo = url.getUserInfo(); if (null != userInfo) { final Matcher m = userInfoPattern.matcher(userInfo); if (m.matches()) { final PasswordAuthentication authenticator = new PasswordAuthentication(m.group(1), m.group(2).toCharArray()); return Optional.of(authenticator); }//from w w w . j a v a 2 s . c om } return Optional.empty(); }
From source file:Main.java
public static String encodeDocumentUrl(String urlString) { try {/*from w ww. j ava 2 s . com*/ URL url = new URL(urlString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); return uri.toASCIIString(); } catch (MalformedURLException e) { return null; } catch (URISyntaxException e) { return null; } }
From source file:org.fusesource.cloudmix.agent.security.SecurityUtils.java
/** * Get input stream for URL adding credentials if neccessary. * //from www . jav a 2 s . c o m * @param url * @return input stream for URL * @throws IOException */ public static InputStream getInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); String userInfo = url.getUserInfo(); if (userInfo != null && !"".equals(userInfo)) { conn.setRequestProperty("Authorization", getBasicAuthHeader(userInfo)); } return conn.getInputStream(); }