/** Check if an URL is relative to another URL. */ public static boolean relativeURL(URL url1, URL url2) { return ((url1.getProtocol() == null && url2.getProtocol() == null) || url1.getProtocol().equals(url2.getProtocol())) && ((url1.getAuthority() == null && url2.getAuthority() == null) || url1.getAuthority().equals(url2.getAuthority())) && ((url1.getPath() == null && url2.getPath() == null) || url2.getPath().startsWith(url1.getPath())); }
/** * Parse a repository document. * * @param url * @throws IOException * @throws XmlPullParserException * @throws Exception */ void parseDocument(URL url) throws IOException, XmlPullParserException, Exception { if (!visited.contains(url)) { visited.add(url); try { System.out.println("Visiting: " + url); InputStream in = null; if (url.getPath().endsWith(".zip")) { ZipInputStream zin = new ZipInputStream(url.openStream()); ZipEntry entry = zin.getNextEntry(); while (entry != null) { if (entry.getName().equals("repository.xml")) { in = zin; break; } entry = zin.getNextEntry(); } } else { in = url.openStream(); } Reader reader = new InputStreamReader(in); XmlPullParser parser = new KXmlParser(); parser.setInput(reader); parseRepository(parser); } catch (MalformedURLException e) { System.out.println("Cannot create connection to url"); } } }
/** * Gets the absolute path. * * @return the absolute path */ public String getAbsolutePath() { if (getFile() != null) { try { return XML.forwardSlash(getFile().getCanonicalPath()); } catch (IOException ex) { ex.printStackTrace(); } return getFile().getAbsolutePath(); } if (getURL() != null) { URL url = getURL(); String path = url.getPath(); // remove file protocol, if any if (path.startsWith("file:")) { // $NON-NLS-1$ path = path.substring(5); } // remove leading slash if drive is specified if (path.startsWith("/") && path.indexOf(":") > -1) { // $NON-NLS-1$ //$NON-NLS-2$ path = path.substring(1); } // replace "%20" with space int i = path.indexOf("%20"); // $NON-NLS-1$ while (i > -1) { String s = path.substring(0, i); path = s + " " + path.substring(i + 3); // $NON-NLS-1$ i = path.indexOf("%20"); // $NON-NLS-1$ } return path; } return null; }
public Set<String> listResources(String subdir) { try { Set<String> result = new HashSet<String>(); if (resourceURL != null) { String protocol = resourceURL.getProtocol(); if (protocol.equals("jar")) { String resPath = resourceURL.getPath(); int pling = resPath.lastIndexOf("!"); URL jarURL = new URL(resPath.substring(0, pling)); String resDirInJar = resPath.substring(pling + 2); String prefix = resDirInJar + subdir + "/"; // System.out.printf("BaseMod.listResources: looking for names starting with %s\n", // prefix); JarFile jar = new JarFile(new File(jarURL.toURI())); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(prefix) && !name.endsWith("/") && !name.contains("/.")) { // System.out.printf("BaseMod.listResources: name = %s\n", name); result.add(name.substring(prefix.length())); } } } else throw new RuntimeException("Resource URL protocol " + protocol + " not supported"); } return result; } catch (Exception e) { throw new RuntimeException(e); } }
/** * mapUrlToFileLocation() is the method used to resolve urls into file names. This maps a given * url to a file location, using the au top directory as the base. It creates directories which * mirror the html string, so 'http://www.journal.org/issue1/index.html' would be cached in the * file: <rootLocation>/www.journal.org/http/issue1/index.html * * @param rootLocation the top directory for ArchivalUnit this URL is in * @param urlStr the url to translate * @return the url file location * @throws java.net.MalformedURLException */ public static String mapUrlToFileLocation(String rootLocation, String urlStr) throws MalformedURLException { int totalLength = rootLocation.length() + urlStr.length(); URL url = new URL(urlStr); StringBuilder buffer = new StringBuilder(totalLength); buffer.append(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(url.getHost().toLowerCase()); int port = url.getPort(); if (port != -1) { buffer.append(PORT_SEPARATOR); buffer.append(port); } buffer.append(File.separator); buffer.append(url.getProtocol()); if (RepositoryManager.isEnableLongComponents()) { String escapedPath = escapePath( StringUtil.replaceString(url.getPath(), UrlUtil.URL_PATH_SEPARATOR, File.separator)); String query = url.getQuery(); if (query != null) { escapedPath = escapedPath + "?" + escapeQuery(query); } String encodedPath = RepositoryNodeImpl.encodeUrl(escapedPath); // encodeUrl strips leading / from path buffer.append(File.separator); buffer.append(encodedPath); } else { buffer.append( escapePath( StringUtil.replaceString(url.getPath(), UrlUtil.URL_PATH_SEPARATOR, File.separator))); String query = url.getQuery(); if (query != null) { buffer.append("?"); buffer.append(escapeQuery(query)); } } return buffer.toString(); }
public static void main(String[] args) throws IOException { URL url = new URL("http://www.javajeff.com/articles/articles/html"); System.out.println("Authority = " + url.getAuthority()); System.out.println("Default port = " + url.getDefaultPort()); System.out.println("File = " + url.getFile()); System.out.println("Host = " + url.getHost()); System.out.println("Path = " + url.getPath()); System.out.println("Port = " + url.getPort()); System.out.println("Protocol = " + url.getProtocol()); System.out.println("Query = " + url.getQuery()); System.out.println("Ref = " + url.getRef()); System.out.println("User Info = " + url.getUserInfo()); }
public static final File fileHandle(Value o) { String encoding = "UTF-8"; // always supported try { URL u = url(o); if (!"file".equals(u.getProtocol())) Procedure.throwPrimException(liMessage(IO.IOB, "notafileurl")); String path = URLDecoder.decode(u.getPath(), encoding); return new File(path); } catch (UnsupportedEncodingException use) { Procedure.throwPrimException(liMessage(IO.IOB, "unsupencoding", encoding)); return null; // not reached } }
/** * Resolve IGFS profiler logs directory. * * @param igfs IGFS instance to resolve logs dir for. * @return {@link Path} to log dir or {@code null} if not found. * @throws IgniteCheckedException if failed to resolve. */ public static Path resolveIgfsProfilerLogsDir(IgniteFileSystem igfs) throws IgniteCheckedException { String logsDir; if (igfs instanceof IgfsEx) logsDir = ((IgfsEx) igfs).clientLogDirectory(); else if (igfs == null) throw new IgniteCheckedException( "Failed to get profiler log folder (IGFS instance not found)"); else throw new IgniteCheckedException( "Failed to get profiler log folder (unexpected IGFS instance type)"); URL logsDirUrl = U.resolveIgniteUrl(logsDir != null ? logsDir : DFLT_IGFS_LOG_DIR); return logsDirUrl != null ? new File(logsDirUrl.getPath()).toPath() : null; }
void assertContents(String path, String pattern, boolean recurse, String member, boolean mustfind) throws IOException { Context context = new Context(null, getClass().getClassLoader(), 1, "src/test/osgi.jar"); Enumeration e = context.findEntries(path, "*.class", recurse); boolean found = false; while (e.hasMoreElements()) { URL url = (URL) e.nextElement(); if (url.getPath().endsWith(member)) { found = true; break; } } if (found == mustfind) return; if (mustfind) fail("No such member: " + member + " in " + pattern); else fail("Unexpected member: " + member + " in " + pattern); }
/** * Creates an instance bound to url. If <code>acceptDeflate</code> is true then HTTP Request * headers will indicate to servers that this client can accept compressed documents. * * @param urlString Connect to this URL. * @param acceptCompress true if this client will accept compressed responses * @throws FileNotFoundException thrown if <code>urlString</code> is not a valid URL, or a * filename which exists on the system. */ public DConnect2(String urlString, boolean acceptCompress) throws FileNotFoundException { int ceIndex = urlString.indexOf('?'); if (ceIndex != -1) { this.urlString = urlString.substring(0, ceIndex); String expr = urlString.substring(ceIndex); int selIndex = expr.indexOf('&'); if (selIndex != -1) { this.projString = expr.substring(0, selIndex); this.selString = expr.substring(selIndex); } else { this.projString = expr; this.selString = ""; } } else { this.urlString = urlString; this.projString = this.selString = ""; } this.acceptCompress = acceptCompress; // capture encoded url this.urlStringEncoded = EscapeStrings.escapeURL(this.urlString); // Check out the URL to see if it is file:// try { URL testURL = new URL(urlString); if ("file".equals(testURL.getProtocol())) { filePath = testURL.getPath(); // See if .dds and .dods files exist File f = new File(filePath + ".dds"); if (!f.canRead()) { throw new FileNotFoundException("file not readable: " + urlString + ".dds"); } f = new File(filePath + ".dods"); if (!f.canRead()) { throw new FileNotFoundException("file not readable: " + urlString + ".dods"); } } /* Set the server version cause we won't get it from anywhere */ ver = new ServerVersion(ServerVersion.DAP2_PROTOCOL_VERSION, ServerVersion.XDAP); } catch (DAP2Exception ex) { throw new FileNotFoundException("Cannot set server version"); } catch (MalformedURLException e) { throw new FileNotFoundException("Malformed URL: " + urlString); } }
/** * Decides if the given source is newer than a class. * * @param source the source we may want to compile * @param cls the former class * @return true if the source is newer, false else * @throws IOException if it is not possible to open an connection for the given source * @see #getTimeStamp(Class) */ protected boolean isSourceNewer(URL source, Class cls) throws IOException { long lastMod; // Special handling for file:// protocol, as getLastModified() often reports // incorrect results (-1) if (isFile(source)) { // Coerce the file URL to a File // See ClassNodeResolver.isSourceNewer for another method that replaces '|' with ':'. // WTF: Why is this done and where is it documented? String path = source.getPath().replace('/', File.separatorChar).replace('|', ':'); File file = new File(path); lastMod = file.lastModified(); } else { URLConnection conn = source.openConnection(); lastMod = conn.getLastModified(); conn.getInputStream().close(); } long classTime = getTimeStamp(cls); return classTime + config.getMinimumRecompilationInterval() < lastMod; }
public static URL adjustURLForHosting(URL url_in) { if (isHosting(url_in)) { String url = url_in.getProtocol() + "://"; if (bind_ip.length() < 7) { url += "127.0.0.1"; } else { url += bind_ip; } int port = url_in.getPort(); if (port != -1) { url += ":" + url_in.getPort(); } url += url_in.getPath(); String query = url_in.getQuery(); if (query != null) { url += "?" + query; } try { return (new URL(url)); } catch (MalformedURLException e) { Debug.printStackTrace(e); } } return (url_in); }
/** * Discover WS device on the local network with specified filter * * @param regexpProtocol url protocol matching regexp like "^http$", might be empty "" * @param regexpPath url path matching regexp like "onvif", might be empty "" * @return list of unique device urls filtered */ public static Collection<URL> discoverWsDevicesAsUrls(String regexpProtocol, String regexpPath) { final Collection<URL> urls = new TreeSet<>( new Comparator<URL>() { public int compare(URL o1, URL o2) { return o1.toString().compareTo(o2.toString()); } }); for (String key : discoverWsDevices()) { try { final URL url = new URL(key); boolean ok = true; if (regexpProtocol.length() > 0 && !url.getProtocol().matches(regexpProtocol)) ok = false; if (regexpPath.length() > 0 && !url.getPath().matches(regexpPath)) ok = false; if (ok) urls.add(url); } catch (MalformedURLException e) { e.printStackTrace(); } } return urls; }
/** * Get a file name from a URL. * * @param url The URL. * @param outputDirectoryName The output directory name. * @return The file name stripped of its original path with the specified output directory * attached. */ public static String getFileNameFromURL(URL url, String outputDirectoryName) { String hostName = url.getHost(); String path = url.getPath(); String baseName = ""; if (path.length() == 0) { if (hostName.length() == 0) { baseName = "adorned"; } else { baseName = hostName; } } else { if (hostName.length() == 0) { baseName = new File(path).getName(); } else { baseName = new File(hostName + "." + path).getName(); } } return new File(outputDirectoryName, baseName).getPath(); }
// TODO hhw 这个方法不太理解 public String getPathFromClass(Class cls) throws IOException { String path = null; if (cls == null) { throw new NullPointerException(); } URL url = getClassLocationURL(cls); if (url != null) { path = url.getPath(); if ("jar".equalsIgnoreCase(url.getProtocol())) { try { path = new URL(path).getPath(); } catch (MalformedURLException e) { } int location = path.indexOf("!/"); if (location != -1) { path = path.substring(0, location); } } File file = new File(path.replaceAll("%20", " ")); path = file.getCanonicalPath(); } return path; }