List of usage examples for java.net URL toString
public String toString()
From source file:de.alpharogroup.lang.ClassExtensions.java
/** * If the given class is in a JAR file than the jar path as String will be returned. * * @param clazz//w w w.j av a 2 s . co m * The class. * @return the jar path as String if the given class is in a JAR file. */ public static String getJarPath(final Class<?> clazz) { String jarPath = null; final String jarPathPrefix = "jar:"; final String jarPathFilePrefix = jarPathPrefix + "file:"; final String path = ClassExtensions.getPath(clazz); final URL classUrl = ClassExtensions.getResource(path); if (classUrl != null) { final String classUrlString = classUrl.toString(); if ((classUrlString.startsWith(jarPathPrefix) && (classUrlString.indexOf(path) > 0))) { jarPath = classUrlString.replace("!" + path, ""); if (jarPath.startsWith(jarPathFilePrefix)) { final int beginIndex = jarPathFilePrefix.length(); jarPath = jarPath.substring(beginIndex, jarPath.length()); } } } return jarPath; }
From source file:com.trsst.Common.java
public static Attributes getManifestAttributes() { Attributes result = null;// w w w . ja v a2s .c om Class<Common> clazz = Common.class; String className = clazz.getSimpleName() + ".class"; URL classPath = clazz.getResource(className); if (classPath == null || !classPath.toString().startsWith("jar")) { // Class not from JAR return null; } String classPathString = classPath.toString(); String manifestPath = classPathString.substring(0, classPathString.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; try { Manifest manifest = new Manifest(new URL(manifestPath).openStream()); result = manifest.getMainAttributes(); } catch (MalformedURLException e) { log.error("Could not locate manifest: " + manifestPath); } catch (IOException e) { log.error("Could not open manifest: " + manifestPath); } return result; }
From source file:org.kie.smoke.wb.util.RestUtil.java
public static <T, G> T getQuery(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user, String password, Map<String, String> queryParams, Class... responseTypes) { URIBuilder uriBuilder = null;/*w w w. j a va 2 s . co m*/ try { String uriStr = createBaseUriString(deploymentUrl, relativeUrl); uriBuilder = new URIBuilder(uriStr); } catch (URISyntaxException urise) { logAndFail("Invalid uri :" + deploymentUrl.toString(), urise); } for (Entry<String, String> paramEntry : queryParams.entrySet()) { uriBuilder.addParameter(paramEntry.getKey(), paramEntry.getValue()); } URI uri = null; String uriStr = null; try { uri = uriBuilder.build(); uriStr = uri.toString(); } catch (URISyntaxException urise) { logAndFail("Invalid uri!", urise); } ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes); // @formatter:off Request request = Request.Get(uri).addHeader(HttpHeaders.ACCEPT, mediaType.toString()) .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password)); // @formatter:off Response resp = null; try { logOp("GET", uriStr); resp = request.execute(); } catch (Exception e) { logAndFail("[GET] " + uriStr, e); } try { return resp.handleResponse(rh); } catch (Exception e) { logAndFail("Failed retrieving response from [GET] " + uriStr, e); } // never happens return null; }
From source file:org.kie.remote.tests.base.RestUtil.java
public static <T, G> T getQuery(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user, String password, Map<String, String> queryParams, Class... responseTypes) { URIBuilder uriBuilder = null;/* w w w. j a va2 s . c o m*/ try { String uriStr = createBaseUriString(deploymentUrl, relativeUrl); uriBuilder = new URIBuilder(uriStr); } catch (URISyntaxException urise) { failAndLog("Invalid uri :" + deploymentUrl.toString(), urise); } for (Entry<String, String> paramEntry : queryParams.entrySet()) { String param = paramEntry.getKey(); String value = paramEntry.getValue(); uriBuilder.addParameter(paramEntry.getKey(), paramEntry.getValue()); } URI uri = null; String uriStr = null; try { uri = uriBuilder.build(); uriStr = uri.toString(); } catch (URISyntaxException urise) { failAndLog("Invalid uri!", urise); } ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes); // @formatter:off Request request = Request.Get(uri).addHeader(HttpHeaders.ACCEPT, mediaType.toString()) .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password)); // @formatter:off Response resp = null; try { logOp("GET", uriStr); resp = request.execute(); } catch (Exception e) { failAndLog("[GET] " + uriStr, e); } try { return resp.handleResponse(rh); } catch (Exception e) { failAndLog("Failed retrieving response from [GET] " + uriStr, e); } // never happens return null; }
From source file:cascading.flow.hadoop.util.HadoopUtil.java
private static PlatformInfo getPlatformInfoInternal() { URL url = JobConf.class.getResource(JobConf.class.getSimpleName() + ".class"); if (url == null || !url.toString().startsWith("jar")) return new PlatformInfo("Hadoop", null, null); String path = url.toString(); String manifestPath = path.substring(0, path.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest;/*w w w .ja v a 2 s. c om*/ try { manifest = new Manifest(new URL(manifestPath).openStream()); } catch (IOException exception) { LOG.warn("unable to get manifest from {}", manifestPath, exception); return new PlatformInfo("Hadoop", null, null); } Attributes attributes = manifest.getAttributes("org/apache/hadoop"); if (attributes == null) { LOG.debug("unable to get Hadoop manifest attributes"); return new PlatformInfo("Hadoop", null, null); } String vendor = attributes.getValue("Implementation-Vendor"); String version = attributes.getValue("Implementation-Version"); return new PlatformInfo("Hadoop", vendor, version); }
From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceObjectProviderBase.java
private static boolean equals(URL aUrl1, URL aUrl2) { if (aUrl1 == aUrl2) { return true; }//from w w w . jav a2 s.c om if ((aUrl1 == null) || (aUrl2 == null)) { return false; } return aUrl1.toString().equals(aUrl2.toString()); }
From source file:com.bah.applefox.main.plugins.fulltextindex.FTLoader.java
/** This method is used to get the page source from the given URL * @param url - the url from which to get the contents * @return - the page contents/* www .j a v a 2s .c o m*/ */ private static String getPageContents(URL url) { String pageContents = ""; try { // Open the URL Connection URLConnection con = url.openConnection(); // Get the file path, and eliminate unreadable documents String filePath = url.toString(); // Reads content only if it is a valid format if (!(filePath.endsWith(".pdf") || filePath.endsWith(".doc") || filePath.endsWith(".jsp") || filePath.endsWith("rss") || filePath.endsWith(".css"))) { // Sets the connection timeout (in milliseconds) con.setConnectTimeout(1000); // Tries to match the character set of the Web Page String charset = "utf-8"; try { Matcher m = Pattern.compile("\\s+charset=([^\\s]+)\\s*").matcher(con.getContentType()); charset = m.matches() ? m.group(1) : "utf-8"; } catch (Exception e) { log.error("Page had no specified charset"); } // Reader derived from the URL Connection's input stream, with // the // given character set Reader r = new InputStreamReader(con.getInputStream(), charset); // String Buffer used to append each chunk of Web Page data StringBuffer buf = new StringBuffer(); // Tries to get an estimate of bytes available int BUFFER_SIZE = con.getInputStream().available(); // If BUFFER_SIZE is too small, increases the size if (BUFFER_SIZE <= 1000) { BUFFER_SIZE = 1000; } // Character array to hold each chunk of Web Page data char[] ch = new char[BUFFER_SIZE]; // Read the first chunk of Web Page data int len = r.read(ch); // Loops until end of the Web Page is reached while (len != -1) { // Appends the data chunk to the string buffer and gets the // next chunk buf.append(ch, 0, len); len = r.read(ch, 0, BUFFER_SIZE); } // Sets the pageContents to the newly created string pageContents = buf.toString(); } } catch (UnsupportedEncodingException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } // Assume the body contents are blank if the character encoding is // not supported pageContents = ""; } catch (IOException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } // Assume the body contents are blank if the Web Page could not be // accessed pageContents = ""; } return pageContents; }
From source file:org.wso2.am.integration.test.utils.http.HTTPSClientUtils.java
/** * do HTTP POST operation for the given URL * * @param url request URL//from ww w. j a v a 2 s . c om * @param headers headers to be send * @param urlParams parameter string to be sent as payload * @return org.wso2.carbon.automation.test.utils.http.client.HttpResponse * @throws IOException if connection issue occurred */ public static org.wso2.carbon.automation.test.utils.http.client.HttpResponse doPost(URL url, String urlParams, Map<String, String> headers) throws IOException { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); if (urlParams != null && urlParams.contains("=")) { String[] paramList = urlParams.split("&"); for (String pair : paramList) { if (pair.contains("=")) { String[] pairList = pair.split("="); String key = pairList[0]; String value = (pairList.length > 1) ? pairList[1] : ""; urlParameters.add(new BasicNameValuePair(key, URLDecoder.decode(value, "UTF-8"))); } } } return doPost(url.toString(), headers, urlParameters); }
From source file:io.fabric8.maven.core.util.KubernetesResourceUtil.java
public static void validateKubernetesMasterUrl(URL masterUrl) throws MojoExecutionException { if (masterUrl == null || Strings.isNullOrBlank(masterUrl.toString())) { throw new MojoExecutionException( "Cannot find Kubernetes master URL. Have you started a cluster via `mvn fabric8:cluster-start` or connected to a remote cluster via `kubectl`?"); }/* www. j ava2s . c o m*/ }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Gets the currently deployed war file name from the ServletContext. * @param context// w ww. j a v a 2 s . c om * @return */ public static String getWarName(ServletContext context) { String[] pathSegments = context.getRealPath("/WEB-INF/web.xml").split("/"); String warName = pathSegments[pathSegments.length - 3]; if (!warName.endsWith(".war")) { URL webXml = WarUtils.class.getClassLoader().getResource("/cadmium-version.properties"); if (webXml != null) { String urlString = webXml.toString().substring(0, webXml.toString().length() - "/WEB-INF/classes/cadmium-version.properties".length()); File warFile = null; if (webXml.getProtocol().equalsIgnoreCase("file")) { warFile = new File(urlString.substring(5)); } else if (webXml.getProtocol().equalsIgnoreCase("vfszip")) { warFile = new File(urlString.substring(7)); } else if (webXml.getProtocol().equalsIgnoreCase("vfsfile")) { warFile = new File(urlString.substring(8)); } else if (webXml.getProtocol().equalsIgnoreCase("vfs") && System.getProperty(JBOSS_7_DEPLOY_DIR) != null) { String path = urlString.substring("vfs:/".length()); String deployDir = System.getProperty(JBOSS_7_DEPLOY_DIR); warFile = new File(deployDir, path); } if (warFile != null) { warName = warFile.getName(); } } } return warName; }