List of usage examples for java.net URL getProtocol
public String getProtocol()
From source file:eionet.cr.util.URLUtil.java
/** * * @param urlString/*from w ww.j av a 2 s .co m*/ * @return */ public static String normalizeUrl(String urlString) { // if given URL string is null, return it as it is if (urlString == null) { return urlString; } // we're going to need both the URL and URI wrappers URL url = null; URI uri = null; try { url = new URL(urlString.trim()); uri = url.toURI(); } catch (MalformedURLException e) { return urlString; } catch (URISyntaxException e) { return urlString; } // get all the various parts of this URL String protocol = url.getProtocol(); String userInfo = url.getUserInfo(); String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); String query = url.getQuery(); String reference = url.getRef(); // start building the result, processing each of the above-found URL parts StringBuilder result = new StringBuilder(); try { if (!StringUtils.isEmpty(protocol)) { result.append(decodeEncode(protocol.toLowerCase())).append("://"); } if (!StringUtils.isEmpty(userInfo)) { result.append(decodeEncode(userInfo, ":")).append("@"); } if (!StringUtils.isEmpty(host)) { result.append(decodeEncode(host.toLowerCase())); } if (port != -1 && port != 80) { result.append(":").append(port); } if (!StringUtils.isEmpty(path)) { result.append(normalizePath(path)); } if (!StringUtils.isEmpty(query)) { String normalizedQuery = normalizeQueryString(uri); if (!StringUtils.isBlank(normalizedQuery)) { result.append("?").append(normalizedQuery); } } if (!StringUtils.isEmpty(reference)) { result.append("#").append(decodeEncode(reference)); } } catch (UnsupportedEncodingException e) { throw new CRRuntimeException("Unsupported encoding: " + e.getMessage(), e); } return result.toString(); }
From source file:gate.util.Files.java
/** * Convert a file: URL to a <code>java.io.File</code>. First tries to parse * the URL's toExternalForm as a URI and create the File object from that * URI. If this fails, just uses the path part of the URL. This handles * URLs that contain spaces or other unusual characters, both as literals and * when encoded as (e.g.) %20.//from ww w . java 2 s.co m * * @exception IllegalArgumentException if the URL is not convertable into a * File. */ public static File fileFromURL(URL theURL) throws IllegalArgumentException { try { URI uri = new URI(theURL.toExternalForm()); return new File(uri); } catch (URISyntaxException use) { try { URI uri = new URI(theURL.getProtocol(), null, theURL.getPath(), null, null); return new File(uri); } catch (URISyntaxException use2) { throw new IllegalArgumentException("Cannot convert " + theURL + " to a file path"); } } }
From source file:com.microsoftopentechnologies.windowsazurestorage.WAStorageClient.java
/** * Generates SAS URL for blob in Azure storage account * * @param storageAccount/*ww w . j ava 2 s. c o m*/ * @param blobName * @param containerName container name * @return SAS URL * @throws Exception */ public static String generateSASURL(StorageAccountInfo storageAccount, String containerName, String blobName) throws Exception { String storageAccountName = storageAccount.getStorageAccName(); StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(storageAccountName, storageAccount.getStorageAccountKey()); URL blobURL = new URL(storageAccount.getBlobEndPointURL()); String saBlobURI = new StringBuilder().append(blobURL.getProtocol()).append("://") .append(storageAccountName).append(".").append(blobURL.getHost()).append("/").toString(); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(credentials, new URI(saBlobURI), new URI(getCustomURI(storageAccountName, QUEUE, saBlobURI)), new URI(getCustomURI(storageAccountName, TABLE, saBlobURI))); // Create the blob client. CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient(); CloudBlobContainer container = blobClient.getContainerReference(containerName); // At this point need to throw an error back since container itself did not exist. if (!container.exists()) { throw new Exception("WAStorageClient: generateSASURL: Container " + containerName + " does not exist in storage account " + storageAccountName); } CloudBlob blob = container.getBlockBlobReference(blobName); String sas = blob.generateSharedAccessSignature(generatePolicy(), null); return sas; }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
static public HttpURLConnection getHUC(String address) { HttpURLConnection http = null; Log.d(TAG, "getHUC for " + address); try {// ww w . j a va2 s . co m URL url = new URL(address); if (url.getProtocol().equalsIgnoreCase("https")) { Log.d(TAG, "getHUC https"); // only use trustAllHosts and DO_NOT_VERIFY in development process trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { Log.d(TAG, "getHUC http"); http = (HttpURLConnection) url.openConnection(); } } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, "getHUC return connection"); return http; }
From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java
public static URI URI(String urlString) { try {// w w w.j av a 2 s.c o m final URL url = new URL(urlString); return new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:ml.shifu.dtrain.DTrainRequestProcessor.java
/** * Find a jar that contains a class of the same name, if any. It will return a jar file, even if that is not the * first thing on the class path that has a class with the same name. * // ww w .j a va2s.com * @param myClass * the class to find * @return a jar file that contains the class, or null */ @SuppressWarnings("rawtypes") private static String findContainingJar(Class myClass) { ClassLoader loader = myClass.getClassLoader(); String classFile = myClass.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } // URLDecoder is a misnamed class, since it actually decodes // x-www-form-urlencoded MIME type rather than actual // URL encoding (which the file path has). Therefore it // would // decode +s to ' 's which is incorrect (spaces are actually // either unencoded or encoded as "%20"). Replace +s first, // so // that they are kept sacred during the decoding process. toReturn = toReturn.replaceAll("\\+", "%2B"); toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } else if ("file".equals(url.getProtocol())) { String toReturn = url.getPath(); toReturn = toReturn.replaceAll("\\+", "%2B"); toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:net.aepik.alasca.core.ldap.Schema.java
/** * Retourne l'ensemble des syntaxes connues, qui sont * contenues dans le package 'ldap.syntax'. * @return String[] L'ensemble des noms de classes de syntaxes. *//* w ww . j a v a2s .c o m*/ public static String[] getSyntaxes() { String[] result = null; try { String packageName = getSyntaxPackageName(); URL url = Schema.class.getResource("/" + packageName.replace('.', '/')); if (url == null) { return null; } if (url.getProtocol().equals("jar")) { Vector<String> vectTmp = new Vector<String>(); int index = url.getPath().indexOf('!'); String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8"); JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8")); if (path.charAt(0) == '/') { path = path.substring(1); } Enumeration<JarEntry> jarFiles = jarFile.entries(); while (jarFiles.hasMoreElements()) { JarEntry tmp = jarFiles.nextElement(); // // Pour chaque fichier dans le jar, on regarde si c'est un // fichier de classe Java. // if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class") && tmp.getName().startsWith(path)) { int i = tmp.getName().lastIndexOf('/'); String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6); vectTmp.add(classname); } } jarFile.close(); result = new String[vectTmp.size()]; for (int i = 0; i < vectTmp.size(); i++) { result[i] = vectTmp.elementAt(i); } } else if (url.getProtocol().equals("file")) { // // On cr le fichier associ pour parcourir son contenu. // En l'occurence, c'est un dossier. // File[] files = (new File(url.toURI())).listFiles(); // // On liste tous les fichiers qui sont dedans. // On les stocke dans un vecteur ... // Vector<File> vectTmp = new Vector<File>(); for (File f : files) { if (!f.isDirectory()) { vectTmp.add(f); } } // // ... pour ensuite les mettres dans le tableau de resultat. // result = new String[vectTmp.size()]; for (int i = 0; i < vectTmp.size(); i++) { String name = vectTmp.elementAt(i).getName(); int a = name.indexOf('.'); name = name.substring(0, a); result[i] = name; } } } catch (Exception e) { e.printStackTrace(); } if (result != null) { Arrays.sort(result); } return result; }
From source file:ml.shifu.guagua.yarn.GuaguaYarnClient.java
/** * Find a jar that contains a class of the same name, if any. It will return a jar file, even if that is not the * first thing on the class path that has a class with the same name. * /*from ww w.j a v a2s . c om*/ * @param my_class * the class to find. * @return a jar file that contains the class, or null. * @throws IOException * in case when read class file. */ private static String findContainingJar(Class<?> my_class) { ClassLoader loader = my_class.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration<?> itr = loader.getResources(class_file); itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } // URLDecoder is a misnamed class, since it actually decodes // x-www-form-urlencoded MIME type rather than actual // URL encoding (which the file path has). Therefore it would // decode +s to ' 's which is incorrect (spaces are actually // either unencoded or encoded as "%20"). Replace +s first, so // that they are kept sacred during the decoding process. toReturn = toReturn.replaceAll("\\+", "%2B"); toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:com.adito.reverseproxy.ReverseProxyMethodHandler.java
/** * Encodes a URL //from w w w .j a v a 2 s . c o m * @param location * @return */ public static final String encodeURL(String location) { try { URL url = new URL(location); StringBuffer buf = new StringBuffer(); buf.append(url.getProtocol()); buf.append("://"); if (!Util.isNullOrTrimmedBlank(url.getUserInfo())) { buf.append(DAVUtilities.encodeURIUserInfo(url.getUserInfo())); buf.append("@"); } buf.append(url.getHost()); if (url.getPort() != -1) { buf.append(":"); buf.append(url.getPort()); } if (!Util.isNullOrTrimmedBlank(url.getPath())) { buf.append(URLUTF8Encoder.encode(url.getPath(), false)); } if (!Util.isNullOrTrimmedBlank(url.getQuery())) { buf.append("?"); buf.append(encodeQuery(url.getQuery())); } return buf.toString(); } catch (MalformedURLException e) { int idx = location.indexOf('?'); if (idx > -1 && idx < location.length() - 1) { return URLUTF8Encoder.encode(location.substring(0, idx), false) + "?" + encodeQuery(location.substring(idx + 1)); } else return URLUTF8Encoder.encode(location, false); } }
From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java
/** * List directory contents for a resource folder. Not recursive. This is * basically a brute-force implementation. Works for regular files and also * JARs.//from www.j a va2s . c o m * * @author Greg Briggs * @param path Should end with "/", but not start with one. * @return Just the name of each member item, not the full paths. * @throws URISyntaxException * @throws IOException */ public static String[] getResourceListing(String path) throws URISyntaxException, IOException { URL dirURL = Utils.class.getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ return new File(dirURL.toURI()).list(); } if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ String me = Utils.class.getName().replace(".", "/") + ".class"; dirURL = Utils.class.getClassLoader().getResource(me); } if (dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ String parent = (new File(dirURL.toURI()).getParent()); return new File(parent + "/../../../../../../resources/" + path).list(); } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar Set<String> result = new HashSet<>(); //avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { //filter according to the path String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = entry.substring(0, checkSubdir); } result.add(entry); } } return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }