PageMapper.cs 15 KB

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