PageMapper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. static PageMapper ()
  44. {
  45. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (CurrentDomain_AssemblyResolve);
  46. try
  47. {
  48. //Try to load the global resources
  49. HttpContext.AppGlobalResourcesAssembly = GetCachedAssembly ("app_globalresources");
  50. }
  51. catch
  52. {
  53. }
  54. }
  55. static Assembly CurrentDomain_AssemblyResolve (object sender, ResolveEventArgs args)
  56. {
  57. Assembly resolvedAssembly = null;
  58. try
  59. {
  60. resolvedAssembly = GetCachedAssembly (args.Name);
  61. }
  62. catch
  63. {
  64. resolvedAssembly = null;
  65. }
  66. return resolvedAssembly;
  67. }
  68. public static string GetFromMapPathCache(string key)
  69. {
  70. Hashtable answer = null;
  71. lock(LOCK_GETFROMMAPPATHCACHE)
  72. {
  73. answer = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.MAP_PATH_CACHE);
  74. if (answer == null)
  75. {
  76. answer = new Hashtable();
  77. CachedDocumentTypeStorage storage = (CachedDocumentTypeStorage)GetAssembliesCachedDocument();
  78. IDictionaryEnumerator e = storage.GetEnumerator();
  79. e.Reset();
  80. while (e.MoveNext())
  81. {
  82. string currentFile = (string)((DictionaryEntry)e.Current).Key;
  83. answer[currentFile]= IAppDomainConfig.WAR_ROOT_SYMBOL + currentFile;
  84. }
  85. AppDomain.CurrentDomain.SetData(J2EEConsts.MAP_PATH_CACHE,answer);
  86. }
  87. }
  88. return (string)answer[key];
  89. }
  90. #if UNUSED
  91. // UNUSED METHOD
  92. //The method was used by runtime to force file names casesensitivity
  93. // problem. The filelist.xml file should contain correct file names,
  94. // but currently it is unused
  95. public static void LoadFileList()
  96. {
  97. Hashtable hashTable = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.FILE_LIST_FILE);
  98. if (hashTable == null)
  99. {
  100. XmlDocument doc;
  101. try
  102. {
  103. Stream fs = (Stream)IOUtils.getStream(_fileListName);
  104. if (fs == null)
  105. {
  106. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  107. return;
  108. }
  109. doc = new XmlDocument();
  110. doc.Load(fs);
  111. }
  112. catch (Exception)
  113. {
  114. // Console.WriteLine("filelist.xml was not found!!!");
  115. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  116. return;
  117. }
  118. // Console.WriteLine("filelist.xml was found!!!");
  119. if (doc != null && doc.DocumentElement.HasChildNodes)
  120. {
  121. hashTable = CollectionsUtil.CreateCaseInsensitiveHashtable();
  122. XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
  123. for (int i = 0;i < nodeList.Count ; i++)
  124. {
  125. string fileName = nodeList.Item(i).InnerText;
  126. hashTable.Add(fileName,fileName);
  127. }
  128. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, hashTable);
  129. }
  130. }
  131. }
  132. #endif
  133. private static ICachedXmlDoc GetAssembliesCachedDocument()
  134. {
  135. lock(LOCK_GETASSEMBLIESCACHEDDOCUMENT)
  136. {
  137. ICachedXmlDoc doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData(J2EEConsts.ASSEMBLIES_FILE);
  138. if (doc == null)
  139. {
  140. doc = CreateDocument();
  141. if (doc != null)
  142. AppDomain.CurrentDomain.SetData(J2EEConsts.ASSEMBLIES_FILE, doc);
  143. }
  144. return doc;
  145. }
  146. }
  147. private static String NormalizeName(string url)
  148. {
  149. #if NET_2_0
  150. url = System.Web.Util.UrlUtils.RemoveDoubleSlashes(url);
  151. #endif
  152. if (url.StartsWith(IAppDomainConfig.WAR_ROOT_SYMBOL))
  153. url = url.Substring(IAppDomainConfig.WAR_ROOT_SYMBOL.Length);
  154. return url;
  155. }
  156. private static ICachedXmlDoc CreateDocument()
  157. {
  158. return new CachedDocumentTypeStorage();
  159. }
  160. public static Type GetObjectType(string url)
  161. {
  162. return GetCachedType(NormalizeName(url), true);
  163. }
  164. public static Type GetObjectType (string url, bool throwException) {
  165. return GetCachedType (NormalizeName (url), throwException);
  166. }
  167. public static Assembly GetObjectAssembly(string url)
  168. {
  169. return GetCachedAssembly(NormalizeName(url));
  170. }
  171. public static string GetAssemblyResource(string url)
  172. {
  173. return GetCachedResource(NormalizeName(url));
  174. }
  175. private static string GetCachedResource(string url)
  176. {
  177. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  178. return doc.GetAssemblyResourceName(url);
  179. }
  180. private static Assembly GetCachedAssembly(string url)
  181. {
  182. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  183. Assembly t = doc.GetAssembly(url);
  184. if (t == null)
  185. throw new HttpException(404, "The requested resource (" + url + ") is not available.");
  186. return t;
  187. }
  188. private static Type GetCachedType (string url) {
  189. return GetCachedType (url, true);
  190. }
  191. private static Type GetCachedType (string url, bool throwException)
  192. {
  193. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  194. Type t = doc.GetType(url);
  195. if (t == null && throwException)
  196. throw new HttpException(404,"The requested resource (" + url + ") is not available.");
  197. return t;
  198. }
  199. #region ICachedXmlDoc interface
  200. interface ICachedXmlDoc
  201. {
  202. Type GetType(string key);
  203. Assembly GetAssembly(string key);
  204. string GetAssemblyResourceName(string key);
  205. }
  206. #endregion
  207. #region CachedDocumentTypeStorage class
  208. class CachedDocumentTypeStorage : ICachedXmlDoc
  209. {
  210. private static readonly object _fuse = new object();
  211. public static readonly ICachedXmlDoc DEFAULT_DOC =
  212. new CachedDocumentTypeStorage(0);
  213. private static readonly int DEFAULT_PAGES_NUMBER = 25;
  214. private Hashtable _table;
  215. private CachedDocumentTypeStorage(int initTableSize)
  216. {
  217. _table = Hashtable.Synchronized(new Hashtable(initTableSize));
  218. }
  219. public CachedDocumentTypeStorage() :
  220. this(DEFAULT_PAGES_NUMBER)
  221. {}
  222. string ICachedXmlDoc.GetAssemblyResourceName(string o)
  223. {
  224. return GetMetaByURL(o).Resource;
  225. }
  226. Type ICachedXmlDoc.GetType(string o)
  227. {
  228. return GetMetaByURL(o).Type;
  229. }
  230. Assembly ICachedXmlDoc.GetAssembly(string o)
  231. {
  232. return GetMetaByURL(o).Assembly;
  233. }
  234. internal IDictionaryEnumerator GetEnumerator()
  235. {
  236. return _table.GetEnumerator();
  237. }
  238. //rewamped for perfomance reasons
  239. //It looks like issue is not important in development mode,
  240. //but only will became important in production mode when dynamyc compilation will be enabled
  241. //Anyway, locking whole table and compiling under lock looks odd
  242. //spivak.December 07 2006
  243. public MetaProvider GetMetaByURL(string url)
  244. {
  245. #if !NO_GLOBAL_LOCK_ON_COMPILE
  246. string lwUrl = url.ToLower();
  247. lock (_table)
  248. {
  249. object retVal = _table[lwUrl];
  250. if (retVal == null)
  251. {
  252. retVal = PageCompiler.GetCompiler(url);
  253. _table[lwUrl] = retVal;
  254. }
  255. return (MetaProvider)retVal;
  256. }
  257. #else
  258. string lwUrl = url.ToLower();
  259. if (!_table.ContainsKey(lwUrl))
  260. {
  261. lock (_table.SyncRoot)
  262. {
  263. if (_table.ContainsKey(lwUrl))
  264. goto Fused;
  265. _table[lwUrl] = _fuse;
  266. }
  267. try
  268. {
  269. MetaProvider meta = PageCompiler.GetCompiler(url);
  270. lock (_table.SyncRoot)
  271. {
  272. return (MetaProvider)(_table[lwUrl] = meta);
  273. }
  274. }
  275. catch(Exception e)
  276. {
  277. _table.Remove(lwUrl);
  278. }
  279. }
  280. Fused:
  281. while (_table[lwUrl] == _fuse)
  282. Thread.Sleep(10);
  283. return !_table.ContainsKey(lwUrl)? PageCompiler.Error: (MetaProvider)_table[lwUrl];
  284. #endif
  285. }
  286. }
  287. #endregion
  288. }
  289. public interface MetaProvider
  290. {
  291. Type Type { get;}
  292. Assembly Assembly {get;}
  293. string Resource { get;}
  294. }
  295. public class PageCompiler : MetaProvider
  296. {
  297. private static readonly string PAGE_XPATH = "preserve";
  298. private static readonly string ASSEM_ATTRIB_NAME = "assem";
  299. private static readonly string TYPE_ATTRIB_NAME = "type";
  300. private static string _parser = null;
  301. private static PageCompiler _errorProvider = new PageCompiler();
  302. private Type _type = null;
  303. private string _typeName = null;
  304. private Assembly _assembly = null;
  305. private string _origAssemblyName = null;
  306. private string _xmlDescriptor = null;
  307. private string _url = null;
  308. private string _session = null;
  309. PageCompiler(string url)
  310. {
  311. _url = url;
  312. _xmlDescriptor = GetDescFromUrl();
  313. _session = DateTime.Now.Ticks.ToString();
  314. LoadTypeAndAssem();
  315. }
  316. PageCompiler()
  317. {
  318. }
  319. public static PageCompiler Error
  320. {
  321. get
  322. {
  323. return _errorProvider;
  324. }
  325. }
  326. public static PageCompiler GetCompiler(string url)
  327. {
  328. try{
  329. return new PageCompiler(url);
  330. }
  331. catch(Exception e)
  332. {
  333. return Error;
  334. }
  335. }
  336. Type MetaProvider.Type
  337. {
  338. get{
  339. return _type;
  340. }
  341. }
  342. Assembly MetaProvider.Assembly
  343. {
  344. get{
  345. return _assembly;
  346. }
  347. }
  348. string MetaProvider.Resource
  349. {
  350. get
  351. {
  352. return _origAssemblyName != null ? _origAssemblyName + ".ghres" : "dll.ghres";
  353. }
  354. }
  355. private void LoadTypeAndAssem()
  356. {
  357. if (_assembly == null)
  358. {
  359. string typeName = GetCachedTypeName();
  360. if (typeName != null)
  361. {
  362. if ((_type = Type.GetType(typeName)) != null)
  363. _assembly = _type.Assembly;
  364. else
  365. _assembly = Assembly.Load(_origAssemblyName);
  366. }
  367. }
  368. }
  369. private void InternalCompile()
  370. {
  371. string fileName = Path.GetFileName(_url);
  372. string fullFileName = (fileName.ToLower() == "global.asax") ? _url : HttpContext.Current.Request.MapPath(_url);
  373. #if DEBUG
  374. Console.WriteLine("fullFileName=" + fullFileName);
  375. #endif
  376. //type not found - run aspxparser
  377. if (File.Exists(fullFileName) || Directory.Exists(fullFileName))
  378. {
  379. string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
  380. if (J2EEUtils.RunProc(command) != 0)
  381. throw GetCompilerError();
  382. }
  383. else
  384. {
  385. string message = "The requested resource (" + _url + ") is not available.";
  386. throw new HttpException(404, message);
  387. }
  388. }
  389. private string GetDescriptorPath()
  390. {
  391. return String.Join("/", new string[] { "assemblies", _xmlDescriptor });
  392. }
  393. private string GetTypeNameFromAppFolder()
  394. {
  395. try
  396. {
  397. using (StreamReader sr = new StreamReader(HttpContext.Current.Request.MapPath("/" + GetDescriptorPath())))
  398. {
  399. return GetTypeFromDescStream(sr.BaseStream);
  400. }
  401. }
  402. catch (Exception ex)
  403. {
  404. Console.WriteLine(ex);
  405. throw ex;
  406. }
  407. }
  408. internal string GetTypeFromResources()
  409. {
  410. string typeName = null;
  411. //if the desciptor exists in the war - get the type
  412. string descPath = GetDescriptorPath();
  413. try
  414. {
  415. #if DEBUG
  416. Console.WriteLine(descPath);
  417. #endif
  418. using (Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath))
  419. {
  420. if (fs != null)
  421. {
  422. return GetTypeFromDescStream(fs);
  423. }
  424. }
  425. }
  426. catch (Exception ex)
  427. {
  428. #if DEBUG
  429. Console.WriteLine(ex);
  430. #endif
  431. }
  432. return null;
  433. }
  434. internal string GetCachedTypeName()
  435. {
  436. string typeName = GetTypeFromResources();
  437. if (typeName == null)
  438. {
  439. //spawn dynamic compilation and lookup typename from created folder
  440. InternalCompile();
  441. typeName = GetTypeNameFromAppFolder();
  442. }
  443. return typeName;
  444. }
  445. private string GetTypeName()
  446. {
  447. return String.Format("{0}, {1}", _typeName, _origAssemblyName);
  448. }
  449. private bool LoadMetaFromXmlStream(Stream fs)
  450. {
  451. if (fs != null)
  452. {
  453. try
  454. {
  455. XmlDocument descXml = new XmlDocument();
  456. descXml.Load(fs);
  457. _origAssemblyName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
  458. _typeName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
  459. return true;
  460. }
  461. catch
  462. {
  463. #if DEBUG
  464. Console.WriteLine("Failed to load typename from stream");
  465. #endif
  466. }
  467. }
  468. return false;
  469. }
  470. private string GetTypeFromDescStream(Stream fs)
  471. {
  472. if (LoadMetaFromXmlStream(fs))
  473. return GetTypeName();
  474. return null;
  475. }
  476. private string[] GetParserCmd(bool globalAsax)
  477. {
  478. string[] cmd = null;
  479. if (globalAsax)
  480. {
  481. cmd = new string[4];
  482. cmd[3] = "/buildglobalasax";
  483. }
  484. else
  485. {
  486. cmd = new string[5];
  487. cmd[3] = "/aspxFiles:" + _url;
  488. cmd[4] = "/compilepages";
  489. }
  490. cmd[0] = GetParser();
  491. cmd[1] = "/session:" + _session;
  492. cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
  493. return cmd;
  494. }
  495. private string GetParser()
  496. {
  497. if (_parser == null)
  498. {
  499. StreamReader sr =
  500. File.OpenText(HttpContext.Current.Request.MapPath("/AspxParser.params"));
  501. _parser = sr.ReadLine();
  502. sr.Close();
  503. }
  504. return _parser;
  505. }
  506. private string GetDescFromUrl()
  507. {
  508. string fileName = Path.GetFileName(_url);
  509. if (fileName.ToLower() == "global.asax")
  510. return "global.asax.xml";
  511. string id = GetIdFromUrl(_url);
  512. string[] descName = new string[3] {fileName, id, ".xml"} ;
  513. return string.Concat(descName).ToLower();
  514. }
  515. private string GetIdFromUrl(string path)
  516. {
  517. path = path.Trim('/');
  518. string fileName = Path.GetFileName(path);
  519. string id = string.Empty;
  520. path = path.Substring (path.IndexOf ("/") + 1);
  521. if (path.Length > fileName.Length)
  522. id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
  523. return id;
  524. }
  525. private Exception GetCompilerError()
  526. {
  527. string _errFile = HttpContext.Current.Request.MapPath("/" + _session + ".vmwerr");
  528. if (!File.Exists(_errFile))
  529. throw new FileNotFoundException("Internal Error",_errFile);
  530. StreamReader sr = new StreamReader(_errFile);
  531. string message = string.Empty, line = null, file = null, lineInFile = "0";
  532. while ((line = sr.ReadLine()) != null)
  533. {
  534. if (line.StartsWith("Message: "))
  535. message = line.Substring("Message: ".Length);
  536. else if (line.StartsWith("File: "))
  537. file = line.Substring("File: ".Length);
  538. else if (line.StartsWith("Line: "))
  539. lineInFile = line.Substring("Line: ".Length);
  540. }
  541. sr.Close();
  542. if (file != null)
  543. {
  544. Location loc = new Location(null);
  545. loc.Filename = file;
  546. loc.BeginLine = int.Parse(lineInFile);
  547. return new ParseException(loc,message);
  548. }
  549. if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
  550. message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
  551. message = "The requested resource (" + _url + ") is not available.";
  552. return new HttpException(404,(message != null ? message : string.Empty));
  553. }
  554. }
  555. }