List of usage examples for java.net URL toURI
public URI toURI() throws URISyntaxException
From source file:com.github.jengelman.gradle.plugins.integration.TestFile.java
private static URI toUri(URL url) { try {/*from w ww . j a va 2 s .c om*/ return url.toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
From source file:edu.washington.cs.mystatus.odk.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// ww w .j a v a 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); 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? MyStatus.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(); 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.koboc.collect.android.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 w w 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); 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? Collect.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(); 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:com.mpower.daktar.android.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 w ww.j a va2 s .c om * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(final String urlString, final HttpContext localContext, final HttpClient httpclient, final String auth) { URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + "while accessing" + urlString, 0); } // set up request... final HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth); HttpResponse response = null; try { response = httpclient.execute(req, localContext); final int statusCode = response.getStatusLine().getStatusCode(); final HttpEntity entity = response.getEntity(); if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase() .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) { try { // don't really care about the stream... final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final Exception e) { e.printStackTrace(); } } if (statusCode != 200) { final String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { final String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { final 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(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); final KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); } finally { if (isr != null) { try { isr.close(); } catch (final Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (final Exception e) { // no-op } } } } catch (final Exception e) { e.printStackTrace(); final String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; final Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; final StringBuilder b = new StringBuilder(); for (final 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 (final Exception e) { e.printStackTrace(); String cause; if (e.getCause() != null) { cause = e.getCause().getMessage(); } else { cause = e.getMessage(); } final String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:com.googlecode.jsonschema2pojo.integration.util.CodeGenerationHelper.java
/** * Invokes the jsonschema2pojo plugin to generate Java types from a given * schema./*from ww w .j av a2s .c o m*/ * * @param schema * a classpath resource to be used as the input JSON Schema * @param targetPackage * the default target package for generated classes * @param configValues * the generation config options and values that should be set on * the maven plugin before invoking it */ public static File generate(final URL schema, final String targetPackage, final Map<String, Object> configValues) { final File outputDirectory = createTemporaryOutputFolder(); try { Jsonschema2PojoMojo pluginMojo = new TestableJsonschema2PojoMojo() .configure(new HashMap<String, Object>() { { put("sourceDirectory", new File(schema.toURI())); put("outputDirectory", outputDirectory); put("project", getMockProject()); put("targetPackage", targetPackage); putAll(configValues); } }); pluginMojo.execute(); } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (MojoExecutionException e) { throw new RuntimeException(e); } catch (DependencyResolutionRequiredException e) { throw new RuntimeException(e); } return outputDirectory; }
From source file:cd.education.data.collector.android.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 av a 2 s . co 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? Collect.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:eionet.cr.util.URLUtil.java
/** * * @param urlString/* w w w.j a va 2 s.com*/ * @return */ public static String normalizeUrl(String urlString) { // if given URL string is null, return it as it is if (urlString == null) { return urlString; } // we're going to need both the URL and URI wrappers URL url = null; URI uri = null; try { url = new URL(urlString.trim()); uri = url.toURI(); } catch (MalformedURLException e) { return urlString; } catch (URISyntaxException e) { return urlString; } // get all the various parts of this URL String protocol = url.getProtocol(); String userInfo = url.getUserInfo(); String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); String query = url.getQuery(); String reference = url.getRef(); // start building the result, processing each of the above-found URL parts StringBuilder result = new StringBuilder(); try { if (!StringUtils.isEmpty(protocol)) { result.append(decodeEncode(protocol.toLowerCase())).append("://"); } if (!StringUtils.isEmpty(userInfo)) { result.append(decodeEncode(userInfo, ":")).append("@"); } if (!StringUtils.isEmpty(host)) { result.append(decodeEncode(host.toLowerCase())); } if (port != -1 && port != 80) { result.append(":").append(port); } if (!StringUtils.isEmpty(path)) { result.append(normalizePath(path)); } if (!StringUtils.isEmpty(query)) { String normalizedQuery = normalizeQueryString(uri); if (!StringUtils.isBlank(normalizedQuery)) { result.append("?").append(normalizedQuery); } } if (!StringUtils.isEmpty(reference)) { result.append("#").append(decodeEncode(reference)); } } catch (UnsupportedEncodingException e) { throw new CRRuntimeException("Unsupported encoding: " + e.getMessage(), e); } return result.toString(); }
From source file:net.pms.external.ExternalFactory.java
private static File url2file(URL url) { File f;/* w w w. j a v a 2 s. com*/ try { f = new File(url.toURI()); } catch (URISyntaxException e) { f = new File(url.getPath()); } return f; }
From source file:jenkins.model.RunIdMigrator.java
private static String getUnmigrationCommandLine(File jenkinsHome) { StringBuilder cp = new StringBuilder(); for (Class<?> c : new Class<?>[] { RunIdMigrator.class, /* TODO how to calculate transitive dependencies automatically? */Charsets.class, WriterOutputStream.class, BuildException.class, FastDateFormat.class }) { URL location = c.getProtectionDomain().getCodeSource().getLocation(); String locationS = location.toString(); if (location.getProtocol().equals("file")) { try { locationS = new File(location.toURI()).getAbsolutePath(); } catch (URISyntaxException x) { // never mind }//from w ww .ja va 2 s .c o m } if (cp.length() > 0) { cp.append(File.pathSeparator); } cp.append(locationS); } return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome); }
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
private static File locateBootstrapperFile() { ProtectionDomain protectionDomain = Bootstrapper.class.getProtectionDomain(); if (protectionDomain == null) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (ProtectionDomain was null)"); throw new RuntimeException(); }/*from www . j ava 2 s . c om*/ CodeSource codeSource = protectionDomain.getCodeSource(); if (codeSource == null) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (CodeSource was null)"); throw new RuntimeException(); } URL url = codeSource.getLocation(); if (url == null) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (Location was null)"); throw new RuntimeException(); } try { URI uri = url.toURI(); File file = new File(uri.getPath()); if (file.isDirectory()) { if (!Boolean.getBoolean("com.heliosdecompiler.isDebugging")) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File is directory)"); throw new RuntimeException(file.getAbsolutePath()); } else { System.out.println( "Warning: Could not locate bootstrapper but com.heliosdecompiler.isDebugging was set to true"); } } else if (!file.exists()) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File does not exist)"); throw new RuntimeException(); } else if (!file.canRead()) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File is not readable)"); throw new RuntimeException(); } return file; } catch (URISyntaxException e) { JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (URISyntaxException)"); throw new RuntimeException(); } }