List of usage examples for java.net URL toURI
public URI toURI() throws URISyntaxException
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java
private static boolean isUrlAvailable(URL url) throws URISyntaxException { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url.toURI()); httpGet.addHeader("Cache-Control", "no-cache"); try {// ww w . j av a 2s . co m HttpResponse response = client.execute(httpGet); System.out.print("HTTP GET " + url + "Response:"); response.getEntity().writeTo(System.out); System.out.print(""); if (response.getStatusLine().getStatusCode() == 404) { return false; } return true; } catch (Exception e) { log("Failed connecting to " + url, e); return false; } finally { client.getConnectionManager().shutdown(); } }
From source file:com.mongolduu.android.ng.misc.HttpConnector.java
public static boolean downloadSong(long id, DownloadSongTask task) { try {/*from ww w. jav a2s .c o m*/ File file = Utils.getSongFile(id); if (file.exists()) { file.delete(); } URL downloadURL = new URL( IMongolduuConstants.DOWNLOAD_URL + "?" + IMongolduuConstants.SONG_ID_PARAMETER_NAME + "=" + id); HttpClient httpClient = createHttpClient(); HttpResponse httpResponse = httpClient.execute(new HttpGet(downloadURL.toURI())); HttpEntity httpEntity = httpResponse.getEntity(); long length = 0; try { length = Long.parseLong(httpResponse.getHeaders("Content-Length")[0].getValue()); } catch (NumberFormatException e) { Log.e(IMongolduuConstants.LOG_TAG, "exception", e); } InputStream input = new BufferedInputStream(httpEntity.getContent()); OutputStream output = new FileOutputStream(file); byte buffer[] = new byte[1024]; int count = 0; int total = 0; while ((count = input.read(buffer)) != -1 && !task.isCancelled()) { total += count; task.publishProgressFromOtherProcess((int) (total * 100 / length)); output.write(buffer, 0, count); } output.flush(); output.close(); input.close(); httpEntity.consumeContent(); return true; } catch (Exception e) { Log.e(IMongolduuConstants.LOG_TAG, "exception", e); } return false; }
From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java
/** * Find library file/directory from an element class. * @param aClass element class in target library * @return target file/directory, or {@code null} if not found * @throws IllegalArgumentException if some parameters were {@code null} *///from www .j a v a 2 s . co m public static File findLibraryPathFromClass(Class<?> aClass) { if (aClass == null) { throw new IllegalArgumentException("aClass must not be null"); //$NON-NLS-1$ } int start = aClass.getName().lastIndexOf('.') + 1; String name = aClass.getName().substring(start); URL resource = aClass.getResource(name + ".class"); if (resource == null) { LOG.warn("Failed to locate the class file: {}", aClass.getName()); return null; } String protocol = resource.getProtocol(); if (protocol.equals("file")) { try { File file = new File(resource.toURI()); return toClassPathRoot(aClass, file); } catch (URISyntaxException e) { LOG.warn( MessageFormat.format( "Failed to locate the library path (cannot convert to local file): {0}", resource), e); return null; } } if (protocol.equals("jar")) { String path = resource.getPath(); return toClassPathRoot(aClass, path); } else { LOG.warn("Failed to locate the library path (unsupported protocol {}): {}", resource, aClass.getName()); return null; } }
From source file:org.fuin.owndeb.commons.DebUtils.java
/** * Downloads a file from an URL to a file and outputs progress in the log * (level 'info') every 1000 bytes.//from w ww. java 2s . com * * @param url * URL to download. * @param dir * Target directory. * @param cookies * Cookies for the request (Format: "name=value"). */ public static void download(@NotNull final URL url, @NotNull final File dir, final String... cookies) { Contract.requireArgNotNull("url", url); Contract.requireArgNotNull("dir", dir); LOG.info("Download: {}", url); try { final Request request = Request.Get(url.toURI()); if (cookies != null) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < cookies.length; i++) { if (i > 0) { sb.append(";"); } sb.append(cookies[i]); } request.addHeader("Cookie", sb.toString()); } final File file = new File(dir, FilenameUtils.getName(url.getFile())); request.execute().saveContent(file); } catch (final IOException | URISyntaxException ex) { throw new RuntimeException("Error downloading: " + url, ex); } }
From source file:com.mpower.clientcollection.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString//from ww w . j a va 2s .c o m * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient) { URI u = null; try { URL url = new URL(urlString); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } if (u.getHost() == null) { return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0); } // if https then enable preemptive basic auth... if (u.getScheme().equals("https")) { enablePreemptiveBasicAuth(localContext, u.getHost()); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u); //req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (statusCode != HttpStatus.SC_OK) { WebUtils.discardEntityBytes(response); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // clear the cookies -- should not be necessary? ClientCollection.getInstance().getCookieStore().clear(); } String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH) .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { WebUtils.discardEntityBytes(response); String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) { is = new GZIPInputStream(is); } isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); isr = null; } finally { if (isr != null) { try { // ensure stream is consumed... final long count = 1024L; while (isr.skip(count) == count) ; } catch (Exception e) { // no-op } try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { clearHttpConnectionManager(); e.printStackTrace(); String cause; Throwable c = e; while (c.getCause() != null) { c = c.getCause(); } cause = c.toString(); String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java
/** * This methods extracts the number of machines running gs-agents using the rest admin api * //ww w. j a v a 2 s. c o m * @param machinesRestAdminUrl * @return number of machines running gs-agents * @throws IOException * @throws URISyntaxException */ private static int getNumberOfMachines(URL machinesRestAdminUrl) throws IOException, URISyntaxException { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(machinesRestAdminUrl.toURI()); try { String json = client.execute(httpGet, new BasicResponseHandler()); Matcher matcher = Pattern.compile("\"Size\":\"([0-9]+)\"").matcher(json); if (matcher.find()) { String rawSize = matcher.group(1); int size = Integer.parseInt(rawSize); return size; } else { return 0; } } catch (Exception e) { return 0; } finally { client.getConnectionManager().shutdown(); } }
From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtil.java
/** * Resolve the specified filename to a URI. * @param filename name os the file// w w w.j a va2 s. c om * @return resolved header file URI * @throws CheckstyleException on failure */ public static URI getUriByFilename(String filename) throws CheckstyleException { // figure out if this is a File or a URL URI uri; try { final URL url = new URL(filename); uri = url.toURI(); } catch (final URISyntaxException | MalformedURLException ignored) { uri = null; } if (uri == null) { final File file = new File(filename); if (file.exists()) { uri = file.toURI(); } else { // check to see if the file is in the classpath try { final URL configUrl = CommonUtil.class.getResource(filename); if (configUrl == null) { throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename); } uri = configUrl.toURI(); } catch (final URISyntaxException ex) { throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, ex); } } } return uri; }
From source file:eu.impact_project.wsclient.FileServiceProvider.java
/** * Tries to find the configuration file. * /* ww w .j a va2s.c o m*/ * @return URL of the found configuration file * @throws MalformedURLException * @throws URISyntaxException */ public static URL findConfig() throws MalformedURLException, URISyntaxException { URL configUrl = null; String baseDir = null; if (sc != null) { if (sc.getInitParameter("serviceList") != null) { logger.debug("Using servlet parameter " + sc.getInitParameter("serviceList")); configUrl = new File(sc.getInitParameter("serviceList")).toURI().toURL(); } baseDir = sc.getRealPath(".") + File.separator; logger.debug("Base directory is " + baseDir); } if (configUrl != null && new File(configUrl.toURI()).exists()) { logger.debug(configUrl + " exists"); return configUrl; } else if (baseDir != null && new File(baseDir + "WEB-INF/classes/services.xml").exists()) { configUrl = new File(baseDir + "WEB-INF/classes/services.xml").toURI().toURL(); } else if (new File(baseDir + "./WEB-INF/classes/services.xml").exists()) { configUrl = new File("./WEB-INF/classes/services.xml").toURI().toURL(); } else if (new File(WSDLinfo.configLocation).exists()) { configUrl = new File(WSDLinfo.configLocation).toURI().toURL(); } return configUrl; }
From source file:fll.xml.XMLUtils.java
/** * Get all challenge descriptors build into the software. *///from w w w.j a v a 2 s .c o m public static Collection<URL> getAllKnownChallengeDescriptorURLs() { final String baseDir = "fll/resources/challenge-descriptors/"; final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final URL directory = classLoader.getResource(baseDir); if (null == directory) { LOGGER.warn("base dir for challenge descriptors not found"); return Collections.emptyList(); } final Collection<URL> urls = new LinkedList<URL>(); if ("file".equals(directory.getProtocol())) { try { final URI uri = directory.toURI(); final File fileDir = new File(uri); final File[] files = fileDir.listFiles(); if (null != files) { for (final File file : files) { if (file.getName().endsWith(".xml")) { try { final URL fileUrl = file.toURI().toURL(); urls.add(fileUrl); } catch (final MalformedURLException e) { LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e); } } } } } catch (final URISyntaxException e) { LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e); } } else if (directory.getProtocol().equals("jar")) { final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource(); if (null != src) { final URL jar = src.getLocation(); JarInputStream zip = null; try { zip = new JarInputStream(jar.openStream()); JarEntry ze = null; while ((ze = zip.getNextJarEntry()) != null) { final String entryName = ze.getName(); if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) { // add 1 to baseDir to skip past the path separator final String challengeName = entryName.substring(baseDir.length()); // check that the file really exists and turn it into a URL final URL challengeUrl = classLoader.getResource(baseDir + challengeName); if (null != challengeUrl) { urls.add(challengeUrl); } else { // TODO could write the resource out to a temporary file if // needed // then mark the file as delete on exit LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: " + entryName); } } } zip.close(); } catch (final IOException e) { LOGGER.error("Error reading jar file at: " + jar.toString(), e); } finally { IOUtils.closeQuietly(zip); } } else { LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors"); } } else { throw new UnsupportedOperationException("Cannot list files for URL " + directory); } return urls; }
From source file:org.jboss.as.test.integration.domain.management.cli.DomainDeploymentOverlayTestCase.java
@BeforeClass public static void before() throws Exception { String tempDir = System.getProperty("java.io.tmpdir"); WebArchive war;/*w w w . j av a2 s.com*/ // deployment1 war = ShrinkWrap.create(WebArchive.class, "deployment0.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource("cli/deployment-overlay/web.xml", "web.xml"); war1 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war1, true); war = ShrinkWrap.create(WebArchive.class, "deployment1.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource("cli/deployment-overlay/web.xml", "web.xml"); war2 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war2, true); war = ShrinkWrap.create(WebArchive.class, "another.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource("cli/deployment-overlay/web.xml", "web.xml"); war3 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war3, true); final URL overrideXmlUrl = DomainDeploymentOverlayTestCase.class.getClassLoader() .getResource("cli/deployment-overlay/override.xml"); if (overrideXmlUrl == null) { Assert.fail("Failed to locate cli/deployment-overlay/override.xml"); } overrideXml = new File(overrideXmlUrl.toURI()); if (!overrideXml.exists()) { Assert.fail("Failed to locate cli/deployment-overlay/override.xml"); } final URL webXmlUrl = DomainDeploymentOverlayTestCase.class.getClassLoader() .getResource("cli/deployment-overlay/web.xml"); if (webXmlUrl == null) { Assert.fail("Failed to locate cli/deployment-overlay/web.xml"); } webXml = new File(webXmlUrl.toURI()); if (!webXml.exists()) { Assert.fail("Failed to locate cli/deployment-overlay/web.xml"); } // Launch the domain testSupport = DomainTestSupport .createAndStartDefaultSupport(DomainDeploymentOverlayTestCase.class.getSimpleName()); }