PageRenderTime 1309ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Core/org/objectweb/proactive/core/util/URIBuilder.java

https://bitbucket.org/lp/programming-multiactivities
Java | 436 lines | 228 code | 47 blank | 161 comment | 33 complexity | 0bd56945410e12ab818eff98e949f697 MD5 | raw file
  1. /*
  2. * ################################################################
  3. *
  4. * ProActive Parallel Suite(TM): The Java(TM) library for
  5. * Parallel, Distributed, Multi-Core Computing for
  6. * Enterprise Grids & Clouds
  7. *
  8. * Copyright (C) 1997-2012 INRIA/University of
  9. * Nice-Sophia Antipolis/ActiveEon
  10. * Contact: proactive@ow2.org or contact@activeeon.com
  11. *
  12. * This library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Affero General Public License
  14. * as published by the Free Software Foundation; version 3 of
  15. * the License.
  16. *
  17. * This library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this library; if not, write to the Free Software
  24. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  25. * USA
  26. *
  27. * If needed, contact us to obtain a release under GPL Version 2 or 3
  28. * or a different license than the AGPL.
  29. *
  30. * Initial developer(s): The ProActive Team
  31. * http://proactive.inria.fr/team_members.htm
  32. * Contributor(s):
  33. *
  34. * ################################################################
  35. * $$PROACTIVE_INITIAL_DEV$$
  36. */
  37. package org.objectweb.proactive.core.util;
  38. import java.net.InetAddress;
  39. import java.net.URI;
  40. import java.net.URISyntaxException;
  41. import java.net.UnknownHostException;
  42. import org.apache.log4j.Logger;
  43. import org.objectweb.proactive.core.Constants;
  44. import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
  45. import org.objectweb.proactive.core.remoteobject.AbstractRemoteObjectFactory;
  46. import org.objectweb.proactive.core.remoteobject.RemoteObjectFactory;
  47. import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException;
  48. import org.objectweb.proactive.core.util.log.Loggers;
  49. import org.objectweb.proactive.core.util.log.ProActiveLogger;
  50. /**
  51. * This class is a utility class to perform modifications and operations on urls.
  52. */
  53. public class URIBuilder {
  54. private static String[] LOCAL_URLS = { "", "localhost.localdomain", "localhost", "127.0.0.1" };
  55. static Logger logger = ProActiveLogger.getLogger(Loggers.UTIL);
  56. //
  57. //-------------------Public methods-------------------------
  58. //
  59. /**
  60. * Checks if the given url is well-formed
  61. * @param url the url to check
  62. * @return The url if well-formed
  63. * @throws URISyntaxException if the url is not well-formed
  64. */
  65. public static URI checkURI(String url) throws URISyntaxException {
  66. URI u = new URI(url);
  67. String hostname;
  68. try {
  69. hostname = fromLocalhostToHostname(u.getHost());
  70. URI u2 = buildURI(hostname, u.getPath(), u.getScheme(), u.getPort());
  71. return u2;
  72. } catch (UnknownHostException e) {
  73. throw new URISyntaxException(url, "host unknow");
  74. }
  75. }
  76. /**
  77. * returns a new URI where the name part has been set to name
  78. * @param baseURI the base URI
  79. * @param name the new name
  80. * @return the new URI which the new name part
  81. */
  82. public static URI buildURI(URI baseURI, String name) {
  83. return buildURI(getHostNameFromUrl(baseURI), name, getProtocol(baseURI), getPortNumber(baseURI),
  84. false);
  85. }
  86. /**
  87. * Returns an url compliant with RFC 2396 [protocol:][//host][[/]path]
  88. * loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
  89. * @param host Url's hostname
  90. * @param name Url's Path
  91. * @param protocol Url's protocol
  92. * @throws UnknownProtocolException
  93. * @returnan url under the form [protocol:][//host][[/]name]
  94. */
  95. public static URI buildURI(String host, String name, String protocol) {
  96. try {
  97. RemoteObjectFactory rof = AbstractRemoteObjectFactory.getRemoteObjectFactory(protocol);
  98. return buildURI(host, name, protocol, rof.getPort());
  99. } catch (UnknownProtocolException e) {
  100. e.printStackTrace();
  101. }
  102. return null;
  103. }
  104. /**
  105. * Returns an url compliant with RFC 2396[//host][[/]path]
  106. * loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
  107. * @param host Url's hostname
  108. * @param name Url's Path
  109. * @throws UnknownProtocolException
  110. * @returnan url under the form [//host][[/]name]
  111. */
  112. public static URI buildURI(String host, String name) {
  113. return buildURI(host, name, null);
  114. }
  115. /**
  116. * Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]path]
  117. * loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
  118. * @param host Url's hostname
  119. * @param name Url's Path
  120. * @param protocol Url's protocol
  121. * @param port Url's port
  122. * @returnan url under the form [protocol:][//host[:port]][[/]name]
  123. */
  124. public static URI buildURI(String host, String name, String protocol, int port) {
  125. return buildURI(host, name, protocol, port, false);
  126. }
  127. /**
  128. * Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]name]
  129. * @param host Url's hostname
  130. * @param name Url's Path
  131. * @param protocol Url's protocol
  132. * @param port Url's port
  133. * @param replaceHost indicate if internal hooks regarding how to resolve the hostname have to be used
  134. * @see #fromLocalhostToHostname(String localName)
  135. * @see #getHostNameorIP(InetAddress address)
  136. * @returnan url under the form [protocol:][//host[:port]][[/]name]
  137. */
  138. public static URI buildURI(String host, String name, String protocol, int port, boolean replaceHost) {
  139. // if (protocol == null) {
  140. // protocol = System.getProperty(Constants.PROPERTY_PA_COMMUNICATION_PROTOCOL);
  141. // }
  142. if (port == 0) {
  143. port = -1;
  144. }
  145. try {
  146. if (replaceHost) {
  147. host = fromLocalhostToHostname(host);
  148. }
  149. if ((name != null) && (!name.startsWith("/"))) {
  150. /* URI does not require a '/' at the beginning of the name like URLs. As we cannot use
  151. * URL directly (because we do not want to register a URL handler), we do this ugly hook.
  152. */
  153. name = "/" + name;
  154. }
  155. return new URI(protocol, null, host, port, name, null, null);
  156. } catch (URISyntaxException e) {
  157. e.printStackTrace();
  158. } catch (UnknownHostException e) {
  159. e.printStackTrace();
  160. }
  161. return null;
  162. }
  163. public static URI setProtocol(URI uri, String protocol) {
  164. try {
  165. return new URI(protocol, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri
  166. .getQuery(), uri.getFragment());
  167. } catch (URISyntaxException e) {
  168. e.printStackTrace();
  169. }
  170. return null;
  171. }
  172. /**
  173. * This method build an url in the form protocol://host:port/name where the port
  174. * and protocol are retrieved from system properties
  175. * @param host
  176. * @param name
  177. * @return an Url built from properties
  178. */
  179. public static URI buildURIFromProperties(String host, String name) {
  180. int port = -1;
  181. String protocol = CentralPAPropertyRepository.PA_COMMUNICATION_PROTOCOL.getValue();
  182. try {
  183. // ok, awful hack but ensures that the factory for the given
  184. // protocol has effectively been loaded by the classloader
  185. // and that the initialization process has been performed
  186. RemoteObjectFactory rof = AbstractRemoteObjectFactory.getRemoteObjectFactory(protocol);
  187. port = rof.getPort();
  188. } catch (UnknownProtocolException e) {
  189. logger.debug(e.getMessage());
  190. }
  191. if (port == -1) {
  192. return buildURI(host, name, protocol);
  193. } else {
  194. return buildURI(host, name, protocol, port);
  195. }
  196. }
  197. /**
  198. * build a virtual node url from a given url
  199. * @param uri
  200. * @return
  201. * @throws java.net.UnknownHostException if no network interface was found
  202. */
  203. public static URI buildVirtualNodeUrl(URI uri) {
  204. String vnName = getNameFromURI(uri);
  205. vnName = vnName.concat("_VN");
  206. String host = getHostNameFromUrl(uri);
  207. String protocol = uri.getScheme();
  208. int port = uri.getPort();
  209. return buildURI(host, vnName, protocol, port);
  210. }
  211. /**
  212. * build a virtual node url from a given url
  213. * @param url
  214. * @return
  215. * @throws java.net.UnknownHostException if no network interface was found
  216. */
  217. public static URI buildVirtualNodeUrl(String url) {
  218. return buildVirtualNodeUrl(URI.create(url));
  219. }
  220. public static String appendVnSuffix(String name) {
  221. return name.concat("_VN");
  222. }
  223. public static String removeVnSuffix(String url) {
  224. int index = url.lastIndexOf("_VN");
  225. if (index == -1) {
  226. return url;
  227. }
  228. return url.substring(0, index);
  229. }
  230. /**
  231. * Returns the name included in the url
  232. * @param uri
  233. * @return the name included in the url
  234. */
  235. public static String getNameFromURI(URI u) {
  236. String path = u.getPath();
  237. if ((path != null) && (path.startsWith("/"))) {
  238. // remove the intial '/'
  239. return path.substring(1);
  240. }
  241. return path;
  242. }
  243. public static String getNameFromURI(String url) {
  244. URI uri = URI.create(url);
  245. return getNameFromURI(uri);
  246. }
  247. /**
  248. * Return the protocol specified in the string
  249. * The same convention as in URL is used
  250. */
  251. public static String getProtocol(URI uri) {
  252. String protocol = uri.getScheme();
  253. if (protocol == null) {
  254. return Constants.DEFAULT_PROTOCOL_IDENTIFIER;
  255. }
  256. return protocol;
  257. }
  258. public static String getProtocol(String url) {
  259. URI uri = URI.create(url);
  260. return getProtocol(uri);
  261. }
  262. /**
  263. * Returns the url without protocol
  264. */
  265. public static URI removeProtocol(URI uri) {
  266. return buildURI(getHostNameFromUrl(uri), uri.getPath(), null, uri.getPort(), false);
  267. }
  268. public static URI removeProtocol(String url) {
  269. URI uri = URI.create(url);
  270. return removeProtocol(uri);
  271. }
  272. public static String getHostNameFromUrl(URI uri) {
  273. return uri.getHost();
  274. }
  275. public static String getHostNameFromUrl(String url) {
  276. URI uri = URI.create(url);
  277. return getHostNameFromUrl(uri);
  278. }
  279. public static String removePortFromHost(String hostname) {
  280. try {
  281. URI uri = new URI(hostname);
  282. return uri.getHost();
  283. } catch (URISyntaxException e) {
  284. e.printStackTrace();
  285. return hostname;
  286. }
  287. }
  288. /**
  289. * this method returns the hostname or the IP address associated to the InetAddress address parameter.
  290. * It is possible to set
  291. * {@code "proactive.hostname"} property (evaluated in that order) to override the default java behaviour
  292. * of resolving InetAddress
  293. * @param address any InetAddress
  294. * @return a String matching the corresponding InetAddress
  295. */
  296. public static String getHostNameorIP(InetAddress address) {
  297. // address = UrlBuilder.getNetworkInterfaces();
  298. if (CentralPAPropertyRepository.PA_HOSTNAME.getValue() != null) {
  299. return CentralPAPropertyRepository.PA_HOSTNAME.getValue();
  300. }
  301. String temp = "";
  302. if (CentralPAPropertyRepository.PA_NET_USE_IP_ADDRESS.isTrue()) {
  303. temp = (address).getHostAddress();
  304. } else {
  305. temp = address.getCanonicalHostName();
  306. }
  307. return URIBuilder.ipv6withoutscope(temp);
  308. }
  309. /**
  310. * evaluate if localName is a loopback entry, if yes calls {@link getHostNameorIP(InetAddress address)}
  311. * @param localName
  312. * @return a remotely accessible host name if exists
  313. * @throws UnknownHostException if no network interface was found
  314. * @see getHostNameorIP(InetAddress address)
  315. */
  316. public static String fromLocalhostToHostname(String localName) throws UnknownHostException {
  317. if (localName == null) {
  318. localName = "localhost";
  319. }
  320. java.net.InetAddress hostInetAddress = ProActiveInet.getInstance().getInetAddress();
  321. for (int i = 0; i < LOCAL_URLS.length; i++) {
  322. if (LOCAL_URLS[i].startsWith(localName.toLowerCase())) {
  323. return URIBuilder.getHostNameorIP(hostInetAddress);
  324. }
  325. }
  326. return localName;
  327. }
  328. /**
  329. * This method extract the port from a string in the form host:port or host
  330. * @param url
  331. * @return port number or 0 if there is no port
  332. */
  333. public static int getPortNumber(String url) {
  334. URI uri = URI.create(url);
  335. return getPortNumber(uri);
  336. }
  337. public static int getPortNumber(URI uri) {
  338. if (uri.getPort() != -1) {
  339. return uri.getPort();
  340. }
  341. return 0;
  342. }
  343. /**
  344. * change the port of a given url
  345. * @param uri the url to change the port
  346. * @param port the new port number
  347. * @return the url with the new port
  348. */
  349. public static URI setPort(URI u, int port) {
  350. URI u2;
  351. try {
  352. u2 = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), port, u.getPath(), u.getQuery(), u
  353. .getFragment());
  354. return u2;
  355. } catch (URISyntaxException e) {
  356. e.printStackTrace();
  357. }
  358. return u;
  359. }
  360. public static String ipv6withoutscope(String address) {
  361. String name = address;
  362. int indexPercent = name.indexOf('%');
  363. if (indexPercent != -1) {
  364. return "[" + name.substring(0, indexPercent) + "]";
  365. } else {
  366. return address;
  367. }
  368. }
  369. public static String ipv6withoutscope(InetAddress address) {
  370. String name = address.getHostAddress();
  371. int indexPercent = name.indexOf('%');
  372. if (indexPercent != -1) {
  373. return "[" + name.substring(0, indexPercent) + "]";
  374. } else {
  375. return name;
  376. }
  377. }
  378. public static String removeUsername(String url) {
  379. //this method is used to extract the username, that might be necessary for the callback
  380. //it updates the hostable.
  381. int index = url.indexOf("@");
  382. if (index >= 0) {
  383. String username = url.substring(0, index);
  384. url = url.substring(index + 1, url.length());
  385. HostsInfos.setUserName(getHostNameFromUrl(url), username);
  386. }
  387. return url;
  388. }
  389. }