List of usage examples for java.net URL toString
public String toString()
From source file:net.sf.eclipsefp.haskell.ui.internal.editors.haskell.HaskellTextHover.java
@SuppressWarnings("unchecked") public static String computeProblemInfo(final ITextViewer textViewer, final IRegion hoverRegion, final IAnnotationAccessExtension fMarkerAnnotationAccess) { if (textViewer instanceof ISourceViewer) { IAnnotationModel annotationModel = ((ISourceViewer) textViewer).getAnnotationModel(); if (annotationModel != null) { // collect all messages StringBuilder sb = new StringBuilder(); Iterator<Annotation> i = annotationModel.getAnnotationIterator(); while (i.hasNext()) { Annotation a = i.next(); String type = a.getType(); if (a.getText() != null && (fMarkerAnnotationAccess.isSubtype(type, ERROR_ANNOTATION_TYPE) || fMarkerAnnotationAccess.isSubtype(type, WARNING_ANNOTATION_TYPE) || fMarkerAnnotationAccess.isSubtype(type, SPELLING_ANNOTATION_TYPE))) { Position p = annotationModel.getPosition(a); if (p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { // add a nice icon String img = ""; String txt = toHTMLString(a.getText()); try { URL url = FileLocator.toFileURL(HaskellUIPlugin.getDefault().getBundle() .getResource(fMarkerAnnotationAccess.isSubtype(type, ERROR_ANNOTATION_TYPE) ? "icons/obj16/error_obj.gif" : "icons/obj16/warning_obj.gif")); img = "<img src=\"" + url.toString() + "\" style=\"vertical-align:-4;\"/>"; } catch (IOException ioe) { HaskellUIPlugin.log(ioe); }//w w w .j a v a 2s. co m String div = "<div style=\"font-family: verdana;padding:2px\">" + img + txt + "</div>"; // put errors first if (fMarkerAnnotationAccess.isSubtype(type, ERROR_ANNOTATION_TYPE)) { if (sb.length() > 0) { sb.insert(0, "<hr/>"); } sb.insert(0, div); } else { if (sb.length() > 0) { sb.append("<hr/>"); } sb.append(div); } } } } if (sb.length() > 0) { return sb.toString(); } } } return null; }
From source file:com.android.dumprendertree2.FsUtils.java
public static List<String> getLayoutTestsDirContents(String dirRelativePath, boolean recurse, boolean mode) { String modeString = (mode ? "folders" : "files"); URL url = null; try {/* w ww . ja va 2s . c om*/ url = new URL(SCRIPT_URL + "?path=" + dirRelativePath + "&recurse=" + recurse + "&mode=" + modeString); } catch (MalformedURLException e) { Log.e(LOG_TAG, "path=" + dirRelativePath + " recurse=" + recurse + " mode=" + modeString, e); return new LinkedList<String>(); } HttpGet httpRequest = new HttpGet(url.toString()); ResponseHandler<LinkedList<String>> handler = new ResponseHandler<LinkedList<String>>() { @Override public LinkedList<String> handleResponse(HttpResponse response) throws IOException { LinkedList<String> lines = new LinkedList<String>(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return lines; } HttpEntity entity = response.getEntity(); if (entity == null) { return lines; } BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; try { while ((line = reader.readLine()) != null) { lines.add(line); } } finally { if (reader != null) { reader.close(); } } return lines; } }; try { return getHttpClient().execute(httpRequest, handler); } catch (IOException e) { Log.e(LOG_TAG, "getLayoutTestsDirContents(): HTTP GET failed for URL " + url); return null; } }
From source file:com.snaplogic.snaps.checkfree.SoapExecuteTest.java
static String getContentFrom(URL fileUrl) { String templateText;//from w ww .ja v a2s.c o m try { URLConnection urlConnection = fileUrl.openConnection(); if (urlConnection == null) { throw new ExecutionException(ERR_URL_CONNECT).formatWith(fileUrl.toString()) .withReason(REASON_URL_CONNECT).withResolution(RESOLUTION_URL_CONNECT); } urlConnection.connect(); try (final InputStream in = urlConnection.getInputStream()) { templateText = IOUtils.toString(in); if (StringUtils.isBlank(templateText)) { throw new ExecutionException(TEMPLATE_READ_FAIL).formatWith(fileUrl.toString()) .withReason(EMPTY_TEMPLATE).withResolution(CHECK_TEMPLATE_CONTENTS); } } } catch (IOException e) { throw new ExecutionException(TEMPLATE_READ_FAIL).formatWith(fileUrl.toString()) .withReason(ERROR_READING_TEMPLATE).withResolution(CHECK_TEMPLATE_CONTENTS); } return templateText; }
From source file:com.vmware.vchs.publicapi.samples.HttpUtils.java
/** * This method uses the vCloud API Query service * // ww w. j a v a 2 s. c om * @param baseVcdUrl * @param queryParameters * @return */ public static QueryResultRecordsType getQueryResults(String baseVcdUrl, String queryParameters, DefaultSampleCommandLineOptions options, String vCloudToken) { URL url = null; QueryResultRecordsType results = null; try { // Construct the URL from the baseVcdUrl to utilize the vCloud Query API to find a // matching template url = new URL(baseVcdUrl + "/api/query?" + queryParameters); } catch (MalformedURLException e) { throw new RuntimeException("Invalid URL: " + baseVcdUrl); } HttpGet httpGet = new HttpGet(url.toString()); httpGet.setHeader(HttpHeaders.ACCEPT, SampleConstants.APPLICATION_PLUS_XML_VERSION + options.vcdVersion); httpGet.setHeader(SampleConstants.VCD_AUTHORIZATION_HEADER, vCloudToken); HttpResponse response = HttpUtils.httpInvoke(httpGet); // make sure the status is 200 OK if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { results = HttpUtils.unmarshal(response.getEntity(), QueryResultRecordsType.class); } return results; }
From source file:hermes.impl.LoaderSupport.java
/** * Return ClassLoader given the list of ClasspathConfig instances. The * resulting loader can then be used to instantiate providers from those * libraries./*from w ww. java 2 s .c o m*/ */ static ClassLoader createClassLoader(List loaderConfigs, URL[] extraUrls, ClassLoader classLoader) throws IOException { int index = 0; int size = loaderConfigs.size(); if (extraUrls != null) { size += extraUrls.length; } URL[] urls = new URL[size]; StringBuffer debug = new StringBuffer("URLClassLoader: "); for (Iterator iter = loaderConfigs.iterator(); iter.hasNext();) { ClasspathConfig lConfig = (ClasspathConfig) iter.next(); URL url = null; if (lConfig.getJar().startsWith("http")) { url = new URL(TextUtils.replaceClasspathVariables(lConfig.getJar())); } else { url = new File(TextUtils.replaceClasspathVariables(lConfig.getJar())).toURL(); } urls[index++] = url; debug.append(url.toString()); if (iter.hasNext()) { debug.append(", "); } } if (extraUrls != null) { for (int i = 0; i < extraUrls.length; i++) { urls[index++] = extraUrls[i]; debug.append(", " + extraUrls[i].toString()); } } log.debug(debug.toString()); return new DebugClassLoader(urls, classLoader); }
From source file:com.jajja.jorm.Database.java
private static void configure(URL url) { Database.get().log.debug("Found jorm configuration @ " + url.toString()); Properties properties = new Properties(); try {//from w ww. j ava2 s. c o m InputStream is = url.openStream(); properties.load(is); is.close(); } catch (IOException ex) { Database.get().log.error("Failed to open jorm.properties: " + ex.getMessage(), ex); return; } for (Entry<Object, Object> property : properties.entrySet()) { String[] parts = ((String) property.getKey()).split("\\."); boolean isMalformed = false; if (parts[0].equals("database") && parts.length > 1) { String database = parts[1]; Configuration configuration = configurations.get(database); if (configuration == null) { configuration = new Configuration(database); configurations.put(database, configuration); } String value = (String) property.getValue(); switch (parts.length) { case 2: if (parts[1].equals("context")) { Database.get().globalDefaultContext = value; } else { isMalformed = true; } break; case 3: if (parts[2].equals("destroyMethod")) { configuration.destroyMethodName = value; } else if (parts[2].equals("dataSource")) { configuration.dataSourceClassName = value; } else if (parts[2].equals("defaultContext")) { if (database.indexOf(Context.CONTEXT_SEPARATOR) != -1) { isMalformed = true; } else { Database.get().defaultContext.put(database, value); } } else { isMalformed = true; } break; case 4: if (parts[2].equals("dataSource")) { configuration.dataSourceProperties.put(parts[3], value); } else { isMalformed = true; } break; default: isMalformed = true; } } else { isMalformed = true; } if (isMalformed) { Database.get().log.warn(String.format("Malformed jorm property: %s", property.toString())); } } }
From source file:io.stallion.utils.ResourceHelpers.java
public static List<String> listFilesInDirectory(String plugin, String path) { String ending = ""; String starting = ""; if (path.contains("*")) { String[] parts = StringUtils.split(path, "*", 2); String base = parts[0];//from ww w . jav a 2s . c o m if (!base.endsWith("/")) { path = new File(base).getParent(); starting = FilenameUtils.getName(base); } else { path = base; } ending = parts[1]; } Log.info("listFilesInDirectory Parsed Path {0} starting:{1} ending:{2}", path, starting, ending); URL url = PluginRegistry.instance().getJavaPluginByName().get(plugin).getClass().getResource(path); Log.info("URL: {0}", url); List<String> filenames = new ArrayList<>(); URL dirURL = getClassForPlugin(plugin).getResource(path); Log.info("Dir URL is {0}", dirURL); // Handle file based resource folder if (dirURL != null && dirURL.getProtocol().equals("file")) { String fullPath = dirURL.toString().substring(5); File dir = new File(fullPath); // In devMode, use the source resource folder, rather than the compiled version if (Settings.instance().getDevMode()) { String devPath = fullPath.replace("/target/classes/", "/src/main/resources/"); File devFolder = new File(devPath); if (devFolder.exists()) { dir = devFolder; } } Log.info("List files from folder {0}", dir.getAbsolutePath()); List<String> files = list(); for (String name : dir.list()) { if (!empty(ending) && !name.endsWith(ending)) { continue; } if (!empty(starting) && !name.endsWith("starting")) { continue; } // Skip special files, hidden files if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#") || name.contains("_flymake.")) { continue; } filenames.add(path + name); } return filenames; } 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 = null; try { jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); } catch (IOException e) { throw new RuntimeException(e); } if (path.startsWith("/")) { path = path.substring(1); } Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); Log.finer("Jar file entry: {0}", name); 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); } if (!empty(ending) && !name.endsWith(ending)) { continue; } if (!empty(starting) && !name.endsWith("starting")) { continue; } // Skip special files, hidden files if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#") || name.contains("_flymake.")) { continue; } result.add(entry); } } return new ArrayList<>(result); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); /* try { URL url1 = getClassForPlugin(plugin).getResource(path); Log.info("URL1 {0}", url1); if (url1 != null) { Log.info("From class folder contents {0}", IOUtils.toString(url1)); Log.info("From class folder contents as stream {0}", IOUtils.toString(getClassForPlugin(plugin).getResourceAsStream(path))); } URL url2 = getClassLoaderForPlugin(plugin).getResource(path); Log.info("URL1 {0}", url2); if (url2 != null) { Log.info("From classLoader folder contents {0}", IOUtils.toString(url2)); Log.info("From classLoader folder contents as stream {0}", IOUtils.toString(getClassLoaderForPlugin(plugin).getResourceAsStream(path))); } } catch (IOException e) { Log.exception(e, "error loading path " + path); } // Handle jar based resource folder try( InputStream in = getResourceAsStream(plugin, path); BufferedReader br = new BufferedReader( new InputStreamReader( in ) ) ) { String resource; while( (resource = br.readLine()) != null ) { Log.finer("checking resource for inclusion in directory scan: {0}", resource); if (!empty(ending) && !resource.endsWith(ending)) { continue; } if (!empty(starting) && !resource.endsWith("starting")) { continue; } // Skip special files, hidden files if (resource.startsWith(".") || resource.startsWith("~") || resource.startsWith("#") || resource.contains("_flymake.")) { continue; } Log.finer("added resource during directory scan: {0}", resource); filenames.add(path + resource); } } catch (IOException e) { throw new RuntimeException(e); } return filenames; */ }
From source file:org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils.java
public static HttpURLConnection getHttpConnection(String urlString) throws DeviceManagementException { URL connectionUrl = null; HttpURLConnection httpConnection; try {//from w ww .j ava 2 s . c om connectionUrl = new URL(urlString); httpConnection = (HttpURLConnection) connectionUrl.openConnection(); } catch (MalformedURLException e) { String errorMsg = "Error occured whilst trying to form HTTP-URL from string: " + urlString; log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } catch (IOException e) { String errorMsg = "Error occured whilst trying to open a connection to: " + connectionUrl.toString(); log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } return httpConnection; }
From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java
/** * Constructs a Class Loader based on a list of paths to classes and a * parent Class Loader/* w w w . j a v a 2 s . c o m*/ * * @param paths * @param mojoClassLoader * @return The constructed ClassLoader * @throws MalformedURLException */ public static ClassLoader getClassLoader(List<String> paths, ClassLoader mojoClassLoader) throws MalformedURLException { final List<URL> pathURLs = new ArrayList<URL>(); for (String curPath : paths) { URL newClassPathURL = new File(curPath).toURI().toURL(); getLog().debug("Adding " + newClassPathURL.toString() + " to class loader"); pathURLs.add(newClassPathURL); } return new URLClassLoader(pathURLs.toArray(new URL[0]), mojoClassLoader); }
From source file:com.moviejukebox.scanner.artwork.FanartScanner.java
/** * Get the Fanart for the movie from TheMovieDB.org * * @author Stuart.Boston/*from w ww. j a v a 2s . c om*/ * @param movie The movie to get the fanart for * @return A string URL pointing to the fanart */ private static String getMovieFanartURL(Movie movie) { // Unable to scan for fanart because TheMovieDB wasn't initialised if (TMDB == null) { return Movie.UNKNOWN; } String language = PropertiesUtil.getProperty("themoviedb.language", "en-US"); MovieInfo moviedb = null; String imdbID = movie.getId(ImdbPlugin.IMDB_PLUGIN_ID); String tmdbIDstring = movie.getId(TheMovieDbPlugin.TMDB_PLUGIN_ID); int tmdbID; if (StringUtils.isNumeric(tmdbIDstring)) { tmdbID = Integer.parseInt(tmdbIDstring); } else { tmdbID = 0; } if (tmdbID > 0) { try { moviedb = TMDB.getMovieInfo(tmdbID, language); } catch (MovieDbException ex) { LOG.debug("Failed to get fanart using TMDB ID: {} - {}", tmdbID, ex.getMessage()); } } if (moviedb == null && StringTools.isValidString(imdbID)) { try { // The ImdbLookup contains images moviedb = TMDB.getMovieInfoImdb(imdbID, language); } catch (MovieDbException ex) { LOG.debug("Failed to get fanart using IMDB ID: {} - {}", imdbID, ex.getMessage()); } } if (moviedb == null) { try { ResultList<MovieInfo> result = TMDB.searchMovie(movie.getOriginalTitle(), 0, language, TheMovieDbPlugin.INCLUDE_ADULT, 0, 0, SearchType.PHRASE); List<MovieInfo> movieList = result.getResults(); for (MovieInfo m : movieList) { if (m.getTitle().equals(movie.getTitle()) || m.getTitle().equalsIgnoreCase(movie.getOriginalTitle()) || m.getOriginalTitle().equalsIgnoreCase(movie.getTitle()) || m.getOriginalTitle().equalsIgnoreCase(movie.getOriginalTitle())) { if (StringTools.isNotValidString(movie.getYear())) { // We don't have a year for the movie, so assume this is the correct movie moviedb = m; break; } else if (m.getReleaseDate().contains(movie.getYear())) { // found the movie name and year moviedb = m; break; } } } } catch (MovieDbException ex) { LOG.debug("Failed to get fanart using IMDB ID: {} - {}", imdbID, ex.getMessage()); } } // Check that the returned movie isn't null if (moviedb == null) { LOG.debug("Error getting fanart from TheMovieDB.org for {}", movie.getBaseFilename()); return Movie.UNKNOWN; } try { URL fanart = TMDB.createImageUrl(moviedb.getBackdropPath(), "original"); if (fanart == null) { return Movie.UNKNOWN; } return fanart.toString(); } catch (MovieDbException ex) { LOG.debug("Error getting fanart from TheMovieDB.org for {}", movie.getBaseFilename()); return Movie.UNKNOWN; } }