List of usage examples for java.net URL getHost
public String getHost()
From source file:com.k42b3.aletheia.protocol.http.Util.java
/** * This method takes an base url and resolves the href to an url * // w w w .j a va 2s . com * @param baseUrl * @param href * @return string * @throws MalformedURLException */ public static String resolveHref(String baseUrl, String href) throws MalformedURLException { URL currentUrl = new URL(baseUrl); if (href.startsWith("http://") || href.startsWith("https://")) { // we have an absolute url return href; } else if (href.startsWith("//")) { return currentUrl.getProtocol() + ":" + href; } else if (href.startsWith("?")) { return currentUrl.getProtocol() + "://" + currentUrl.getHost() + currentUrl.getPath() + href; } else { // we have an path wich must be resolved to the base url String completePath; if (href.startsWith("/")) { completePath = href; } else { int pos = currentUrl.getPath().lastIndexOf('/'); String path; if (pos != -1) { path = currentUrl.getPath().substring(0, pos); } else { path = currentUrl.getPath(); } completePath = path + "/" + href; } // remove dot segments from path String path = removeDotSegments(completePath); // build url String url = currentUrl.getProtocol() + "://" + currentUrl.getHost() + path; // add query params int sPos, ePos; sPos = href.indexOf('?'); if (sPos != -1) { String query; ePos = href.indexOf('#'); if (ePos == -1) { query = href.substring(sPos + 1); } else { query = href.substring(sPos + 1, ePos); } if (!query.isEmpty()) { url += "?" + query; } } // add fragment sPos = href.indexOf('#'); if (sPos != -1) { String fragment = href.substring(sPos + 1); if (!fragment.isEmpty()) { url += "#" + fragment; } } return url; } }
From source file:io.fabric8.apiman.ApimanStarter.java
private static URL waitForDependency(URL url, String path, String serviceName, String key, String value, String username, String password) throws InterruptedException { boolean isFoundRunningService = false; ObjectMapper mapper = new ObjectMapper(); int counter = 0; URL endpoint = null;//from w w w .j a v a2 s. c o m while (!isFoundRunningService) { endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort())); if (endpoint != null) { String isLive = null; try { URL statusURL = new URL(endpoint.toExternalForm() + path); HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection(); urlConnection.setConnectTimeout(500); if (urlConnection instanceof HttpsURLConnection) { try { KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH, ApimanStarter.TRUSTSTORE_PASSWORD_PATH); TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo); KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info( ApimanStarter.CLIENT_KEYSTORE_PATH, ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH); KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo); final SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kms, tms, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier()); httpsConnection.setSSLSocketFactory(socketFactory); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } if (Utils.isNotNullOrEmpty(username)) { String encoded = Base64.getEncoder() .encodeToString((username + ":" + password).getBytes("UTF-8")); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); log.info(username + ":" + "*****"); } isLive = IOUtils.toString(urlConnection.getInputStream()); Map<String, Object> esResponse = mapper.readValue(isLive, new TypeReference<Map<String, Object>>() { }); if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) { isFoundRunningService = true; } else { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. " + isLive); } } catch (Exception e) { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage()); } } else { if (counter % 10 == 0) log.info("Could not find " + serviceName + " in namespace, waiting.."); } counter++; Thread.sleep(1000l); } return endpoint; }
From source file:com.amazonaws.eclipse.core.regions.RegionUtils.java
/** * Searches through all known regions to find one with any service at the * specified endpoint. If no region is found with a service at that * endpoint, an exception is thrown./*from w w w . java2s . com*/ * * @param endpoint * The endpoint for any service residing in the desired region. * @return The region containing any service running at the specified * endpoint, otherwise an exception is thrown if no region is found * with a service at the specified endpoint. */ public static Region getRegionByEndpoint(String endpoint) { URL targetEndpointUrl = null; try { targetEndpointUrl = new URL(endpoint); } catch (MalformedURLException e) { throw new RuntimeException("Unable to parse service endpoint: " + e.getMessage()); } String targetHost = targetEndpointUrl.getHost(); for (Region region : getRegions()) { for (String serviceEndpoint : region.getServiceEndpoints().values()) { try { URL serviceEndpointUrl = new URL(serviceEndpoint); if (serviceEndpointUrl.getHost().equals(targetHost)) { return region; } } catch (MalformedURLException e) { Status status = new Status(Status.ERROR, AwsToolkitCore.PLUGIN_ID, "Unable to parse service endpoint: " + serviceEndpoint, e); StatusManager.getManager().handle(status, StatusManager.LOG); } } } throw new RuntimeException("No region found with any service for endpoint " + endpoint); }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
private static void setAuth(HttpClient client, String url, String username, String pw) throws MalformedURLException { URL u = new URL(url); if (username != null && pw != null) { Credentials defaultcreds = new UsernamePasswordCredentials(username, pw); client.getState().setCredentials(new AuthScope(u.getHost(), u.getPort()), defaultcreds); client.getParams().setAuthenticationPreemptive(true); // GS2 by // default // always // requires // authentication } else {//w ww .j av a2 s . c o m if (LOGGER.isDebugEnabled()) { LOGGER.debug("Not setting credentials to access to " + url); } } }
From source file:sce.RESTAppMetricJob.java
public static URL convertToURLEscapingIllegalCharacters(String string) { try {/* w w w . jav a 2 s .c o m*/ String decodedURL = URLDecoder.decode(string, "UTF-8"); URL url = new URL(decodedURL); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); return uri.toURL(); } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
From source file:com.eviware.soapui.support.Tools.java
public static String getEndpointFromUrl(URL baseUrl) { StringBuilder result = new StringBuilder(); result.append(baseUrl.getProtocol()).append("://"); result.append(baseUrl.getHost()); if (baseUrl.getPort() > 0) { result.append(':').append(baseUrl.getPort()); }//from www. ja va2 s .c om return result.toString(); }
From source file:com.liferay.ide.server.remote.RemoteLogStream.java
protected static InputStream openInputStream(IServerManagerConnection remote, URL url) throws IOException { String username = remote.getUsername(); String password = remote.getPassword(); String authString = username + ":" + password; //$NON-NLS-1$ byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); final IProxyService proxyService = LiferayCore.getProxyService(); URLConnection conn = null;/*from ww w . j a v a 2 s. c o m*/ try { URI uri = new URI("HTTP://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$ IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxyHost", data.getHost()); //$NON-NLS-1$ System.setProperty("http.proxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$ break; } } uri = new URI("SOCKS://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$ proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("socksProxyHost", data.getHost()); //$NON-NLS-1$ System.setProperty("socksProxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$ break; } } } catch (URISyntaxException e) { LiferayServerCore.logError("Could not read proxy data", e); //$NON-NLS-1$ } conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$ //$NON-NLS-2$ Authenticator.setDefault(null); conn.setAllowUserInteraction(false); return conn.getInputStream(); }
From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java
/** * Construct a full URL to the specified path given the URL * to some other resource in the bundle/*from ww w . ja va 2s . co m*/ * * @param url * @param path * @return locaion */ private static String[] getBundleLocation(URL url, String path) { String protocol = url.getProtocol(); String host = url.getHost(); String port = String.valueOf(url.getPort()); String urlString = protocol + "://" + host + ":" + port + "/" + path; return new String[] { urlString, null }; }
From source file:com.zimbra.cs.servlet.util.CsrfUtil.java
/** * * @param req// w w w .ja v a 2 s. c o m * @param allowedRefHost * @return * @throws MalformedURLException */ public static boolean isCsrfRequestBasedOnReferrer(final HttpServletRequest req, final String[] allowedRefHost) throws MalformedURLException { List<String> allowedRefHostList = Arrays.asList(allowedRefHost); boolean csrfReq = false; String method = req.getMethod(); if (!method.equalsIgnoreCase("POST")) { csrfReq = false; return csrfReq; } String host = getRequestHost(req); String referrer = req.getHeader(HttpHeaders.REFERER); String refHost = null; if (!StringUtil.isNullOrEmpty(referrer)) { URL refURL = null; if (referrer.contains("http") || referrer.contains("https")) { refURL = new URL(referrer); } else { refURL = new URL("http://" + referrer); } refHost = refURL.getHost().toLowerCase(); } if (refHost == null) { csrfReq = false; } else if (refHost.equalsIgnoreCase(host)) { csrfReq = false; } else { if (allowedRefHost != null && allowedRefHostList.contains(refHost)) { csrfReq = false; } else { csrfReq = true; } } if (ZimbraLog.soap.isDebugEnabled()) { ZimbraLog.soap.debug("Host : %s, Referrer host :%s, Allowed Hosts:[%s] Soap req is %s", host, refHost, Joiner.on(',').join(allowedRefHostList), (csrfReq ? " not allowed." : " allowed.")); } return csrfReq; }
From source file:io.seldon.importer.articles.FileItemAttributesImporter.java
/** * // w w w .ja v a 2 s .c o m * @param url The domain to extract the domain from. * @return The domain or UNKOWN_DOMAN if unable to use url. */ private static String getDomain(String url) { String retVal = "UNKOWN_DOMAN"; if (!url.startsWith("http") && !url.startsWith("https")) { url = "http://" + url; } URL netUrl = null; try { netUrl = new URL(url); } catch (MalformedURLException e) { logger.warn("Failed to get domain for " + url); } if (netUrl != null) { String host = netUrl.getHost(); retVal = host; } return retVal; }