List of usage examples for java.net URI getScheme
public String getScheme()
From source file:ratpack.spring.config.RatpackProperties.java
static Path resourceToPath(URL resource) { Objects.requireNonNull(resource, "Resource URL cannot be null"); URI uri; try {/* w ww . j a v a 2 s.c o m*/ uri = resource.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not extract URI", e); } String scheme = uri.getScheme(); if (scheme.equals("file")) { String path = uri.toString().substring("file:".length()); if (path.contains("//")) { path = StringUtils.cleanPath(path.replace("//", "")); } return Paths.get(new FileSystemResource(path).getFile().toURI()); } if (!scheme.equals("jar")) { throw new IllegalArgumentException("Cannot convert to Path: " + uri); } String s = uri.toString(); int separator = s.indexOf("!/"); String entryName = s.substring(separator + 2); URI fileURI = URI.create(s.substring(0, separator)); FileSystem fs; try { fs = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap()); return fs.getPath(entryName); } catch (IOException e) { throw new IllegalArgumentException("Could not create file system for resource: " + resource, e); } }
From source file:brooklyn.networking.cloudstack.HttpUtil.java
public static HttpClient createHttpClient(URI uri, Optional<Credentials> credentials) { final DefaultHttpClient httpClient = new DefaultHttpClient(); // TODO if supplier returns null, we may wish to defer initialization until url available? if (uri != null && "https".equalsIgnoreCase(uri.getScheme())) { try {/*from www . ja va 2s . c om*/ int port = (uri.getPort() >= 0) ? uri.getPort() : 443; SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustAllStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", port, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (Exception e) { LOG.warn("Error in HTTP Feed of {}, setting trust for uri {}", uri); throw Exceptions.propagate(e); } } // Set credentials if (uri != null && credentials.isPresent()) { String hostname = uri.getHost(); int port = uri.getPort(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials.get()); } return httpClient; }
From source file:fr.free.movierenamer.utils.URIRequest.java
private static URLConnection openConnection(URI uri, RequestProperty... properties) throws IOException { boolean isHttpRequest = Proxy.Type.HTTP.name().equalsIgnoreCase(uri.getScheme()); URLConnection connection;/*w w w .ja va 2s .com*/ if (isHttpRequest && Settings.getInstance().isProxyIsOn()) { Settings settings = Settings.getInstance(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(settings.getProxyUrl(), settings.getProxyPort())); connection = uri.toURL().openConnection(proxy); } else { connection = uri.toURL().openConnection(); } if (isHttpRequest) { Settings settings = Settings.getInstance(); connection.setReadTimeout(settings.getHttpRequestTimeOut() * 1000); // in ms //fake user agent ;) connection.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"); connection.addRequestProperty("From", "googlebot(at)googlebot.com"); connection.addRequestProperty("Accept", "*/*"); String customUserAgent = settings.getHttpCustomUserAgent(); if (customUserAgent != null && customUserAgent.length() > 0) { connection.addRequestProperty("User-Agent", customUserAgent); } } connection.addRequestProperty("Accept-Encoding", "gzip,deflate"); connection.addRequestProperty("Accept-Charset", UTF + "," + ISO); // important for accents ! if (properties != null) { for (RequestProperty property : properties) { connection.addRequestProperty(property.getKey(), property.getValue()); } } return connection; }
From source file:com.cloud.utils.UriUtils.java
public static Long getRemoteSize(String url) { Long remoteSize = (long) 0; HttpURLConnection httpConn = null; HttpsURLConnection httpsConn = null; try {/*w w w. j a va 2 s .co m*/ URI uri = new URI(url); if (uri.getScheme().equalsIgnoreCase("http")) { httpConn = (HttpURLConnection) uri.toURL().openConnection(); if (httpConn != null) { httpConn.setConnectTimeout(2000); httpConn.setReadTimeout(5000); String contentLength = httpConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpConn.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("https")) { httpsConn = (HttpsURLConnection) uri.toURL().openConnection(); if (httpsConn != null) { String contentLength = httpsConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpsConn.disconnect(); } } } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } catch (IOException e) { throw new IllegalArgumentException("Unable to establish connection with URL " + url); } return remoteSize; }
From source file:org.koiroha.jyro.workers.crawler.Crawler.java
/** * Determine the port number of specified uri. Return negative value if * URI scheme is not supported.// w w w . jav a 2 s.co m * * @param uri URI * @return port number */ private static int getPort(URI uri) { int port = uri.getPort(); if (port >= 0) { return port; } String scheme = uri.getScheme(); if (scheme.equals("http")) { return 80; } else if (scheme.equals("https")) { return 443; } else if (scheme.equals("ftp")) { return 21; } return -1; }
From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java
/** * Copy any missing files from the the jar's resources/firmware_config/ dir * into the settings/firmware_config dir. *//*from ww w.ja v a2 s.c o m*/ public synchronized static void initialize() { System.out.println("Initializing firmware... ..."); File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME); // Create directory if it's missing. if (!firmwareConfig.exists()) { firmwareConfig.mkdirs(); } FileSystem fileSystem = null; // Copy firmware config files. try { final String dir = "/resources/firmware_config/"; URI location = FirmwareUtils.class.getResource(dir).toURI(); Path myPath; if (location.getScheme().equals("jar")) { try { // In case the filesystem already exists. fileSystem = FileSystems.getFileSystem(location); } catch (FileSystemNotFoundException e) { // Otherwise create the new filesystem. fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap()); } myPath = fileSystem.getPath(dir); } else { myPath = Paths.get(location); } Stream<Path> files = Files.walk(myPath, 1); for (Path path : (Iterable<Path>) () -> files.iterator()) { System.out.println(path); final String name = path.getFileName().toString(); File fwConfig = new File(firmwareConfig, name); if (name.endsWith(".json")) { boolean copyFile = !fwConfig.exists(); ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path)); // If the file is outdated... ask the user (once). if (fwConfig.exists()) { ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig)); boolean outOfDate = current.getVersion() < jarSetting.getVersion(); if (outOfDate && !userNotified && !overwriteOldFiles) { int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); overwriteOldFiles = result == JOptionPane.OK_OPTION; userNotified = true; } if (overwriteOldFiles) { copyFile = true; jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom; } } // Copy file from jar to firmware_config directory. if (copyFile) { try { save(fwConfig, jarSetting); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } } } catch (Exception ex) { String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage()); GUIHelpers.displayErrorDialog(errorMessage); logger.log(Level.SEVERE, errorMessage, ex); } finally { if (fileSystem != null) { try { fileSystem.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Problem closing filesystem.", ex); } } } configFiles.clear(); for (File f : firmwareConfig.listFiles()) { try { ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class); //ConfigLoader config = new ConfigLoader(f); configFiles.put(config.getName(), new ConfigTuple(config, f)); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) { GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath()); } } }
From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java
public static RomData getROMFrom(final String url) throws IOException { final URI uri; try {//from w w w . jav a 2s .c om uri = new URI(url); } catch (URISyntaxException ex) { throw new IOException("Error in URL '" + url + "\'", ex); } final String scheme = uri.getScheme(); final String userInfo = uri.getUserInfo(); final String name; final String password; if (userInfo != null) { final String[] splitted = userInfo.split("\\:"); name = splitted[0]; password = splitted[1]; } else { name = null; password = null; } final byte[] loaded; if (scheme.startsWith("http")) { loaded = loadHTTPArchive(url); } else if (scheme.startsWith("ftp")) { loaded = loadFTPArchive(uri.getHost(), uri.getPath(), name, password); } else { throw new IllegalArgumentException("Unsupported scheme [" + scheme + ']'); } final ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(loaded)); byte[] rom48 = null; byte[] rom128 = null; byte[] romTrDos = null; while (true) { final ZipArchiveEntry entry = in.getNextZipEntry(); if (entry == null) { break; } if (entry.isDirectory()) { continue; } if (ROM_48.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM 48 has too big size"); } rom48 = new byte[16384]; IOUtils.readFully(in, rom48, 0, size); } else if (ROM_128TR.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM 128TR has too big size"); } rom128 = new byte[16384]; IOUtils.readFully(in, rom128, 0, size); } else if (ROM_TRDOS.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM TRDOS has too big size"); } romTrDos = new byte[16384]; IOUtils.readFully(in, romTrDos, 0, size); } } if (rom48 == null) { throw new IOException(ROM_48 + " not found"); } if (rom128 == null) { throw new IOException(ROM_128TR + " not found"); } if (romTrDos == null) { throw new IOException(ROM_TRDOS + " not found"); } return new RomData(rom48, rom128, romTrDos); }
From source file:com.cloud.utils.UriUtils.java
public static Pair<String, Integer> validateUrl(String format, String url) throws IllegalArgumentException { try {// ww w . j a v a 2 s .c o m URI uri = new URI(url); if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { throw new IllegalArgumentException("Unsupported scheme for url: " + url); } int port = uri.getPort(); if (!(port == 80 || port == 8080 || port == 443 || port == -1)) { throw new IllegalArgumentException("Only ports 80, 8080 and 443 are allowed"); } if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) { port = 443; } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) { port = 80; } String host = uri.getHost(); try { InetAddress hostAddr = InetAddress.getByName(host); if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { throw new IllegalArgumentException("Illegal host specified in url"); } if (hostAddr instanceof Inet6Address) { throw new IllegalArgumentException( "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); } } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); } // verify format if (format != null) { String uripath = uri.getPath(); checkFormat(format, uripath); } return new Pair<String, Integer>(host, port); } catch (URISyntaxException use) { throw new IllegalArgumentException("Invalid URL: " + url); } }
From source file:com.microsoft.tfs.core.credentials.internal.KeychainCredentialsManager.java
/** * @param uri// ww w . j a va2s .c o m * the {@link URI} to use; should already have path and query parts * removed ({@link URIUtils#removePathAndQueryParts(URI)}) (must not * be <code>null</code>) */ private static KeychainInternetPassword newKeychainInternetPasswordFromURI(final URI uri) { Check.notNull(uri, "uri"); //$NON-NLS-1$ final KeychainInternetPassword keychainPassword = new KeychainInternetPassword(); /* * Compute the protocol. */ if ("http".equalsIgnoreCase(uri.getScheme())) //$NON-NLS-1$ { keychainPassword.setProtocol(KeychainProtocol.HTTP); } else if ("https".equalsIgnoreCase(uri.getScheme())) //$NON-NLS-1$ { keychainPassword.setProtocol(KeychainProtocol.HTTPS); } else { keychainPassword.setProtocol(KeychainProtocol.ANY); } if (uri.getHost() != null && uri.getHost().length() > 0) { keychainPassword.setServerName(uri.getHost()); } if (uri.getPort() > 0) { keychainPassword.setPort(uri.getPort()); } if (uri.getPath() != null) { keychainPassword.setPath(uri.getPath()); } return keychainPassword; }
From source file:com.cloud.utils.UriUtils.java
public static String getUpdateUri(String url, boolean encrypt) { String updatedPath = null;/* ww w . j ava 2 s .co m*/ try { String query = URIUtil.getQuery(url); URIBuilder builder = new URIBuilder(url); builder.removeQuery(); StringBuilder updatedQuery = new StringBuilder(); List<NameValuePair> queryParams = getUserDetails(query); ListIterator<NameValuePair> iterator = queryParams.listIterator(); while (iterator.hasNext()) { NameValuePair param = iterator.next(); String value = null; if ("password".equalsIgnoreCase(param.getName()) && param.getValue() != null) { value = encrypt ? DBEncryptionUtil.encrypt(param.getValue()) : DBEncryptionUtil.decrypt(param.getValue()); } else { value = param.getValue(); } if (updatedQuery.length() == 0) { updatedQuery.append(param.getName()).append('=').append(value); } else { updatedQuery.append('&').append(param.getName()).append('=').append(value); } } String schemeAndHost = ""; URI newUri = builder.build(); if (newUri.getScheme() != null) { schemeAndHost = newUri.getScheme() + "://" + newUri.getHost(); } updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery; } catch (URISyntaxException e) { throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage()); } return updatedPath; }