List of usage examples for java.net URL getProtocol
public String getProtocol()
From source file:Main.java
/** * Convert from a <code>URL</code> to a <code>File</code>. * <p/>/* w w w . j a v a 2 s . c o m*/ * From version 1.1 this method will decode the URL. * Syntax such as <code>file:///my%20docs/file.txt</code> will be * correctly decoded to <code>/my docs/file.txt</code>. Starting with version * 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. * Additionally, malformed percent-encoded octets are handled leniently by * passing them through literally. * * @param url the file URL to convert, {@code null} returns {@code null} * @return the equivalent <code>File</code> object, or {@code null} * if the URL's protocol is not <code>file</code> */ public static File toFile(URL url) { if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { return null; } else { String filename = url.getFile().replace('/', File.separatorChar); filename = decodeUrl(filename); return new File(filename); } }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.HttpUtils.java
/** * @param config Gerrit Server Configuration. * @param url URL to get./*from www. jav a 2s. co m*/ * @return httpresponse. * @throws IOException if found. */ public static HttpResponse performHTTPGet(IGerritHudsonTriggerConfig config, String url) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) { try { URL proxyUrl = new URL(config.getGerritProxy()); HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); } } httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials()); HttpResponse execute; return httpclient.execute(httpGet); }
From source file:URLUtils.java
/** * normalize an URL,// w w w. ja v a 2s. c o m * * @param u, * the URL to normalize * @return a new URL, the normalized version of the parameter, or the u URL, * if something failed in the process */ public static URL normalize(URL u) { String proto = u.getProtocol().toLowerCase(); String host = u.getHost().toLowerCase(); int port = u.getPort(); if (port != -1) { if (url_defport != null) { try { int udp; udp = ((Integer) url_defport.invoke(u, (Object[]) null)).intValue(); // we have the default, skip the port part if (udp == port) { port = -1; } } catch (InvocationTargetException ex) { } catch (IllegalAccessException iex) { } } else { switch (port) { case 21: if (proto.equals("ftp")) { port = -1; } break; case 80: if (proto.equals("http")) { port = -1; } break; case 443: if (proto.equals("https")) { port = -1; } break; } } } try { URL _nu; if (port == -1) { _nu = new URL(proto, host, u.getFile()); } else { _nu = new URL(proto, host, port, u.getFile()); } return _nu; } catch (MalformedURLException ex) { } return u; }
From source file:com.magnet.plugin.helpers.UrlParser.java
public static ParsedUrl parseUrl(String url) { List<PathPart> pathParts = new ArrayList<PathPart>(); List<Query> queries = new ArrayList<Query>(); ParsedUrl parsedUrl;/*from w w w . j a v a 2s .c o m*/ String base; try { URL aURL = new URL(url); base = aURL.getAuthority(); String protocol = aURL.getProtocol(); parsedUrl = new ParsedUrl(); parsedUrl.setPathWithEndingSlash(aURL.getPath().endsWith("/")); parsedUrl.setBase(protocol + "://" + base); List<NameValuePair> pairs = URLEncodedUtils.parse(aURL.getQuery(), Charset.defaultCharset()); for (NameValuePair pair : pairs) { Query query = new Query(pair.getName(), pair.getValue()); queries.add(query); } parsedUrl.setQueries(queries); String[] pathStrings = aURL.getPath().split("/"); for (String pathPart : pathStrings) { Matcher m = PATH_PARAM_PATTERN.matcher(pathPart); if (m.find()) { String paramDef = m.group(1); String[] paramParts = paramDef.split(":"); if (paramParts.length > 1) { pathParts.add(new PathPart(paramParts[1].trim(), paramParts[0].trim())); } else { pathParts.add(new PathPart(paramParts[0].trim())); } } else { if (!pathPart.isEmpty()) { pathParts.add(new PathPart(pathPart)); } } } parsedUrl.setPathParts(pathParts); } catch (Exception ex) { Logger.error(UrlParser.class, "Can't parse URL " + url); return null; } return parsedUrl; }
From source file:com.magnet.plugin.r2m.helpers.UrlParser.java
public static ParsedUrl parseUrl(String url) { List<PathPart> pathParts = new ArrayList<PathPart>(); List<Query> queries = new ArrayList<Query>(); ParsedUrl parsedUrl;/*w w w . j a v a2 s. co m*/ String base; try { URL aURL = new URL(url); base = aURL.getAuthority(); String protocol = aURL.getProtocol(); parsedUrl = new ParsedUrl(); parsedUrl.setPathWithEndingSlash(aURL.getPath().endsWith("/")); parsedUrl.setBaseUrl(protocol + "://" + base); List<NameValuePair> pairs = URLEncodedUtils.parse(aURL.getQuery(), Charset.defaultCharset()); for (NameValuePair pair : pairs) { Query query = new Query(pair.getName(), pair.getValue()); queries.add(query); } parsedUrl.setQueries(queries); String[] pathStrings = aURL.getPath().split("/"); for (String pathPart : pathStrings) { Matcher m = PATH_PARAM_PATTERN.matcher(pathPart); if (m.find()) { String paramDef = m.group(1); String[] paramParts = paramDef.split(":"); if (paramParts.length > 1) { pathParts.add(new PathPart(paramParts[1].trim(), paramParts[0].trim())); } else { pathParts.add(new PathPart(paramParts[0].trim())); } } else { if (!pathPart.isEmpty()) { pathParts.add(new PathPart(pathPart)); } } } parsedUrl.setPathParts(pathParts); } catch (Exception ex) { Logger.error(UrlParser.class, R2MMessages.getMessage("CANNOT_PARSE_URL", url)); return null; } return parsedUrl; }
From source file:it.govpay.web.console.utils.HttpClientUtils.java
public static HttpResponse getEsitoPagamento(String urlToInvoke, Logger log) throws Exception { HttpResponse responseGET = null;/*from w w w . j a va 2 s . co m*/ try { log.debug("Richiesta Esito del pagamento in corso..."); URL urlObj = new URL(urlToInvoke); HttpHost target = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol()); CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); HttpGet richiestaPost = new HttpGet(); richiestaPost.setURI(urlObj.toURI()); log.debug("Invio tramite client Http in corso..."); responseGET = client.execute(target, richiestaPost); if (responseGET == null) throw new NullPointerException("La Response HTTP e' null"); log.debug("Invio tramite client Http completato."); return responseGET; } catch (Exception e) { log.error("Errore durante l'invio della richiesta di pagamento: " + e.getMessage(), e); throw e; } }
From source file:com.ibm.jaggr.core.util.PathUtil.java
/** * Convenience method to convert a URL to a URI that doesn't throw a * URISyntaxException if the path component for the URL contains * spaces (like {@link URL#toURI()} does). * * @param url The input URL// w w w .java2s . co m * @return The URI * @throws URISyntaxException */ public static URI url2uri(URL url) throws URISyntaxException { return new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef()); }
From source file:com.us.util.FileHelper.java
/** * /*ww w. j a va 2 s.co m*/ * * @param packName ?? * @param fileName ?? * @return */ public static InputStream getFileInPackage(String packName, String fileName) { try { String packdir = packName.replace('.', '/'); Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packdir); while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); if (url.getProtocol().equals("file")) { String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); return new FileInputStream(filePath + "/" + fileName); } else if (url.getProtocol().equals("jar")) { return FileHelper.class.getClassLoader() .getResourceAsStream(packdir.concat("/").concat(fileName)); } } } catch (IOException e) { throw UsMsgException.newInstance(String.format(":%s.%s", packName, fileName), e); } return null; }
From source file:it.govpay.web.console.utils.HttpClientUtils.java
public static HttpResponse sendRichiestaPagamento(String urlToInvoke, RichiestaPagamento richiestaPagamento, Logger log) throws Exception { HttpResponse responseGET = null;// www. jav a2 s .c o m try { log.debug("Invio del pagamento in corso..."); URL urlObj = new URL(urlToInvoke); HttpHost target = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol()); CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); HttpPost richiestaPost = new HttpPost(); richiestaPost.setURI(urlObj.toURI()); log.debug("Serializzazione pagamento in corso..."); byte[] bufferPagamento = JaxbUtils.toBytes(richiestaPagamento); log.debug("Serializzazione pagamento completata."); HttpEntity bodyEntity = new InputStreamEntity(new ByteArrayInputStream(bufferPagamento), ContentType.APPLICATION_XML); richiestaPost.setEntity(bodyEntity); richiestaPost.setHeader("Content-Type", ContentType.APPLICATION_XML.getMimeType()); log.debug("Invio tramite client Http in corso..."); responseGET = client.execute(target, richiestaPost); if (responseGET == null) throw new NullPointerException("La Response HTTP e' null"); log.debug("Invio tramite client Http completato."); return responseGET; } catch (Exception e) { log.error("Errore durante l'invio della richiesta di pagamento: " + e.getMessage(), e); throw e; } }
From source file:Main.java
/** * Make a URL from the given string./*from w w w .j a v a 2s . c o m*/ * * <p> * If the string is a properly formatted file URL, then the file * portion will be made canonical. * * <p> * If the string is an invalid URL then it will be converted into a * file URL. * * @param urlspec The string to construct a URL for. * @param relativePrefix The string to prepend to relative file * paths, or null to disable prepending. * @return A URL for the given string. * * @throws MalformedURLException Could not make a URL for the given string. */ public static URL toURL(String urlspec, final String relativePrefix) throws MalformedURLException { urlspec = urlspec.trim(); URL url; try { url = new URL(urlspec); if (url.getProtocol().equals("file")) { url = makeURLFromFilespec(url.getFile(), relativePrefix); } } catch (Exception e) { // make sure we have a absolute & canonical file url try { url = makeURLFromFilespec(urlspec, relativePrefix); } catch (IOException n) { // // jason: or should we rethrow e? // throw new MalformedURLException(n.toString()); } } return url; }