PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Toobs/PresFramework/src/main/java/org/toobsframework/pres/util/ParameterUtil.java

https://github.com/parabuzzle/toobs
Java | 428 lines | 389 code | 26 blank | 13 comment | 180 complexity | 3f92ba5eaf6cb347a7a1a85fc66da199 MD5 | raw file
  1. package org.toobsframework.pres.util;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.List;
  5. import java.util.Enumeration;
  6. import java.util.HashMap;
  7. import java.util.Iterator;
  8. import java.util.Map;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpSession;
  11. import org.apache.commons.jxpath.JXPathContext;
  12. import org.apache.commons.jxpath.JXPathException;
  13. import org.apache.commons.logging.Log;
  14. import org.apache.commons.logging.LogFactory;
  15. import org.springframework.web.util.WebUtils;
  16. import org.toobsframework.pres.component.config.Parameter;
  17. import org.toobsframework.pres.doit.config.Forward;
  18. import org.toobsframework.exception.ParameterException;
  19. import org.toobsframework.util.Configuration;
  20. @SuppressWarnings("unchecked")
  21. public class ParameterUtil {
  22. private static Log log = LogFactory.getLog(ParameterUtil.class);
  23. private static List excludedParameters;
  24. private static Map envParameters;
  25. static {
  26. excludedParameters = new ArrayList();
  27. excludedParameters.add("org.springframework.web.servlet.DispatcherServlet.THEME");
  28. excludedParameters.add("org.springframework.web.servlet.DispatcherServlet.THEME_RESOLVER");
  29. excludedParameters.add("org.springframework.web.servlet.DispatcherServlet.THEME_SOURCE");
  30. excludedParameters.add("org.springframework.web.servlet.DispatcherServlet.CONTEXT");
  31. excludedParameters.add("org.springframework.web.servlet.DispatcherServlet.LOCALE");
  32. excludedParameters.add("org.springframework.web.servlet.DispatcherServlet.LOCALE_RESOLVER");
  33. excludedParameters.add("org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping");
  34. excludedParameters.add("hibernateFilter.FILTERED");
  35. envParameters = new HashMap();
  36. envParameters.put("host", Configuration.getInstance().getMainHost() );
  37. envParameters.put("toobs.debug", Configuration.getInstance().getProperty("toobs.debug", "false") );
  38. }
  39. /**
  40. * Extract the URL filename from the given request URI.
  41. * Delegates to <code>WebUtils.extractViewNameFromUrlPath(String)</code>.
  42. * @param uri the request URI (e.g. "/index.html")
  43. * @return the extracted URI filename (e.g. "index")
  44. * @see org.springframework.web.util.WebUtils#extractFilenameFromUrlPath
  45. */
  46. public static String extractViewNameFromUrlPath(String uri) {
  47. return WebUtils.extractFilenameFromUrlPath(uri);
  48. }
  49. public static String extractExtensionFromUrlPath(String uri) {
  50. int lastDot = uri.indexOf(".");
  51. if (lastDot != -1) {
  52. return uri.substring(lastDot+1);
  53. }
  54. return "";
  55. }
  56. public static String extractContextPathFromUrlPath(String uri) {
  57. int midSlash = uri.indexOf("/",1);
  58. if (midSlash != -1) {
  59. return uri.substring(1,midSlash);
  60. }
  61. return "";
  62. }
  63. public static String resoveForwardPath(Forward forwardDef, Map parameters, String urlPath) {
  64. String forwardPath = null;
  65. forwardPath = ((String[])ParameterUtil.resolveParam(forwardDef.getUri(), parameters))[0];
  66. if (forwardPath != null && forwardDef.getUseContext()) {
  67. String contextPath = ParameterUtil.extractContextPathFromUrlPath(urlPath);
  68. forwardPath = (contextPath.length()>0 ? "/" + contextPath + "/" : "") + forwardPath;
  69. }
  70. return forwardPath;
  71. }
  72. public static Map buildParameterMap(HttpServletRequest request) {
  73. return buildParameterMap(request, false);
  74. }
  75. public static Map buildParameterMap(HttpServletRequest request, boolean compCall) {
  76. Map params = new HashMap();
  77. HttpSession session = request.getSession();
  78. Enumeration attributes = session.getAttributeNames();
  79. // Session has lowest priority
  80. while(attributes.hasMoreElements()){
  81. String thisAttribute = (String) attributes.nextElement();
  82. //if (session.getAttribute(thisAttribute) instanceof String) {
  83. params.put(thisAttribute, session.getAttribute(thisAttribute));
  84. //}
  85. }
  86. // Parameters next highest
  87. params.putAll(request.getParameterMap());
  88. // Attributes rule all
  89. attributes = request.getAttributeNames();
  90. while(attributes.hasMoreElements()){
  91. String thisAttribute = (String) attributes.nextElement();
  92. if (!excludedParameters.contains(thisAttribute)) {
  93. if (log.isDebugEnabled()) {
  94. log.debug("Putting " + thisAttribute + " As " + request.getAttribute(thisAttribute));
  95. }
  96. params.put(thisAttribute, request.getAttribute(thisAttribute));
  97. }
  98. }
  99. params.put("httpQueryString", request.getQueryString());
  100. if (compCall && request.getMethod().equals("POST")) {
  101. StringBuffer qs = new StringBuffer();
  102. Iterator iter = request.getParameterMap().entrySet().iterator();
  103. int i = 0;
  104. while (iter.hasNext()) {
  105. Map.Entry entry = (Map.Entry)iter.next();
  106. String key = (String)entry.getKey();
  107. String[] value = (String[])entry.getValue();
  108. for (int j = 0; j < value.length; j++) {
  109. if (i > 0) qs.append("&");
  110. qs.append(key).append("=").append(value[j]);
  111. i++;
  112. }
  113. }
  114. params.put("httpQueryString", qs.toString());
  115. }
  116. return params;
  117. }
  118. public static void mapParameters(String callingContext,
  119. Parameter[] paramMap,
  120. Map inParams,
  121. Map outParams,
  122. String scopeId) throws ParameterException {
  123. mapParameters(callingContext, paramMap, inParams, outParams, scopeId, null);
  124. }
  125. public static void mapParameters(String callingContext,
  126. Parameter[] paramMap,
  127. Map inParams,
  128. Map outParams,
  129. String scopeId,
  130. ArrayList objectList) throws ParameterException {
  131. JXPathContext context = JXPathContext.newContext(inParams);
  132. for(int j = 0; j < paramMap.length; j++){
  133. Parameter thisParam = paramMap[j];
  134. Object value = null;
  135. String thisPath = null;
  136. String thisName = null;
  137. try {
  138. if (thisParam.getScope() != null &&
  139. !thisParam.getScope().equalsIgnoreCase("all") &&
  140. !thisParam.getScope().equalsIgnoreCase(scopeId) ) {
  141. continue;
  142. }
  143. if(!thisParam.getOverwriteExisting() && inParams.get(thisParam.getName()) != null) {
  144. continue;
  145. }
  146. thisName = resolveParam(thisParam.getName(), inParams)[0];
  147. thisPath = resolveParam(thisParam.getPath(), inParams)[0];
  148. boolean condition = true;
  149. if (thisParam.getCondition() != null) {
  150. Object condObj = context.getValue(thisParam.getCondition());
  151. if (log.isDebugEnabled()) {
  152. log.debug("Condition Object: " + condObj);
  153. }
  154. if (condObj != null && condObj instanceof Boolean) {
  155. condition = (Boolean)condObj;
  156. }
  157. }
  158. if (condition) {
  159. if (thisParam.getIsStatic()) {
  160. value = thisPath;
  161. } else if (thisParam.getIsObject()) {
  162. if((objectList == null) || (objectList != null && thisParam.getObjectIndex() >= objectList.size())){
  163. continue;
  164. }
  165. JXPathContext objContext = JXPathContext.newContext(objectList.get(thisParam.getObjectIndex()));
  166. if (thisParam.getIsList()) {
  167. Iterator iter = objContext.iterate(thisPath);
  168. value = new ArrayList();
  169. while (iter.hasNext()) {
  170. ((ArrayList)value).add(iter.next());
  171. }
  172. if (((ArrayList)value).size() == 0 && thisParam.getDefault() != null) {
  173. ((ArrayList)value).add(thisParam.getDefault());
  174. }
  175. } else {
  176. value = objContext.getValue(thisPath);
  177. }
  178. } else if (thisParam.getIsList()) {
  179. Object newList = inParams.get(thisName);
  180. if (newList == null)
  181. newList = outParams.get(thisName);
  182. if (newList != null && !(newList instanceof ArrayList)) {
  183. newList = new ArrayList();
  184. ((ArrayList)newList).add(value);
  185. }
  186. if (newList == null)
  187. newList = new ArrayList();
  188. value = context.getValue(thisPath);
  189. if(value != null && value.getClass().isArray()){
  190. Object[] valueArray = (Object[])value;
  191. if (valueArray.length > 1) {
  192. for (int i = 0; i < valueArray.length; i++) {
  193. if (valueArray[i] != null && ((String)valueArray[i]).length() > 0)
  194. ((ArrayList)newList).add(valueArray[i]);
  195. }
  196. value = null;
  197. } else {
  198. value = valueArray[0];
  199. }
  200. }
  201. if (value != null && !"".equals(value))
  202. ((ArrayList)newList).add(value);
  203. value = newList;
  204. } else {
  205. value = context.getValue(thisPath);
  206. if(value != null && value.getClass().isArray()){
  207. Object[] valueArray = (Object[])value;
  208. if (valueArray.length > 1) {
  209. value = valueArray;
  210. } else {
  211. value = valueArray[0];
  212. }
  213. } else if (value == null && thisParam.getSessionPath() != null) {
  214. value = context.getValue(thisParam.getSessionPath());
  215. }
  216. }
  217. if (value != null && value.getClass().isArray() && thisParam.getIsList()) {
  218. outParams.put(thisName, value);
  219. } else if (value != null && value.getClass().isArray()) {
  220. outParams.put(thisName, ((String[])value)[0]);
  221. } else if (value != null && value instanceof ArrayList && ((ArrayList)value).size()>0) {
  222. outParams.put(thisName, value);
  223. } else if (value != null && !(value instanceof ArrayList) && String.valueOf(value).length() > 0) {
  224. outParams.put(thisName, String.valueOf(value));
  225. } else if (thisParam.getDefault() != null) {
  226. String [] defVal = resolveParam(thisParam.getDefault(), inParams);
  227. if (defVal != null) {
  228. outParams.put(thisName, defVal[0]);
  229. }
  230. } else if (!thisParam.getIgnoreNull()) {
  231. throw new ParameterException(callingContext, thisName, thisPath);
  232. } else if (log.isDebugEnabled()){
  233. log.debug("Param " + thisName + " evaluated to null");
  234. }
  235. }
  236. } catch (Exception e) {
  237. log.error("mapParameters - exception [name:" + thisName + " path:" + thisPath + " value:" + value + "]");
  238. throw new ParameterException(callingContext, thisName, thisPath);
  239. }
  240. }
  241. }
  242. public static void mapOutputParameters(Parameter[] paramMap, Map paramsIn, String scopeId, ArrayList objects) {
  243. for(int j = 0; j < paramMap.length; j++){
  244. Parameter thisParam = paramMap[j];
  245. if (thisParam.getScope() != null &&
  246. !thisParam.getScope().equalsIgnoreCase("all") &&
  247. !thisParam.getScope().equalsIgnoreCase(scopeId) ) {
  248. continue;
  249. }
  250. if(!thisParam.getOverwriteExisting() && paramsIn.get(thisParam.getName()) != null) {
  251. continue;
  252. }
  253. if(thisParam.getObjectIndex() >= objects.size()){
  254. continue;
  255. }
  256. JXPathContext context = null;
  257. Object value = null;
  258. String paramName = resolveParam(thisParam.getName(), paramsIn)[0];
  259. try {
  260. String thisPath = resolveParam(thisParam.getPath(), paramsIn)[0];
  261. if(thisParam.getIsStatic()){
  262. value = thisPath;
  263. } else {
  264. if (thisParam.getIsList()) {
  265. value = new ArrayList();
  266. if (thisParam.getObjectIndex() == -1) {
  267. for (int i = 0; i < objects.size(); i++) {
  268. context = JXPathContext.newContext(objects.get(i));
  269. ((ArrayList)value).add(context.getValue(thisPath));
  270. }
  271. } else {
  272. context = JXPathContext.newContext(objects.get(thisParam.getObjectIndex()));
  273. Iterator iter = context.iterate(thisPath);
  274. while (iter.hasNext()) {
  275. ((ArrayList)value).add(iter.next());
  276. }
  277. }
  278. if (((ArrayList)value).size() == 0) {
  279. if (thisParam.getDefault() != null) {
  280. try {
  281. ((ArrayList)value).add(Integer.parseInt(thisParam.getDefault()));
  282. } catch (NumberFormatException nfe) {
  283. ((ArrayList)value).add(thisParam.getDefault());
  284. }
  285. } else {
  286. value = null;
  287. }
  288. }
  289. } else {
  290. context = JXPathContext.newContext(objects.get(thisParam.getObjectIndex()));
  291. value = context.getValue(thisPath);
  292. }
  293. }
  294. if(value != null
  295. && List.class.isAssignableFrom(value.getClass())
  296. && ((List)value).size() == 0
  297. && thisParam.getDefault() != null){
  298. ((List)value).add(thisPath);
  299. }
  300. paramsIn.put(paramName, value);
  301. } catch (JXPathException e) {
  302. if (thisParam.getDefault() != null) {
  303. String[] def = resolveParam(thisParam.getDefault(), paramsIn);
  304. if (def != null && def.length > 0) {
  305. paramsIn.put(paramName, def[0]);
  306. }
  307. } else if (!thisParam.getIgnoreNull()) {
  308. log.error("JXPathException for parameter " + paramName + " in scope " + scopeId);
  309. // TODO This should be a BaseException
  310. throw e;
  311. }
  312. }
  313. }
  314. }
  315. public static void mapDoItParameters(Parameter[] paramMap, Map paramsIn, Map paramsOut, boolean useJXPathContext)
  316. {
  317. JXPathContext context = null;
  318. if(useJXPathContext)
  319. context = JXPathContext.newContext(paramsIn);
  320. for(int j = 0; j < paramMap.length; j++){
  321. Parameter thisParam = paramMap[j];
  322. Object value = null;
  323. if(thisParam.getIsStatic()) {
  324. String [] valueAry = new String[1];
  325. valueAry[0] = resolveParam(thisParam.getPath(), paramsIn)[0];
  326. value = valueAry;
  327. } else {
  328. value = context.getValue(resolveParam(thisParam.getPath(), paramsIn)[0]);
  329. if (value != null && value.getClass().isArray() && ((Object[])value).length == 1) {
  330. value = ((Object[])value)[0];
  331. } else if (value == null && thisParam.getDefault() != null) {
  332. value = thisParam.getDefault();
  333. }
  334. }
  335. paramsOut.put(resolveParam(thisParam.getName(), paramsIn)[0], value);
  336. }
  337. }
  338. public static String[] resolveParam(Object input, Map params) {
  339. return resolveParam(input, params, null);
  340. }
  341. public static String[] resolveParam(Object input, Map params, Object defaultValue) {
  342. String[] output;
  343. if (input != null && input.getClass().isArray()) {
  344. output = (String[])input;
  345. } else {
  346. output = new String[] {(String)input};
  347. }
  348. if (input != null && input instanceof String && !"".equals(input)) {
  349. char ind = ((String)input).charAt(0);
  350. Object value;
  351. switch (ind) {
  352. case '$':
  353. value = params.get(((String)input).substring(1));
  354. if (value == null) {
  355. if (defaultValue != null) {
  356. value = defaultValue;
  357. } else {
  358. log.warn("Input variable with name " + input + " resolved to null");
  359. return null;
  360. }
  361. }
  362. if (value.getClass().isArray()) {
  363. output = ((String[])value);
  364. } else {
  365. output = new String[1];
  366. output[0] = (String)value;
  367. }
  368. if (log.isDebugEnabled()) {
  369. log.debug("Input variable with name " + input + " resolved to " + output[0]);
  370. }
  371. break;
  372. case '#':
  373. value = envParameters.get(((String)input).substring(1));
  374. if (value != null) {
  375. if (value.getClass().isArray()) {
  376. output = ((String[])value);
  377. } else {
  378. output = new String[1];
  379. output[0] = (String)value;
  380. }
  381. }
  382. break;
  383. case '%':
  384. if (((String)input).equalsIgnoreCase("%now")) {
  385. output = new String[1];
  386. output[0] = String.valueOf(new Date().getTime());
  387. }
  388. }
  389. } else if (defaultValue != null) {
  390. output = new String[1];
  391. output[0] = (String)defaultValue;
  392. }
  393. return output;
  394. }
  395. public static void mapScriptParams(Map params, Map paramsIn) {
  396. Iterator iter = params.keySet().iterator();
  397. while (iter.hasNext()) {
  398. Object key = iter.next();
  399. paramsIn.put(key, params.get(key));
  400. }
  401. }
  402. }