List of usage examples for java.net URL getHost
public String getHost()
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;//ww 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:com.sforce.dataset.DatasetUtilMain.java
public static void main(String[] args) { printBanner();//from w w w. j a v a2 s. com DatasetUtilParams params = new DatasetUtilParams(); if (args.length > 0) params.server = false; System.out.println(""); System.out.println("DatsetUtils called with {" + args.length + "} Params:"); for (int i = 0; i < args.length; i++) { if ((i & 1) == 0) { System.out.print("{" + args[i] + "}"); } else { if (i > 0 && args[i - 1].equalsIgnoreCase("--p")) System.out.println(":{*******}"); else System.out.println(":{" + args[i] + "}"); } if (i > 0 && args[i - 1].equalsIgnoreCase("--server")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("false")) params.server = false; else if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.server = true; } } System.out.println(""); if (!printlneula(params.server)) { System.out.println( "You do not have permission to use this software. Please delete it from this computer"); System.exit(-1); } String action = null; if (args.length >= 2) { for (int i = 1; i < args.length; i = i + 2) { if (args[i - 1].equalsIgnoreCase("--help") || args[i - 1].equalsIgnoreCase("-help") || args[i - 1].equalsIgnoreCase("help")) { printUsage(); } else if (args[i - 1].equalsIgnoreCase("--u")) { params.username = args[i]; } else if (args[i - 1].equalsIgnoreCase("--p")) { params.password = args[i]; } else if (args[i - 1].equalsIgnoreCase("--sessionId")) { params.sessionId = args[i]; } else if (args[i - 1].equalsIgnoreCase("--token")) { params.token = args[i]; } else if (args[i - 1].equalsIgnoreCase("--endpoint")) { params.endpoint = args[i]; } else if (args[i - 1].equalsIgnoreCase("--action")) { action = args[i]; } else if (args[i - 1].equalsIgnoreCase("--operation")) { if (args[i] != null) { if (args[i].equalsIgnoreCase("overwrite")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("upsert")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("append")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("delete")) { params.Operation = args[i]; } else { System.out.println("Invalid Operation {" + args[i] + "} Must be Overwrite or Upsert or Append or Delete"); System.exit(-1); } } } else if (args[i - 1].equalsIgnoreCase("--debug")) { params.debug = true; DatasetUtilConstants.debug = true; } else if (args[i - 1].equalsIgnoreCase("--ext")) { DatasetUtilConstants.ext = true; } else if (args[i - 1].equalsIgnoreCase("--inputFile")) { String tmp = args[i]; if (tmp != null) { File tempFile = new File(tmp); if (tempFile.exists()) { params.inputFile = tempFile.toString(); } else { System.out.println("File {" + args[i] + "} does not exist"); System.exit(-1); } } } else if (args[i - 1].equalsIgnoreCase("--dataset")) { params.dataset = args[i]; } else if (args[i - 1].equalsIgnoreCase("--datasetLabel")) { params.datasetLabel = args[i]; } else if (args[i - 1].equalsIgnoreCase("--app")) { params.app = args[i]; } else if (args[i - 1].equalsIgnoreCase("--useBulkAPI")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.useBulkAPI = true; } else if (args[i - 1].equalsIgnoreCase("--uploadFormat")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("csv")) params.uploadFormat = "csv"; else if (args[i] != null && args[i].trim().equalsIgnoreCase("binary")) params.uploadFormat = "binary"; } else if (args[i - 1].equalsIgnoreCase("--rowLimit")) { if (args[i] != null && !args[i].trim().isEmpty()) params.rowLimit = (new BigDecimal(args[i].trim())).intValue(); } else if (args[i - 1].equalsIgnoreCase("--rootObject")) { params.rootObject = args[i]; } else if (args[i - 1].equalsIgnoreCase("--fileEncoding")) { params.fileEncoding = args[i]; } else if (args[i - 1].equalsIgnoreCase("--server")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.server = true; else if (args[i] != null && args[i].trim().equalsIgnoreCase("false")) params.server = false; } else if (args[i - 1].equalsIgnoreCase("--codingErrorAction")) { if (args[i] != null) { if (args[i].equalsIgnoreCase("IGNORE")) { params.codingErrorAction = CodingErrorAction.IGNORE; } else if (args[i].equalsIgnoreCase("REPORT")) { params.codingErrorAction = CodingErrorAction.REPORT; } else if (args[i].equalsIgnoreCase("REPLACE")) { params.codingErrorAction = CodingErrorAction.REPLACE; } } } else { printUsage(); System.out.println("\nERROR: Invalid argument: " + args[i - 1]); System.exit(-1); } } //end for if (params.username != null) { if (params.endpoint == null || params.endpoint.isEmpty()) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } } } if (params.server) { System.out.println(); System.out.println("\n*******************************************************************************"); try { DatasetUtilServer datasetUtilServer = new DatasetUtilServer(); datasetUtilServer.init(args, true); } catch (Exception e) { e.printStackTrace(); } System.out.println("Server ended, exiting JVM....."); System.out.println("*******************************************************************************\n"); System.out.println("QUITAPP"); System.exit(0); } if (params.sessionId == null) { if (params.username == null || params.username.trim().isEmpty()) { params.username = getInputFromUser("Enter salesforce username: ", true, false); } if (params.username.equals("-1")) { params.sessionId = getInputFromUser("Enter salesforce sessionId: ", true, false); params.username = null; params.password = null; } else { if (params.password == null || params.password.trim().isEmpty()) { params.password = getInputFromUser("Enter salesforce password: ", true, true); } } } if (params.sessionId != null && !params.sessionId.isEmpty()) { while (params.endpoint == null || params.endpoint.trim().isEmpty()) { params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false); if (params.endpoint == null || params.endpoint.trim().isEmpty()) System.out.println("\nERROR: endpoint must be specified when sessionId is specified"); } while (params.endpoint.toLowerCase().contains("login.salesforce.com") || params.endpoint.toLowerCase().contains("test.salesforce.com") || params.endpoint.toLowerCase().contains("test") || params.endpoint.toLowerCase().contains("prod") || params.endpoint.toLowerCase().contains("sandbox")) { System.out.println("\nERROR: endpoint must be the actual serviceURL and not the login url"); params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false); } } else { if (params.endpoint == null || params.endpoint.isEmpty()) { params.endpoint = getInputFromUser("Enter salesforce instance url (default=prod): ", false, false); if (params.endpoint == null || params.endpoint.trim().isEmpty()) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } } } try { if (params.endpoint.equalsIgnoreCase("PROD") || params.endpoint.equalsIgnoreCase("PRODUCTION")) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } else if (params.endpoint.equalsIgnoreCase("TEST") || params.endpoint.equalsIgnoreCase("SANDBOX")) { params.endpoint = DatasetUtilConstants.defaultEndpoint.replace("login", "test"); } URL uri = new URL(params.endpoint); String protocol = uri.getProtocol(); String host = uri.getHost(); if (protocol == null || !protocol.equalsIgnoreCase("https")) { if (host == null || !(host.toLowerCase().endsWith("internal.salesforce.com") || host.toLowerCase().endsWith("localhost"))) { System.out.println("\nERROR: Invalid endpoint. UNSUPPORTED_CLIENT: HTTPS Required in endpoint"); System.exit(-1); } } if (uri.getPath() == null || uri.getPath().isEmpty() || uri.getPath().equals("/")) { uri = new URL(uri.getProtocol(), uri.getHost(), uri.getPort(), DatasetUtilConstants.defaultSoapEndPointPath); } params.endpoint = uri.toString(); } catch (MalformedURLException e) { e.printStackTrace(); System.out.println("\nERROR: endpoint is not a valid URL"); System.exit(-1); } PartnerConnection partnerConnection = null; if (params.username != null || params.sessionId != null) { try { partnerConnection = DatasetUtils.login(0, params.username, params.password, params.token, params.endpoint, params.sessionId, params.debug); } catch (ConnectionException e) { e.printStackTrace(); System.exit(-1); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(-1); } } if (args.length == 0 || action == null) { // System.out.println("\n*******************************************************************************"); //// FileListenerUtil.startAllListener(partnerConnection); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // } // System.out.println("*******************************************************************************\n"); // System.out.println(); // System.out.println("\n*******************************************************************************"); // try { // DatasetUtilServer datasetUtilServer = new DatasetUtilServer(); // datasetUtilServer.init(args, false); // } catch (Exception e) { // e.printStackTrace(); // } // System.out.println("*******************************************************************************\n"); // System.out.println(); while (true) { action = getActionFromUser(); if (action == null || action.isEmpty()) { System.exit(-1); } params = new DatasetUtilParams(); getRequiredParams(action, partnerConnection, params); @SuppressWarnings("unused") boolean status = doAction(action, partnerConnection, params); // if(status) // { // if(action.equalsIgnoreCase("load") && params.debug) // createListener(partnerConnection, params); // } } } else { doAction(action, partnerConnection, params); } }
From source file:Main.java
/** * Checks if URL needs Authentication by checking if the domain is bitbucket.org or * api.bitbucket.org.//w ww .j av a 2 s . c om */ public static Boolean urlNeedsAuthentication(URL url) { return "bitbucket.org".equals(url.getHost().toLowerCase()) || "api.bitbucket.org".equals(url.getHost().toLowerCase()); }
From source file:Main.java
/** * Test whether a {@link URL} is a Tor Hidden Service host name, also known * as an ".onion address".//from w ww. j a v a 2 s . com * * @return whether the host name is a Tor .onion address */ public static boolean isOnionAddress(URL url) { return url.getHost().endsWith(".onion"); }
From source file:bad.robot.http.apache.Coercions.java
public static HttpHost asHttpHost(URL url) { return new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); }
From source file:Main.java
public static boolean isPlaylistUrl(String url) { if (url == null) { return false; }/* w w w . j a v a 2 s . c om*/ try { URL _url = new URL(url); String host = _url.getHost(); if (host == null) { return false; } if (!host.contains("nicovideo.jp")) { return false; } String path = _url.getPath(); if (path == null) { return false; } return path.startsWith("/search") || path.startsWith("/mylist"); } catch (MalformedURLException e) { } return false; }
From source file:Main.java
public static boolean isGravatar(URL url) { if (url == null) { return false; }/*from w w w . j a v a 2s. c o m*/ return url.getHost().equals("gravatar.com") || url.getHost().endsWith(".gravatar.com"); }
From source file:Main.java
public static String getNoQueryUrl(String source) { String dest = null;//from ww w .jav a 2 s . com try { URL sUrl = new URL(source); URL dUrl = new URL(sUrl.getProtocol(), sUrl.getHost(), sUrl.getPort(), sUrl.getPath()); dest = dUrl.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } return dest; }
From source file:Main.java
public static String restoreAvatarUrl(String stringUrl) { try {//from ww w.java2 s. c om StringBuilder sb = new StringBuilder(); URL url = new URL(stringUrl); sb.append(url.getProtocol()).append("://").append(url.getHost()).append(url.getPath()); return sb.toString(); } catch (MalformedURLException e) { return stringUrl; } }
From source file:Main.java
public static String getHost(String urlString) { URL url; try {//from ww w. j a va 2s . c o m url = new URL(urlString); return url.getHost(); } catch (MalformedURLException e) { e.printStackTrace(); return ""; } }