PageMapper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. //
  2. // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
  3. //
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. //
  24. using System;
  25. using System.Xml;
  26. using System.IO;
  27. using System.Collections;
  28. using System.Web.Compilation;
  29. using System.Collections.Specialized;
  30. using System.Threading;
  31. using vmw.common;
  32. using System.Reflection;
  33. namespace System.Web.J2EE
  34. {
  35. /// <summary>
  36. /// Class that allows reading assemblies.xml file for getting information about different types.
  37. /// </summary>
  38. public class PageMapper
  39. {
  40. private static readonly string _fileListName = "/filelist.xml";
  41. private static readonly object LOCK_GETASSEMBLIESCACHEDDOCUMENT = new object();
  42. private static readonly object LOCK_GETFROMMAPPATHCACHE = new object();
  43. public static string GetFromMapPathCache(string key)
  44. {
  45. Hashtable answer = null;
  46. lock(LOCK_GETFROMMAPPATHCACHE)
  47. {
  48. answer = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.MAP_PATH_CACHE);
  49. if (answer == null)
  50. {
  51. answer = new Hashtable();
  52. CachedDocumentTypeStorage storage = (CachedDocumentTypeStorage)GetAssembliesCachedDocument();
  53. IDictionaryEnumerator e = storage.GetEnumerator();
  54. e.Reset();
  55. while (e.MoveNext())
  56. {
  57. string currentFile = (string)((DictionaryEntry)e.Current).Key;
  58. answer[currentFile]= IAppDomainConfig.WAR_ROOT_SYMBOL + currentFile;
  59. }
  60. AppDomain.CurrentDomain.SetData(J2EEConsts.MAP_PATH_CACHE,answer);
  61. }
  62. }
  63. return (string)answer[key];
  64. }
  65. // UNUSED METHOD
  66. //The method was used by runtime to force file names casesensitivity
  67. // problem. The filelist.xml file should contain correct file names,
  68. // but currently it is unused
  69. public static void LoadFileList()
  70. {
  71. Hashtable hashTable = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.FILE_LIST_FILE);
  72. if (hashTable == null)
  73. {
  74. XmlDocument doc;
  75. try
  76. {
  77. Stream fs = (Stream)IOUtils.getStream(_fileListName);
  78. if (fs == null)
  79. {
  80. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  81. return;
  82. }
  83. doc = new XmlDocument();
  84. doc.Load(fs);
  85. }
  86. catch (Exception)
  87. {
  88. // Console.WriteLine("filelist.xml was not found!!!");
  89. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  90. return;
  91. }
  92. // Console.WriteLine("filelist.xml was found!!!");
  93. if (doc != null && doc.DocumentElement.HasChildNodes)
  94. {
  95. hashTable = CollectionsUtil.CreateCaseInsensitiveHashtable();
  96. XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
  97. for (int i = 0;i < nodeList.Count ; i++)
  98. {
  99. string fileName = nodeList.Item(i).InnerText;
  100. hashTable.Add(fileName,fileName);
  101. }
  102. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, hashTable);
  103. }
  104. }
  105. }
  106. private static ICachedXmlDoc GetAssembliesCachedDocument()
  107. {
  108. lock(LOCK_GETASSEMBLIESCACHEDDOCUMENT)
  109. {
  110. ICachedXmlDoc doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData(J2EEConsts.ASSEMBLIES_FILE);
  111. if (doc == null)
  112. {
  113. doc = CreateDocument();
  114. if (doc != null)
  115. AppDomain.CurrentDomain.SetData(J2EEConsts.ASSEMBLIES_FILE, doc);
  116. }
  117. return doc;
  118. }
  119. }
  120. private static String NormalizeName(string url)
  121. {
  122. #if NET_2_0
  123. url = System.Web.Util.UrlUtils.RemoveDoubleSlashes(url);
  124. #endif
  125. if (url.StartsWith(IAppDomainConfig.WAR_ROOT_SYMBOL))
  126. url = url.Substring(IAppDomainConfig.WAR_ROOT_SYMBOL.Length);
  127. return url;
  128. }
  129. private static ICachedXmlDoc CreateDocument()
  130. {
  131. return new CachedDocumentTypeStorage();
  132. }
  133. public static Type GetObjectType(string url)
  134. {
  135. return GetCachedType(NormalizeName(url));
  136. }
  137. public static Assembly GetObjectAssembly(string url)
  138. {
  139. return GetCachedAssembly(NormalizeName(url));
  140. }
  141. private static Assembly GetCachedAssembly(string url)
  142. {
  143. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  144. Assembly t = doc.GetAssembly(url);
  145. if (t == null)
  146. throw new HttpException(404, "The requested resource (" + url + ") is not available.");
  147. return t;
  148. }
  149. private static Type GetCachedType(string url)
  150. {
  151. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  152. Type t = doc.GetType(url);
  153. if (t == null)
  154. throw new HttpException(404,"The requested resource (" + url + ") is not available.");
  155. return t;
  156. }
  157. #region ICachedXmlDoc interface
  158. interface ICachedXmlDoc
  159. {
  160. Type GetType(string key);
  161. Assembly GetAssembly(string key);
  162. }
  163. #endregion
  164. #region CachedDocumentTypeStorage class
  165. class CachedDocumentTypeStorage : ICachedXmlDoc
  166. {
  167. private static readonly object _fuse = new object();
  168. public static readonly ICachedXmlDoc DEFAULT_DOC =
  169. new CachedDocumentTypeStorage(0);
  170. private static readonly int DEFAULT_PAGES_NUMBER = 25;
  171. private Hashtable _table;
  172. private CachedDocumentTypeStorage(int initTableSize)
  173. {
  174. _table = Hashtable.Synchronized(new Hashtable(initTableSize));
  175. }
  176. public CachedDocumentTypeStorage() :
  177. this(DEFAULT_PAGES_NUMBER)
  178. {}
  179. Type ICachedXmlDoc.GetType(string o)
  180. {
  181. return GetMetaByURL(o).Type;
  182. }
  183. Assembly ICachedXmlDoc.GetAssembly(string o)
  184. {
  185. return GetMetaByURL(o).Assembly;
  186. }
  187. internal IDictionaryEnumerator GetEnumerator()
  188. {
  189. return _table.GetEnumerator();
  190. }
  191. //rewamped for perfomance reasons
  192. //It looks like issue is not important in development mode,
  193. //but only will became important in production mode when dynamyc compilation will be enabled
  194. //Anyway, locking whole table and compiling under lock looks odd
  195. //spivak.December 07 2006
  196. public MetaProvider GetMetaByURL(string url)
  197. {
  198. #if !NO_GLOBAL_LOCK_ON_COMPILE
  199. string lwUrl = url.ToLower();
  200. lock (_table)
  201. {
  202. object retVal = _table[lwUrl];
  203. if (retVal == null)
  204. {
  205. retVal = PageCompiler.GetCompiler(url);
  206. _table[lwUrl] = retVal;
  207. }
  208. return (MetaProvider)retVal;
  209. }
  210. #else
  211. string lwUrl = url.ToLower();
  212. if (!_table.ContainsKey(lwUrl))
  213. {
  214. lock (_table.SyncRoot)
  215. {
  216. if (_table.ContainsKey(lwUrl))
  217. goto Fused;
  218. _table[lwUrl] = _fuse;
  219. }
  220. try
  221. {
  222. MetaProvider meta = PageCompiler.GetCompiler(url);
  223. lock (_table.SyncRoot)
  224. {
  225. return (MetaProvider)(_table[lwUrl] = meta);
  226. }
  227. }
  228. catch(Exception e)
  229. {
  230. _table.Remove(lwUrl);
  231. }
  232. }
  233. Fused:
  234. while (_table[lwUrl] == _fuse)
  235. Thread.Sleep(10);
  236. return !_table.ContainsKey(lwUrl)? PageCompiler.Error: (MetaProvider)_table[lwUrl];
  237. #endif
  238. }
  239. }
  240. #endregion
  241. }
  242. public interface MetaProvider
  243. {
  244. Type Type { get;}
  245. Assembly Assembly {get;}
  246. }
  247. public class PageCompiler : MetaProvider
  248. {
  249. private static readonly string PAGE_XPATH = "preserve";
  250. private static readonly string ASSEM_ATTRIB_NAME = "assem";
  251. private static readonly string TYPE_ATTRIB_NAME = "type";
  252. private static string _parser = null;
  253. private static PageCompiler _errorProvider = new PageCompiler();
  254. private Type _type = null;
  255. private Assembly _assembly = null;
  256. private string _xmlDescriptor = null;
  257. private string _url = null;
  258. private string _session = null;
  259. PageCompiler(string url)
  260. {
  261. _url = url;
  262. _xmlDescriptor = GetDescFromUrl();
  263. _session = DateTime.Now.Ticks.ToString();
  264. LoadTypeAndAssem();
  265. }
  266. PageCompiler()
  267. {
  268. }
  269. public static PageCompiler Error
  270. {
  271. get
  272. {
  273. return _errorProvider;
  274. }
  275. }
  276. public static PageCompiler GetCompiler(string url)
  277. {
  278. try{
  279. return new PageCompiler(url);
  280. }
  281. catch(Exception e)
  282. {
  283. return Error;
  284. }
  285. }
  286. Type MetaProvider.Type
  287. {
  288. get{
  289. return _type;
  290. }
  291. }
  292. Assembly MetaProvider.Assembly
  293. {
  294. get{
  295. return _assembly;
  296. }
  297. }
  298. private void LoadTypeAndAssem()
  299. {
  300. if (_assembly == null)
  301. {
  302. string typeName = GetCachedTypeName();
  303. if (typeName != null)
  304. {
  305. if ((_type = Type.GetType(typeName)) != null)
  306. _assembly = _type.Assembly;
  307. else
  308. _assembly = Assembly.Load(typeName);
  309. }
  310. }
  311. }
  312. public string GetCachedTypeName()
  313. {
  314. string typeName = null;
  315. //if the desciptor exists in the war - get the type
  316. string descPath = String.Join("/", new string[]{"assemblies", _xmlDescriptor});
  317. try
  318. {
  319. #if DEBUG
  320. Console.WriteLine(descPath);
  321. #endif
  322. Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath);
  323. if (fs != null)
  324. {
  325. return GetTypeFromDescStream(fs);
  326. }
  327. }
  328. catch (Exception ex)
  329. {
  330. #if DEBUG
  331. Console.WriteLine(ex);
  332. #endif
  333. //desc not in the war
  334. //typeName = null;
  335. }
  336. //if (typeName != null)
  337. //{
  338. // _type = Type.GetType(typeName);
  339. // return _type;
  340. //}
  341. string fileName = Path.GetFileName(_url);
  342. if (fileName.ToLower() != "defaultwsdlhelpgenerator.aspx")
  343. {
  344. string fullFileName = (fileName.ToLower() == "global.asax") ? _url : HttpContext.Current.Request.MapPath(_url);
  345. #if DEBUG
  346. Console.WriteLine("fullFileName=" + fullFileName);
  347. #endif
  348. if ( File.Exists(fullFileName) || Directory.Exists(fullFileName)) {
  349. //type not found - run aspxparser
  350. string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
  351. if (J2EEUtils.RunProc(command) != 0)
  352. throw GetCompilerError();
  353. }
  354. else {
  355. string message = "The requested resource (" + _url + ") is not available.";
  356. throw new HttpException(404, message);
  357. }
  358. //if the desciptor exists in the real app dir - get the type
  359. try
  360. {
  361. StreamReader sr = new StreamReader(HttpContext.Current.Request.MapPath("/" + descPath));
  362. typeName = GetTypeFromDescStream(sr.BaseStream);
  363. sr.Close();
  364. return typeName;
  365. }
  366. catch (Exception ex)
  367. {
  368. Console.WriteLine(ex);
  369. throw ex;
  370. }
  371. }
  372. else
  373. typeName = "ASP.defaultwsdlhelpgenerator_jvm_aspx";
  374. //if (typeName != null)
  375. //{
  376. // _type = Type.GetType(typeName);
  377. // return _type;
  378. //}
  379. return null;
  380. }
  381. private string GetTypeFromDescStream(Stream fs)
  382. {
  383. if (fs != null)
  384. {
  385. XmlDocument descXml = new XmlDocument();
  386. descXml.Load(fs);
  387. string assem = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
  388. string shortType = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
  389. string typeName = String.Format("{0}, {1}",shortType,assem);
  390. fs.Close();
  391. return typeName;
  392. }
  393. return null;
  394. }
  395. private string[] GetParserCmd(bool globalAsax)
  396. {
  397. string[] cmd = null;
  398. if (globalAsax)
  399. {
  400. cmd = new string[4];
  401. cmd[3] = "/buildglobalasax";
  402. }
  403. else
  404. {
  405. cmd = new string[5];
  406. cmd[3] = "/aspxFiles:" + _url;
  407. cmd[4] = "/compilepages";
  408. }
  409. cmd[0] = GetParser();
  410. cmd[1] = "/session:" + _session;
  411. cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
  412. return cmd;
  413. }
  414. private string GetParser()
  415. {
  416. if (_parser == null)
  417. {
  418. StreamReader sr =
  419. File.OpenText(HttpContext.Current.Request.MapPath("/AspxParser.params"));
  420. _parser = sr.ReadLine();
  421. sr.Close();
  422. }
  423. return _parser;
  424. }
  425. private string GetDescFromUrl()
  426. {
  427. string fileName = Path.GetFileName(_url);
  428. if (fileName.ToLower() == "global.asax")
  429. return "global.asax.xml";
  430. string id = GetIdFromUrl(_url);
  431. string[] descName = new string[3] {fileName, id, ".xml"} ;
  432. return string.Concat(descName).ToLower();
  433. }
  434. private string GetIdFromUrl(string path)
  435. {
  436. path = path.Trim('/');
  437. string fileName = Path.GetFileName(path);
  438. string id = string.Empty;
  439. path = path.Substring (path.IndexOf ("/") + 1);
  440. if (path.Length > fileName.Length)
  441. id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
  442. return id;
  443. }
  444. private Exception GetCompilerError()
  445. {
  446. string _errFile = HttpContext.Current.Request.MapPath("/" + _session + ".vmwerr");
  447. if (!File.Exists(_errFile))
  448. throw new FileNotFoundException("Internal Error",_errFile);
  449. StreamReader sr = new StreamReader(_errFile);
  450. string message = string.Empty, line = null, file = null, lineInFile = "0";
  451. while ((line = sr.ReadLine()) != null)
  452. {
  453. if (line.StartsWith("Message: "))
  454. message = line.Substring("Message: ".Length);
  455. else if (line.StartsWith("File: "))
  456. file = line.Substring("File: ".Length);
  457. else if (line.StartsWith("Line: "))
  458. lineInFile = line.Substring("Line: ".Length);
  459. }
  460. sr.Close();
  461. if (file != null)
  462. {
  463. Location loc = new Location(null);
  464. loc.Filename = file;
  465. loc.BeginLine = int.Parse(lineInFile);
  466. return new ParseException(loc,message);
  467. }
  468. if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
  469. message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
  470. message = "The requested resource (" + _url + ") is not available.";
  471. return new HttpException(404,(message != null ? message : string.Empty));
  472. }
  473. }
  474. }