List of usage examples for java.net URL getProtocol
public String getProtocol()
From source file:Main.java
public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. // There may be more than one if a package is split over multiple jars/paths List<Class<?>> classes = new ArrayList<Class<?>>(); ArrayList<File> directories = new ArrayList<File>(); try {// ww w . j ava 2 s . c o m // Ask for all resources for the path final String packageUrl = iPackageName.replace('.', '/'); Enumeration<URL> resources = iClassLoader.getResources(packageUrl); if (!resources.hasMoreElements()) { resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION); if (resources.hasMoreElements()) { throw new IllegalArgumentException( iPackageName + " does not appear to be a valid package but a class"); } } else { while (resources.hasMoreElements()) { URL res = resources.nextElement(); if (res.getProtocol().equalsIgnoreCase("jar")) { JarURLConnection conn = (JarURLConnection) res.openConnection(); JarFile jar = conn.getJarFile(); for (JarEntry e : Collections.list(jar.entries())) { if (e.getName().startsWith(iPackageName.replace('.', '/')) && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) { String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6); classes.add(Class.forName(className)); } } } else directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8"))); } } } catch (NullPointerException x) { throw new ClassNotFoundException( iPackageName + " does not appear to be " + "a valid package (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)"); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying " + "to get all resources for " + iPackageName); } // For every directory identified capture all the .class files for (File directory : directories) { if (directory.exists()) { // Get the list of the files contained in the package File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { classes.addAll(findClasses(file, iPackageName)); } else { String className; if (file.getName().endsWith(CLASS_EXTENSION)) { className = file.getName().substring(0, file.getName().length() - CLASS_EXTENSION.length()); classes.add(Class.forName(iPackageName + '.' + className)); } } } } else { throw new ClassNotFoundException( iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package"); } } return classes; }
From source file:org.openremote.android.console.util.HTTPUtil.java
/** * Down load file and store it in local context. * // ww w . j a v a2s . c o m * @param serverUrl the current server url * @param fileName the file name for downloading * * @return the int */ private static int downLoadFile(Context context, String serverUrl, String fileName) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpClient client = new DefaultHttpClient(params); int statusCode = ControllerException.CONTROLLER_UNAVAILABLE; try { URL uri = new URL(serverUrl); if ("https".equals(uri.getProtocol())) { Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context), uri.getPort()); client.getConnectionManager().getSchemeRegistry().register(sch); } HttpGet get = new HttpGet(serverUrl); SecurityUtil.addCredentialToHttpRequest(context, get); HttpResponse response = client.execute(get); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == Constants.HTTP_SUCCESS) { FileOutputStream fOut = context.openFileOutput(fileName, Context.MODE_PRIVATE); InputStream is = response.getEntity().getContent(); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { fOut.write(buf, 0, len); } fOut.close(); is.close(); } } catch (MalformedURLException e) { Log.e("OpenRemote-HTTPUtil", "Create URL fail:" + serverUrl); } catch (IllegalArgumentException e) { Log.e("OpenRemote-IllegalArgumentException", "Download file " + fileName + " failed with URL: " + serverUrl, e); } catch (ClientProtocolException cpe) { Log.e("OpenRemote-ClientProtocolException", "Download file " + fileName + " failed with URL: " + serverUrl, cpe); } catch (IOException ioe) { Log.e("OpenRemote-IOException", "Download file " + fileName + " failed with URL: " + serverUrl, ioe); } return statusCode; }
From source file:org.commonjava.maven.galley.transport.htcli.internal.HttpListing.java
static boolean isSameServer(final URL url, final String linkHref) { String linkProtocol = null;/*from w ww . ja v a 2s.com*/ String linkAuthority = null; Logger logger = LoggerFactory.getLogger(HttpListing.class); try { URL linkUrl = new URL(linkHref); linkProtocol = linkUrl.getProtocol(); linkAuthority = linkUrl.getAuthority(); logger.debug("Absolute URL: {} is on the same server.", linkHref); } catch (MalformedURLException ex) { // linkHref is a relative path on the same server logger.debug("URL is relative, must be on the same server."); } boolean valid = (linkProtocol == null || linkProtocol.equals(url.getProtocol())) && (linkAuthority == null || linkAuthority.equals(url.getAuthority())); logger.debug("URL: {} has same protocol and authority? {}", linkHref, valid); return valid; }
From source file:at.beris.virtualfile.util.UrlUtils.java
/** * Masks sensitive information in an url (e.g. for logging) * * @param url//from w w w . j a v a 2 s . c om * @return */ public static String maskedUrlString(URL url) { StringBuilder stringBuilder = new StringBuilder(""); stringBuilder.append(url.getProtocol()); stringBuilder.append(':'); if (!url.getProtocol().toLowerCase().equals("file")) stringBuilder.append("//"); String authority = url.getAuthority(); if (!StringUtils.isEmpty(authority)) { String[] authorityParts = authority.split("@"); if (authorityParts.length > 1) { String[] userInfoParts = authorityParts[0].split(":"); stringBuilder.append(userInfoParts[0]); if (userInfoParts.length > 1) { stringBuilder.append(":***"); } stringBuilder.append('@'); stringBuilder.append(authorityParts[1]); } else { stringBuilder.append(authorityParts[0]); } } stringBuilder.append(url.getPath()); return stringBuilder.toString(); }
From source file:de.fhg.iais.asc.xslt.binaries.download.Downloader.java
private static URI createURI(URL url) throws URISyntaxException { return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); }
From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java
public static String getApplicationId(HttpServletRequest request) throws MalformedURLException { StringBuffer appID = new StringBuffer(); URL url = new URL(request.getRequestURL().toString()); appID.append(url.getProtocol()).append("://").append(url.getHost()); /*if (! (url.getProtocol().equalsIgnoreCase("http") && (url.getPort() == 80 || url.getPort() <= 0)) || ! ( url.getProtocol().equalsIgnoreCase("https") && (url.getPort() == 443 || url.getPort() <= 0)) ) { appID.append(':').append(url.getPort()); }*//*from www .ja v a 2 s .c o m*/ if (url.getPort() > 0) { appID.append(':').append(url.getPort()); } return appID.toString(); }
From source file:org.silvertunnel.netlib.adapter.httpclient.HttpClientUtil.java
private static InputStream action_NOT_NEEDED(URL url) throws IOException { HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params); HttpGet req = new HttpGet(url.getPath()); log.info("executing request to " + target); HttpResponse rsp = httpclient.execute(target, req); HttpEntity entity = rsp.getEntity(); /*//from ww w. j a v a2 s .c om if (entity != null) { log.info(EntityUtils.toString(entity)); } */ return entity.getContent(); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources //TODO: httpclient.getConnectionManager().shutdown(); }
From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java
/** * ?GET??/* www .j av a2s. c o m*/ * * @param url * @return */ public static HttpGet getGetMethod(String url) { URI uri = null; try { URL _url = new URL(url); uri = new URI(_url.getProtocol(), _url.getHost(), _url.getPath(), _url.getQuery(), null); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpGet pmethod = new HttpGet(uri); // ?? pmethod.addHeader("Connection", "keep-alive"); pmethod.addHeader("Cache-Control", "max-age=0"); pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8"); return pmethod; }
From source file:com.adrguides.utils.HTTPUtils.java
public static InputStream openAddress(Context context, URL url) throws IOException { if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) { return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15 } else {/*from w w w . j av a 2 s .com*/ URLConnection urlconn = url.openConnection(); urlconn.setReadTimeout(10000 /* milliseconds */); urlconn.setConnectTimeout(15000 /* milliseconds */); urlconn.setAllowUserInteraction(false); urlconn.setDoInput(true); urlconn.setDoOutput(false); if (urlconn instanceof HttpURLConnection) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responsecode = connection.getResponseCode(); if (responsecode != HttpURLConnection.HTTP_OK) { throw new IOException("Http response code returned:" + responsecode); } } return urlconn.getInputStream(); } }
From source file:com.seajas.search.utilities.tags.URLTag.java
/** * Protect a given URL by starring out the password-portion. * //from w w w . j a va 2 s . c om * @param url * @return String */ public static String protectUrl(final String url) { try { URL actualUrl = new URL(url); return actualUrl.getProtocol() + "://" + (StringUtils.isEmpty(actualUrl.getUserInfo()) ? "" : "****@") + actualUrl.getHost() + (actualUrl.getPort() == -1 ? "" : ':' + actualUrl.getPort()) + actualUrl.getPath() + (StringUtils.isEmpty(actualUrl.getQuery()) ? "" : '?' + actualUrl.getQuery()); } catch (MalformedURLException e) { return url; } }