List of usage examples for java.net URL toURI
public URI toURI() throws URISyntaxException
From source file:org.jboss.as.test.manualmode.web.ssl.AbstractCertificateLoginModuleTestCase.java
/** * Requests given URL and checks if the returned HTTP status code is the * expected one. Returns HTTP response body *//*from w ww.j ava 2s.c om*/ public static String makeCall(URL url, HttpClient httpClient, int expectedStatusCode) throws ClientProtocolException, IOException, URISyntaxException { String httpResponseBody = null; HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); LOGGER.trace("Request to: " + url + " responds: " + statusCode); assertEquals("Unexpected status code", expectedStatusCode, statusCode); HttpEntity entity = response.getEntity(); if (entity != null) { httpResponseBody = EntityUtils.toString(response.getEntity()); EntityUtils.consume(entity); } return httpResponseBody; }
From source file:org.cloudifysource.azure.AbstractCliAzureDeploymentTest.java
protected static boolean isUrlAvailable(URL url) throws URISyntaxException { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url.toURI()); httpGet.addHeader("Cache-Control", "no-cache"); try {//from ww w .j a v a 2s . c o m HttpResponse response = client.execute(httpGet); logger.info("HTTP GET " + url + " returned " + response.getStatusLine().getReasonPhrase() + " Response: [" + response.getStatusLine().getStatusCode() + "] " + EntityUtils.toString(response.getEntity())); if (response.getStatusLine().getStatusCode() == 404 || response.getStatusLine().getStatusCode() == 502) { return false; } return true; } catch (Exception e) { log("Failed connecting to " + url, e); return false; } finally { client.getConnectionManager().shutdown(); } }
From source file:org.openremote.android.console.net.ORConnection.java
/** * TODO// ww w.j a v a 2 s.c om * * Establish the httpconnection with url for caller and then the caller can deal with the * httprequest result within ORConnectionDelegate instance. if check failed, return null. * * @param context global Android application context * @param httpMethod enum POST or GET * @param url the URL to connect to * @param useHTTPAuth indicates whether the HTTP 'Authentication' header should be added * to the HTTP request * * @return TODO * * @throws IOException if the URL cannot be resolved by DNS (UnknownHostException), * if the URL was not correctly formed (MalformedURLException), * if the connection timed out (SocketTimeoutException), * there was an error in the HTTP protocol (ClientProtocolException), * or any other IO error occured (generic IOException) */ public static HttpResponse checkURLWithHTTPProtocol(Context context, ORHttpMethod httpMethod, String urlString, boolean useHTTPAuth) throws IOException { // TODO : could move this method to ORNetworkCheck class, no one else is using it. // // TODO : use URL in the API instead of string // // Validate the URL by creating a proper URL instance from the string... it will throw // an MalformedURLException (IOException) in case the URL was invalid. // // This can go away when the API is fixed... URL targetURL = new URL(urlString); URI targetURI; try { targetURI = targetURL.toURI(); } catch (URISyntaxException e) { // Not sure if we're ever going to hit this, but in case we do, just convert to // MalformedURLException... throw new MalformedURLException( "Could not convert " + urlString + " to a compliant URI: " + e.getMessage()); } HttpRequestBase request = null; HttpResponse response = null; HttpParams params = new BasicHttpParams(); // TODO : seems like timeouts ought to be externalized... HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpClient client = new DefaultHttpClient(params); switch (httpMethod) { case POST: request = new HttpPost(targetURI); break; case GET: request = new HttpGet(targetURI); break; default: throw new IOException("Unsupported HTTP Method: " + httpMethod); } if (useHTTPAuth) { SecurityUtil.addCredentialToHttpRequest(context, request); } if ("https".equals(targetURL.getProtocol())) { Scheme sch = new Scheme(targetURL.getProtocol(), new SelfCertificateSSLSocketFactory(context), targetURL.getPort()); client.getConnectionManager().getSchemeRegistry().register(sch); } try { response = client.execute(request); } catch (IllegalArgumentException e) { throw new MalformedURLException("Illegal argument: " + e.getMessage()); } return response; }
From source file:WarUtil.java
public static boolean isResourceExist(URL resource) { if (resource.getProtocol().equals(FILE_PROTOCOL)) { try {// w ww. ja va2s . c o m File file = new File(resource.toURI()); return file.exists(); } catch (URISyntaxException e) { return false; } } InputStream is = null; try { is = resource.openStream(); return (is != null); } catch (Exception ioe) { return false; } }
From source file:io.Tools.java
/** * Create test PDB and Chemcomp folder. Also all PDB files in resources are copied there so all test can use this * folder/*from w w w. j ava 2 s . co m*/ * * @return */ public static String createPermanentTestFolder() { String d = System.getProperty("user.home"); String builtTestFolder = d + File.separator + "Documents" + File.separator + testFolderName + File.separator; final File baseDir = new File(builtTestFolder); String builttestPDBFolder = builtTestFolder + File.separator + "pdb"; baseDir.mkdirs(); final File pdbDir = new File(builttestPDBFolder); if (Files.exists(Paths.get(builttestPDBFolder))) { try { FileUtils.deleteDirectory(pdbDir); } catch (IOException e) { } } pdbDir.mkdir(); String builttestChemcompFolder = builtTestFolder + File.separator + "chemcomp"; final File chemcompDir = new File(builttestChemcompFolder); if (Files.exists(Paths.get(builttestChemcompFolder))) { try { FileUtils.deleteDirectory(chemcompDir); } catch (IOException e) { } } chemcompDir.mkdirs(); pdbDir.mkdir(); testChemcompFolder = builtTestFolder; testPDBFolder = builttestPDBFolder; String resourcesPDBFolder = null; try { URL url = BiojavaReaderFromPDBFolderTest.class.getClassLoader().getResource("pdb/1di9.cif.gz"); File pdb1di9file = new File(url.toURI()); resourcesPDBFolder = pdb1di9file.getParent(); Map<String, List<MMcifFileInfos>> indexPDBFileInFolder = IOTools .indexPDBFileInFolder(new File(resourcesPDBFolder).toString()); for (Map.Entry<String, List<MMcifFileInfos>> entry : indexPDBFileInFolder.entrySet()) { try { FileUtils.copyFileToDirectory(new File(entry.getValue().get(0).getPathToFile().toString()), pdbDir); } catch (IOException e) { e.printStackTrace(); } } } catch (URISyntaxException e) { e.printStackTrace(); } String resourcesChemcompFolder = null; try { URL url = BiojavaReaderFromPDBFolderTest.class.getClassLoader().getResource("chemcomp/0DY.cif.gz"); File chemcomp0DY = new File(url.toURI()); resourcesChemcompFolder = chemcomp0DY.getParent(); Map<String, List<Path>> indexPDBFileInFolder = IOTools .indexChemcompFileInFolder(new File(resourcesChemcompFolder).toString()); for (Map.Entry<String, List<Path>> entry : indexPDBFileInFolder.entrySet()) { try { FileUtils.copyFileToDirectory(new File(entry.getValue().get(0).toString()), new File(builttestChemcompFolder)); } catch (IOException e) { e.printStackTrace(); } } } catch (URISyntaxException e) { e.printStackTrace(); } return testChemcompFolder; }
From source file:cloudlens.parser.FileReader.java
public static InputStream fetchFile(String urlString) { try {/* w w w. j av a 2s .c o m*/ InputStream inputStream; URL url; if (urlString.startsWith("local:")) { final String path = urlString.replaceFirst("local:", ""); inputStream = Files.newInputStream(Paths.get(path)); } else if (urlString.startsWith("file:")) { url = new URL(urlString); inputStream = Files.newInputStream(Paths.get(url.toURI())); } else if (urlString.startsWith("http:") || urlString.startsWith("https:")) { url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString); if (matcher.find()) { final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes()); conn.setRequestProperty("Authorization", "Basic " + encoding); } conn.setRequestMethod("GET"); inputStream = conn.getInputStream(); } else { throw new CLException("supported protocols are: http, https, file, and local."); } return inputStream; } catch (IOException | URISyntaxException e) { throw new CLException(e.getMessage()); } }
From source file:jp.terasoluna.fw.batch.unit.util.ClassLoaderUtils.java
/** * <pre>// w ww . ja v a 2 s.com * srcPaths?????????? * ?????? * ????destPaths???? * </pre> * * @param destPaths * @param srcPaths */ public static void addPathIfExists(List<String> destPaths, List<String> srcPaths) { Assert.notNull(destPaths); Assert.notNull(srcPaths); ClassLoader cl = getClassLoader(); for (String path : srcPaths) { if (path != null) { URL r = cl.getResource(path); if (r != null) { try { String protocol = r.getProtocol(); if (protocol.equals("file")) { URI uri = r.toURI(); File f = new File(uri); if (f.isFile()) { // ????? destPaths.add(path); } } else { // jar URLConnection con = null; try { con = r.openConnection(); if (con.getContentLength() > 0) { // ????? destPaths.add(path); } } catch (IOException e) { // ????????? LOG.warn(con + " is illegal.", e); } } } catch (URISyntaxException e) { // r != null??????????????? LOG.warn(path + " is illegal.", e); } } else { LOG.debug(path + " is not found."); } } } }
From source file:net.sf.jabref.gui.groups.EntryTableTransferHandler.java
/** * Translate a String describing a set of files or URLs dragged into JabRef into a List of File objects, taking care * of URL special characters.//from w w w . jav a 2s .c o m * * @param s String describing a set of files or URLs dragged into JabRef * @return a List<File> containing the individual file objects. * */ public static List<File> getFilesFromDraggedFilesString(String s) { // Split into lines: String[] lines = s.replace("\r", "").split("\n"); List<File> files = new ArrayList<>(); for (String line1 : lines) { String line = line1; // Try to use url.toURI() to translate URL specific sequences like %20 into // standard characters: File fl = null; try { URL url = new URL(line); fl = new File(url.toURI()); } catch (MalformedURLException | URISyntaxException e) { LOGGER.warn("Could not get file", e); } // Unless an exception was thrown, we should have the sanitized path: if (fl != null) { line = fl.getPath(); } else if (line.startsWith("file:")) { line = line.substring(5); } else { continue; } // Under Gnome, the link is given as file:///...., so we // need to strip the extra slashes: if (line.startsWith("//")) { line = line.substring(2); } File f = new File(line); if (f.exists()) { files.add(f); } } return files; }
From source file:net.sf.jabref.groups.EntryTableTransferHandler.java
/** * Translate a String describing a set of files or URLs dragged into JabRef into a List of File objects, taking care * of URL special characters.//from w w w.j a va2 s. c o m * * @param s String describing a set of files or URLs dragged into JabRef * @return a List<File> containing the individual file objects. * */ public static List<File> getFilesFromDraggedFilesString(String s) { // Split into lines: String[] lines = s.replaceAll("\r", "").split("\n"); List<File> files = new ArrayList<>(); for (String line1 : lines) { String line = line1; // Try to use url.toURI() to translate URL specific sequences like %20 into // standard characters: File fl = null; try { URL url = new URL(line); fl = new File(url.toURI()); } catch (MalformedURLException | URISyntaxException e) { LOGGER.warn("Could not get file", e); } // Unless an exception was thrown, we should have the sanitized path: if (fl != null) { line = fl.getPath(); } else if (line.startsWith("file:")) { line = line.substring(5); } else { continue; } // Under Gnome, the link is given as file:///...., so we // need to strip the extra slashes: if (line.startsWith("//")) { line = line.substring(2); } File f = new File(line); if (f.exists()) { files.add(f); } } return files; }
From source file:com.mpower.mintel.android.utilities.WebUtils.java
public static HttpResponse stringResponseGet(String urlString, HttpContext localContext, HttpClient httpclient) throws Exception { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); URI u = url.toURI(); HttpGet req = new HttpGet(); req.setURI(u);//from w w w .j a va 2s .c o m HttpResponse response = null; response = httpclient.execute(req, localContext); return response; }