PageMapper.cs 15 KB

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