List of usage examples for java.net URL getProtocol
public String getProtocol()
From source file:com.atinternet.tracker.Tool.java
/** * Get parameters//from w w w .j av a 2 s . c o m * * @param hit String * @return HashMap */ static LinkedHashMap<String, String> getParameters(String hit) { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); try { URL url = new URL(hit); map.put("ssl", url.getProtocol().equals("http") ? "Off" : "On"); map.put("log", url.getHost()); String[] queryComponents = url.getQuery().split("&"); for (String queryComponent : queryComponents) { String[] elem = queryComponent.split("="); if (elem.length > 1) { elem[1] = Tool.percentDecode(elem[1]); if (Tool.parseJSON(elem[1]) instanceof JSONObject) { JSONObject json = (JSONObject) Tool.parseJSON(elem[1]); if (json != null && elem[0].equals(Hit.HitParam.JSON.stringValue())) { map.put(elem[0], json.toString(3)); } else { map.put(elem[0], elem[1]); } } else { map.put(elem[0], elem[1]); } } else { map.put(elem[0], ""); } } } catch (Exception e) { e.printStackTrace(); } return map; }
From source file:Urls.java
public static String getNoRefForm(URL url) { String host = url.getHost();/*ww w.ja va 2s .co m*/ int port = url.getPort(); String portText = port == -1 ? "" : ":" + port; String userInfo = url.getUserInfo(); String userInfoText = userInfo == null || userInfo.length() == 0 ? "" : userInfo + "@"; String hostPort = host == null || host.length() == 0 ? "" : "//" + userInfoText + host + portText; return url.getProtocol() + ":" + hostPort + url.getFile(); }
From source file:org.dkpro.lab.Util.java
/** * Make the given URL available as a file. A temporary file is created and * deleted upon a regular shutdown of the JVM. If the parameter {@code * aCache} is {@code true}, the temporary file is remembered in a cache and * if a file is requested for the same URL at a later time, the same file is * returned again. If the previously created file has been deleted * meanwhile, it is recreated from the URL. * * @param aUrl//from w w w . j a v a 2s. c o m * the URL. * @param aCache * use the cache or not. * @return a file created from the given URL. * @throws IOException * if the URL cannot be accessed to (re)create the file. */ public static synchronized File getUrlAsFile(URL aUrl, boolean aCache) throws IOException { // If the URL already points to a file, there is not really much to do. if ("file".equals(aUrl.getProtocol())) { try { return new File(aUrl.toURI()); } catch (URISyntaxException e) { throw new IOException(e); } } // Lets see if we already have a file for this URL in our cache. Maybe // the file has been deleted meanwhile, so we also check if the file // actually still exists on disk. File file = urlFileCache.get(aUrl); if (!aCache || (file == null) || !file.exists()) { // Create a temporary file and try to preserve the file extension String suffix = ".temp"; String name = new File(aUrl.getPath()).getName(); int suffixSep = name.indexOf("."); if (suffixSep != -1) { suffix = name.substring(suffixSep + 1); name = name.substring(0, suffixSep); } // Get a temporary file which will be deleted when the JVM shuts // down. file = File.createTempFile(name, suffix); file.deleteOnExit(); // Now copy the file from the URL to the file. shoveAndClose(aUrl.openStream(), new FileOutputStream(file)); // Remember the file if (aCache) { urlFileCache.put(aUrl, file); } } return file; }
From source file:app.web.Application2ITCase.java
public static URL toLocationPath(String location) { try {//from w ww. j av a 2 s . c om URL fullUrl = new URL(location); // We just throw the query string if any return new URL(fullUrl.getProtocol(), fullUrl.getHost(), fullUrl.getPort(), fullUrl.getPath()); } catch (MalformedURLException e) { throw new RuntimeException(e); } }
From source file:com.evilisn.DAO.CertMapper.java
public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception { InputStream is = null;//from ww w . j a v a2 s . c om InputStream is_temp = null; try { if (uri == null) return null; URL url = uri.toURL(); if (bActiveCheckUnknownHost) { url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) port = url.getDefaultPort(); InetSocketAddress isa = new InetSocketAddress(host, port); if (isa.isUnresolved()) { //fix JNLP popup error issue throw new UnknownHostException("Host Unknown:" + isa.toString()); } } HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoInput(true); uc.setAllowUserInteraction(false); uc.setInstanceFollowRedirects(true); setTimeout(uc); String contentEncoding = uc.getContentEncoding(); int len = uc.getContentLength(); // is = uc.getInputStream(); if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) { is_temp = uc.getInputStream(); is = new GZIPInputStream(is_temp); } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) { is_temp = uc.getInputStream(); is = new InflaterInputStream(is_temp); } else { is = uc.getInputStream(); } if (len != -1) { int ch = 0, i = 0; byte[] res = new byte[len]; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); } return res; } else { ArrayList<byte[]> buffer = new ArrayList<byte[]>(); int buf_len = 1024; byte[] res = new byte[buf_len]; int ch = 0, i = 0; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); if (i == buf_len) { //rotate buffer.add(res); i = 0; res = new byte[buf_len]; } } int total_len = buffer.size() * buf_len + i; byte[] buf = new byte[total_len]; for (int j = 0; j < buffer.size(); j++) { System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len); } if (i > 0) { System.arraycopy(res, 0, buf, buffer.size() * buf_len, i); } return buf; } } catch (Exception e) { e.printStackTrace(); return null; } finally { closeInputStream(is_temp); closeInputStream(is); } }
From source file:jenkins.model.RunIdMigrator.java
private static String getUnmigrationCommandLine(File jenkinsHome) { StringBuilder cp = new StringBuilder(); for (Class<?> c : new Class<?>[] { RunIdMigrator.class, /* TODO how to calculate transitive dependencies automatically? */Charsets.class, WriterOutputStream.class, BuildException.class, FastDateFormat.class }) { URL location = c.getProtectionDomain().getCodeSource().getLocation(); String locationS = location.toString(); if (location.getProtocol().equals("file")) { try { locationS = new File(location.toURI()).getAbsolutePath(); } catch (URISyntaxException x) { // never mind }// w w w. java 2 s.co m } if (cp.length() > 0) { cp.append(File.pathSeparator); } cp.append(locationS); } return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome); }
From source file:Models.Geographic.Repository.RepositoryGoogle.java
/** * Method that geocoding a address from google api * @param country/* w w w.java 2 s . co m*/ * @param adm1 * @param adm2 * @param adm3 * @param local_area * @param locality * @param uncertainty * @return */ public static Location georenferencing(String country, String adm1, String adm2, String adm3, String local_area, String locality, double uncertainty) { Location a = null; String key; try { key = FixData.generateKey(new String[] { country, adm1, adm2, adm3, local_area, locality }); if (RepositoryGoogle.db == null) RepositoryGoogle.db = new HashMap(); if (RepositoryGoogle.db.containsKey(key)) return (Location) RepositoryGoogle.db.get(key); String data = (!locality.equals("") ? locality : "") + (!local_area.equals("") ? local_area + "+,+" : "") + (!adm3.equals("") ? adm3 + "+,+" : "") + (!adm2.equals("") ? adm2 + "+,+" : "") + (!adm1.equals("") ? adm1 + "+,+" : "") + (!country.equals("") ? country + "+,+" : ""); URL url = new URL(Configuration.getParameter("geocoding_google_url_send_xml") + "address=" + data.replace(" ", "%20").replace(".", "").replace(";", "")); URL file_url = new URL( url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery())); // Get information from URL DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Create a proxy to work in CIAT (erase this in another place) //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy2.ciat.cgiar.org", 8080)); DocumentBuilder db = dbf.newDocumentBuilder(); //Document doc = db.parse(file_url.openConnection(proxy).getInputStream()); Document doc = db.parse(file_url.openConnection().getInputStream()); // Document with data if (doc != null) { NodeList locationList = doc.getElementsByTagName("location"); NodeList locationTypeList = doc.getElementsByTagName("location_type"); NodeList viewPortList = doc.getElementsByTagName("viewport"); Node location = null, lat = null, lng = null; if (locationList.getLength() > 0) { for (int i = 0; i < locationList.getLength(); i++) { location = locationList.item(i); if (location.hasChildNodes()) { lat = location.getChildNodes().item(1); lng = location.getChildNodes().item(3); } } Node locationType = null; if (locationTypeList.getLength() > 0) { for (int i = 0; i < locationTypeList.getLength(); i++) locationType = locationTypeList.item(i); } Node viewPort = null, northeast = null, southwest = null, lat_northeast = null, lng_northeast = null, lat_southwest = null, lng_southwest = null; if (viewPortList.getLength() > 0) { for (int i = 0; i < viewPortList.getLength(); i++) { viewPort = viewPortList.item(i); if (viewPort.hasChildNodes()) { northeast = viewPort.getChildNodes().item(1); southwest = viewPort.getChildNodes().item(3); } /* Extract data from viewport field */ if (northeast.hasChildNodes()) { lat_northeast = northeast.getChildNodes().item(1); lng_northeast = northeast.getChildNodes().item(3); } if (southwest.hasChildNodes()) { lat_southwest = southwest.getChildNodes().item(1); lng_southwest = southwest.getChildNodes().item(3); } } } double[] coordValues = new double[] { Double.parseDouble(lat.getTextContent()), Double.parseDouble(lng.getTextContent()) }; double[] coordValuesNortheast = new double[] { Double.parseDouble(lat_northeast.getTextContent()), Double.parseDouble(lng_northeast.getTextContent()) }; double[] coordValuesSouthwest = new double[] { Double.parseDouble(lat_southwest.getTextContent()), Double.parseDouble(lng_southwest.getTextContent()) }; double distance = FixData.getDistance(coordValuesNortheast, coordValuesSouthwest); // Distance - km between Northeast and Southeast if (distance <= uncertainty) a = new Location(coordValues[0], coordValues[1], distance); else { RepositoryGoogle.db.put(key, a); throw new Exception("Exceede uncertainty. " + "Uncertainty: " + distance + " THRESHOLD: " + Configuration.getParameter("geocoding_threshold")); } } } RepositoryGoogle.db.put(key, a); } catch (NoSuchAlgorithmException | InvalidKeyException | URISyntaxException | IOException | ParserConfigurationException | SAXException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } return a; }
From source file:org.artifactory.util.HttpUtils.java
public static String adjustRefererValue(Map<String, String> headersMap, String headerVal) { //Append the artifactory user agent to the referer if (headerVal == null) { //Fallback to host headerVal = headersMap.get("HOST"); if (headerVal == null) { //Fallback to unknown headerVal = "UNKNOWN"; }//from w w w . j a v a 2 s .c o m } if (!headerVal.startsWith("http")) { headerVal = "http://" + headerVal; } try { java.net.URL uri = new java.net.URL(headerVal); //Only use the uri up to the path part headerVal = uri.getProtocol() + "://" + uri.getAuthority(); } catch (MalformedURLException e) { //Nothing } headerVal += "/" + HttpUtils.getArtifactoryUserAgent(); return headerVal; }
From source file:elaborate.util.StringUtil.java
/** * change ULRs in <code>textWithURLs</code> to links * /*w ww . ja v a 2s .co m*/ * @param textWithURLs * text with URLs * @return text with links */ public static String activateURLs(String textWithURLs) { StringTokenizer tokenizer = new StringTokenizer(textWithURLs, "<> ", true); StringBuilder replaced = new StringBuilder(textWithURLs.length()); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); // Log.info("token={}", token); try { URL url = new URL(token); // If possible then replace with anchor... String linktext = token; String file = url.getFile(); if (StringUtils.isNotBlank(file)) { linktext = file; } String protocol = url.getProtocol(); if (hostProtocols.contains(protocol)) { linktext = url.getHost() + linktext; } replaced.append("<a target=\"_blank\" href=\"" + url + "\">" + linktext + "</a>"); } catch (MalformedURLException e) { replaced.append(token); } } return replaced.toString(); }
From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java
/** * Find library file/directory from an element class. * @param aClass element class in target library * @return target file/directory, or {@code null} if not found * @throws IllegalArgumentException if some parameters were {@code null} *//*from w w w. j a v a 2 s .c o m*/ public static File findLibraryPathFromClass(Class<?> aClass) { if (aClass == null) { throw new IllegalArgumentException("aClass must not be null"); //$NON-NLS-1$ } int start = aClass.getName().lastIndexOf('.') + 1; String name = aClass.getName().substring(start); URL resource = aClass.getResource(name + ".class"); if (resource == null) { LOG.warn("Failed to locate the class file: {}", aClass.getName()); return null; } String protocol = resource.getProtocol(); if (protocol.equals("file")) { try { File file = new File(resource.toURI()); return toClassPathRoot(aClass, file); } catch (URISyntaxException e) { LOG.warn( MessageFormat.format( "Failed to locate the library path (cannot convert to local file): {0}", resource), e); return null; } } if (protocol.equals("jar")) { String path = resource.getPath(); return toClassPathRoot(aClass, path); } else { LOG.warn("Failed to locate the library path (unsupported protocol {}): {}", resource, aClass.getName()); return null; } }