PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/frameworks/sip-servlets/ssf/sf-core/src/main/java/org/mobicents/ssf/servlet/handler/support/DefaultEventStrategy.java

http://mobicents.googlecode.com/
Java | 596 lines | 419 code | 81 blank | 96 comment | 80 complexity | 55a5ec46f083aaacca7f77117ea70127 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1, GPL-2.0, CC-BY-SA-3.0, CC0-1.0, Apache-2.0, BSD-3-Clause
  1. /**
  2. * This is free software; you can redistribute it and/or modify it under the
  3. * terms of the GNU Lesser General Public License as published by the Free
  4. * Software Foundation; either version 2.1 of the License, or (at your option)
  5. * any later version.
  6. *
  7. * This software is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU Lesser General Public License
  13. * along with this software; if not, write to the Free Software Foundation,
  14. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
  15. * site: http://www.fsf.org.
  16. */
  17. package org.mobicents.ssf.servlet.handler.support;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import java.util.StringTokenizer;
  27. import javax.servlet.ServletException;
  28. import javax.servlet.sip.SipApplicationSession;
  29. import javax.servlet.sip.SipServletResponse;
  30. import javax.servlet.sip.SipSession;
  31. import org.mobicents.ssf.SsfException;
  32. import org.mobicents.ssf.bind.SignalingError;
  33. import org.mobicents.ssf.bind.SignalingErrors;
  34. import org.mobicents.ssf.bind.SignalingResult;
  35. import org.mobicents.ssf.bind.SipRequestError;
  36. import org.mobicents.ssf.context.SignalingAttributes;
  37. import org.mobicents.ssf.context.SipContextHolder;
  38. import org.mobicents.ssf.event.DefaultEventFactory;
  39. import org.mobicents.ssf.event.Event;
  40. import org.mobicents.ssf.event.EventFactory;
  41. import org.mobicents.ssf.event.EventType;
  42. import org.mobicents.ssf.internal.ResourceMessage;
  43. import org.mobicents.ssf.servlet.handler.ErrorHandler;
  44. import org.mobicents.ssf.servlet.handler.EventStrategy;
  45. import org.mobicents.ssf.servlet.handler.SipHandlerAdapter;
  46. import org.mobicents.ssf.servlet.handler.SipHandlerFactory;
  47. import org.mobicents.ssf.util.MessageQueue;
  48. import org.slf4j.Logger;
  49. import org.slf4j.LoggerFactory;
  50. import org.springframework.beans.factory.BeanFactoryUtils;
  51. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
  52. import org.springframework.context.ApplicationContext;
  53. import org.springframework.core.OrderComparator;
  54. /**
  55. * ????????????????????????????????????????
  56. *
  57. * @author nisihara
  58. *
  59. */
  60. public class DefaultEventStrategy implements EventStrategy {
  61. public Logger logger = LoggerFactory.getLogger(DefaultEventStrategy.class);
  62. private ApplicationContext ac;
  63. private List<EventFactory> eventFactories;
  64. private List<SipHandlerFactory> sipHandlerFactories;
  65. private List<SipHandlerAdapter> sipHandlerAdapters;
  66. private List<ErrorHandler> errorHandlers;
  67. private boolean detectAllEventFactories = true;
  68. private boolean detectAllSipHandlerFactories = true;
  69. private boolean detectAllSipHandlerAdapters = true;
  70. private boolean detectAllErrorHandlers = true;
  71. private String servletName;
  72. /**
  73. * ?????????
  74. */
  75. private String stateNameSeparator = ";";
  76. /* (? Javadoc)
  77. * @see org.mobicents.ssf.servlet.handler.EventStrategy#getEventFactories()
  78. */
  79. public List<EventFactory> getEventFactories() {
  80. return this.eventFactories;
  81. }
  82. /* (? Javadoc)
  83. * @see org.mobicents.ssf.servlet.handler.EventStrategy#getSipHandlerAdapters()
  84. */
  85. public List<SipHandlerAdapter> getSipHandlerAdapters() {
  86. return this.sipHandlerAdapters;
  87. }
  88. /* (? Javadoc)
  89. * @see org.mobicents.ssf.servlet.handler.EventStrategy#getSipHandlerFactories()
  90. */
  91. public List<SipHandlerFactory> getSipHandlerFactories() {
  92. return sipHandlerFactories;
  93. }
  94. public String getStateNameSeparator() {
  95. return this.stateNameSeparator;
  96. }
  97. /* (? Javadoc)
  98. * @see org.mobicents.ssf.servlet.handler.EventStrategy#handle(java.lang.Object, java.lang.Object, com.oki.sip.sf.event.EventType)
  99. */
  100. @SuppressWarnings("unchecked")
  101. public Object handle(Object source, Object obj, EventType type) throws ServletException {
  102. // ??????????
  103. // NOTE ????????????
  104. List<Event> eventList = new LinkedList<Event>();
  105. for(EventFactory efactory:this.eventFactories) {
  106. try {
  107. if(logger.isTraceEnabled()) {
  108. logger.trace("[EventFactory:" + efactory + "],[obj:" + obj + "],[type:" + type + "]");
  109. }
  110. Event evt = efactory.createEvent(source, obj, type);
  111. if(evt != null) {
  112. if(logger.isTraceEnabled()) {
  113. logger.trace(ResourceMessage.getMessage(9304, efactory, evt));
  114. }
  115. eventList.add(evt);
  116. }
  117. } catch (Throwable t) {
  118. // ????????
  119. logger.error(ResourceMessage.getMessage(303, efactory, obj, type), t);
  120. throw new ServletException("Exception Occured.", t);
  121. }
  122. }
  123. if(logger.isDebugEnabled()) {
  124. logger.debug(ResourceMessage.getMessage(9305, eventList));
  125. }
  126. if(eventList.isEmpty()) {
  127. logger.error(ResourceMessage.getMessage(302, source, obj, type));
  128. for(ErrorHandler ehandler: this.errorHandlers) {
  129. // ?????????????
  130. SipServletResponse res = ehandler.cannotCreateEvent(obj, type);
  131. if(res != null) {
  132. try {
  133. // ?????????????????????????
  134. MessageQueue.send(res);
  135. return null;
  136. } finally {
  137. try {
  138. MessageQueue.flush(this.ac);
  139. } catch (Exception e) {
  140. logger.error("Cannot send the messages.", e);
  141. }
  142. }
  143. }
  144. }
  145. // ???????????????????????????????????????
  146. // throw new ServletException("Cannot create event.[" + source + "," + obj + "," + type);
  147. return null;
  148. }
  149. // ?????????????
  150. // Event??????????????Map
  151. Map<Event, List<Object>> handlers = new HashMap<Event, List<Object>>();
  152. for(SipHandlerFactory hfactory:this.sipHandlerFactories) {
  153. for(Event evt: eventList) {
  154. Object handler = hfactory.getHandler(evt);
  155. // Event???????????????
  156. if(handler != null) {
  157. if(logger.isTraceEnabled()) {
  158. logger.trace(ResourceMessage.getMessage(9306, hfactory, evt, handler));
  159. }
  160. List<Object> list = handlers.get(evt);
  161. if(list == null) {
  162. list = new LinkedList<Object>();
  163. }
  164. list.add(handler);
  165. handlers.put(evt, list);
  166. }
  167. }
  168. }
  169. for(Event evt: eventList) {
  170. // ?????????????????????
  171. List<Object> handlerList = handlers.get(evt);
  172. if(handlerList != null) {
  173. // ????????
  174. for(SipHandlerAdapter adapter: this.sipHandlerAdapters) {
  175. // ???????????????????
  176. for(Object handler: handlerList) {
  177. if(adapter.supports(handler)) {
  178. try {
  179. // ?????????????????
  180. // NOTE ?????????????????
  181. // TODO ?????????????
  182. if(logger.isTraceEnabled()) {
  183. logger.trace(ResourceMessage.getMessage(9307, adapter, evt, handler));
  184. }
  185. Object rv = adapter.handle(evt, handler);
  186. // ????
  187. if(logger.isTraceEnabled()) {
  188. logger.trace(ResourceMessage.getMessage(9308, adapter, evt, handler));
  189. }
  190. if(rv != null) {
  191. if(rv instanceof String) {
  192. // ?????????String??????
  193. // ???????????????
  194. String stateName = (String)rv;
  195. SignalingAttributes attr = SipContextHolder.currentSignalingAttributes();
  196. setupState(attr, stateName);
  197. } else if(rv instanceof Map) {
  198. // ?????????Map?????????SipSession????
  199. // SipApplicationSession????????????
  200. SignalingAttributes attr = SipContextHolder.currentSignalingAttributes();
  201. Map<Object, String> stateMap = (Map<Object, String>)rv;
  202. setupState(attr, stateMap);
  203. }
  204. }
  205. SignalingAttributes attr = SipContextHolder.currentSignalingAttributes();
  206. SignalingResult result = attr.getSignalingResult();
  207. if(result.hasErrors()) {
  208. // ??????????????????
  209. boolean isErrorSended = false;
  210. SignalingErrors errors = result.getSignalingErrors();
  211. for(SignalingError error: errors.getErrors()) {
  212. if(error instanceof SipRequestError) {
  213. SipRequestError requestError = (SipRequestError)error;
  214. SipServletResponse res = requestError.createResponse();
  215. result.push(res);
  216. isErrorSended = true;
  217. }
  218. }
  219. if(!isErrorSended) {
  220. // ?????????????????????
  221. throw new SsfException("SingalingError occured:" + errors);
  222. }
  223. }
  224. return rv;
  225. } catch (Throwable t) {
  226. // ?????
  227. // ????????ServletException????
  228. // ?????????????????????????
  229. MessageQueue.cancel();
  230. for(ErrorHandler ehandler: this.errorHandlers) {
  231. ehandler.handleError(evt, adapter, handler, t);
  232. }
  233. return t;
  234. } finally {
  235. SignalingAttributes attr = SipContextHolder.currentSignalingAttributes();
  236. SignalingResult result = attr.getSignalingResult();
  237. try {
  238. result.flush();
  239. } catch (Exception e) {
  240. // ????????????????????????????????
  241. // TODO SignalingAttributes????????rollback????
  242. logger.error("Cannot send the messages.", e);
  243. }
  244. // ?????SipSession?Handler???
  245. SipApplicationSession appSession = attr.getSipApplicationSession();
  246. appSession.setAttribute(HANDLER_NAME, this.servletName);
  247. Iterator<?> iter = appSession.getSessions("SIP");
  248. while(iter.hasNext()) {
  249. Object s = iter.next();
  250. if(s instanceof SipSession) {
  251. ((SipSession)s).setHandler(this.servletName);
  252. }
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }
  259. }
  260. for(ErrorHandler ehandler: this.errorHandlers) {
  261. SipServletResponse res = ehandler.handlerNotFound(obj, type);
  262. try {
  263. if(res != null) {
  264. // ?????????????????????????
  265. MessageQueue.send(res);
  266. return null;
  267. }
  268. } finally {
  269. try {
  270. MessageQueue.flush(this.ac);
  271. } catch (Exception e) {
  272. logger.error("Cannot send the messages.", e);
  273. }
  274. }
  275. }
  276. // ErrorHandler????????????????????????????
  277. //throw new ServletException("SipHandlerAdapter NOT FOUND.[event=" + obj + "],[type=" + type + "]");
  278. logger.error("SipHandlerAdapter NOT FOUND.[event=" + obj + "],[type=" + type + "]");
  279. return null;
  280. }
  281. public List<ErrorHandler> getErrorHandlers() {
  282. return errorHandlers;
  283. }
  284. public void setErrorHandlers(List<ErrorHandler> errorHandlers) {
  285. this.errorHandlers = errorHandlers;
  286. }
  287. public boolean isDetectAllErrorHandlers() {
  288. return detectAllErrorHandlers;
  289. }
  290. public void setDetectAllErrorHandlers(boolean detectAllErrorHandlers) {
  291. this.detectAllErrorHandlers = detectAllErrorHandlers;
  292. }
  293. /* (? Javadoc)
  294. * @see org.mobicents.ssf.servlet.handler.EventStrategy#init(String)
  295. */
  296. public void init(String servletName) {
  297. this.servletName = servletName;
  298. initEventFactories();
  299. initSipHandlerFactories();
  300. initSipHandlerAdaptors();
  301. initErrorHandlers();
  302. }
  303. public boolean isDetectAllEventFactories() {
  304. return this.detectAllEventFactories;
  305. }
  306. public boolean isDetectAllSipHandlerAdapters() {
  307. return detectAllSipHandlerAdapters;
  308. }
  309. public boolean isDetectAllSipHandlerFactories() {
  310. return this.detectAllSipHandlerFactories;
  311. }
  312. /* (? Javadoc)
  313. * @see org.mobicents.ssf.servlet.handler.EventStrategy#setServletContext(org.springframework.context.ApplicationContext)
  314. */
  315. public void setApplicationContext(ApplicationContext ac) {
  316. this.ac = ac;
  317. }
  318. public void setDetectAllEventFactories(boolean detectAllEventFactories) {
  319. this.detectAllEventFactories = detectAllEventFactories;
  320. }
  321. public void setDetectAllSipHandlerAdapters(boolean detectAllSipHandlerAdapters) {
  322. this.detectAllSipHandlerAdapters = detectAllSipHandlerAdapters;
  323. }
  324. public void setDetectAllSipHandlerFactories(boolean detectAllSipHandlerFactories) {
  325. this.detectAllSipHandlerFactories = detectAllSipHandlerFactories;
  326. }
  327. /* (? Javadoc)
  328. * @see org.mobicents.ssf.servlet.handler.EventStrategy#setEventFactories(java.util.List)
  329. */
  330. public void setEventFactories(List<EventFactory> eventFactories) {
  331. this.eventFactories = eventFactories;
  332. }
  333. /* (? Javadoc)
  334. * @see org.mobicents.ssf.servlet.handler.EventStrategy#setSipHandlerAdapters(java.util.List)
  335. */
  336. public void setSipHandlerAdapters(List<SipHandlerAdapter> sipHandlerAdapters) {
  337. this.sipHandlerAdapters = sipHandlerAdapters;
  338. }
  339. /* (? Javadoc)
  340. * @see org.mobicents.ssf.servlet.handler.EventStrategy#setSipHandlerFactories(java.util.List)
  341. */
  342. public void setSipHandlerFactories(List<SipHandlerFactory> sipHandlerFactories) {
  343. this.sipHandlerFactories = sipHandlerFactories;
  344. }
  345. public void setStateNameSeparator(String separator) {
  346. this.stateNameSeparator = separator;
  347. }
  348. @SuppressWarnings("unchecked")
  349. private void initEventFactories() {
  350. this.eventFactories = null;
  351. if(this.detectAllEventFactories) {
  352. if(logger.isTraceEnabled()) {
  353. logger.trace(ResourceMessage.getMessage(9301, EventFactory.class.getName(), ac));
  354. }
  355. Map matchedBeans =
  356. BeanFactoryUtils.beansOfTypeIncludingAncestors(ac, EventFactory.class, true, false);
  357. if(!matchedBeans.isEmpty()) {
  358. this.eventFactories = new ArrayList(matchedBeans.values());
  359. Collections.sort(this.eventFactories, new OrderComparator());
  360. }
  361. } else {
  362. try {
  363. if(logger.isTraceEnabled()) {
  364. logger.trace(ResourceMessage.getMessage(9302, EVENT_FACTORY_BEAN_NAME, EventFactory.class.getName()));
  365. }
  366. EventFactory ef =
  367. (EventFactory)this.ac.getBean(EVENT_FACTORY_BEAN_NAME, EventFactory.class);
  368. this.eventFactories = Collections.singletonList(ef);
  369. } catch (NoSuchBeanDefinitionException e) {
  370. //
  371. }
  372. }
  373. if(this.eventFactories == null) {
  374. logger.info(ResourceMessage.getMessage(301, EventFactory.class.getName(), DefaultEventFactory.class.getName()));
  375. this.eventFactories = Collections.singletonList((EventFactory)new DefaultEventFactory());
  376. }
  377. if(logger.isDebugEnabled()) {
  378. logger.debug(ResourceMessage.getMessage(9303, EventFactory.class.getName(), this.eventFactories));
  379. }
  380. }
  381. @SuppressWarnings("unchecked")
  382. private void initSipHandlerAdaptors() {
  383. this.sipHandlerAdapters = null;
  384. if(this.detectAllSipHandlerAdapters) {
  385. if(logger.isTraceEnabled()) {
  386. logger.trace(ResourceMessage.getMessage(9301, SipHandlerAdapter.class.getName(), ac));
  387. }
  388. Map matchedBeans =
  389. BeanFactoryUtils.beansOfTypeIncludingAncestors(ac, SipHandlerAdapter.class, true, false);
  390. if(!matchedBeans.isEmpty()) {
  391. this.sipHandlerAdapters = new ArrayList(matchedBeans.values());
  392. Collections.sort(this.sipHandlerAdapters, new OrderComparator());
  393. }
  394. } else {
  395. try {
  396. if(logger.isTraceEnabled()) {
  397. logger.trace(ResourceMessage.getMessage(9302, SIP_HANDLER_ADAPTER_BEAN_NAME, SipHandlerAdapter.class.getName()));
  398. }
  399. SipHandlerAdapter sha =
  400. (SipHandlerAdapter)this.ac.getBean(SIP_HANDLER_ADAPTER_BEAN_NAME, SipHandlerAdapter.class);
  401. this.sipHandlerAdapters = Collections.singletonList(sha);
  402. } catch (NoSuchBeanDefinitionException e) {
  403. // ignore
  404. }
  405. }
  406. if(this.sipHandlerAdapters == null) {
  407. logger.info(ResourceMessage.getMessage(301, SipHandlerAdapter.class.getName(), DefaultSipHandlerAdapter.class.getName()));
  408. this.sipHandlerAdapters = Collections.singletonList((SipHandlerAdapter)new DefaultSipHandlerAdapter());
  409. }
  410. if(logger.isDebugEnabled()) {
  411. logger.debug(ResourceMessage.getMessage(9303, SipHandlerAdapter.class.getName(), this.sipHandlerAdapters));
  412. }
  413. }
  414. @SuppressWarnings("unchecked")
  415. private void initSipHandlerFactories() {
  416. this.sipHandlerFactories = null;
  417. if(this.detectAllSipHandlerFactories) {
  418. if(logger.isTraceEnabled()) {
  419. logger.trace(ResourceMessage.getMessage(9301, SipHandlerFactory.class.getName(), ac));
  420. }
  421. Map matchedBeans =
  422. BeanFactoryUtils.beansOfTypeIncludingAncestors(ac, SipHandlerFactory.class, true, false);
  423. if(logger.isDebugEnabled()) {
  424. logger.debug("initSipHandlerFactories:[matchedBeans=" + matchedBeans + "]");
  425. }
  426. if(!matchedBeans.isEmpty()) {
  427. this.sipHandlerFactories = new ArrayList(matchedBeans.values());
  428. Collections.sort(this.sipHandlerFactories, new OrderComparator());
  429. }
  430. } else {
  431. try {
  432. if(logger.isTraceEnabled()) {
  433. logger.trace(ResourceMessage.getMessage(9302, SIP_HANDLER_FACTORY_BEAN_NAME, SipHandlerFactory.class.getName()));
  434. }
  435. SipHandlerFactory shf =
  436. (SipHandlerFactory)this.ac.getBean(SIP_HANDLER_FACTORY_BEAN_NAME, SipHandlerFactory.class);
  437. this.sipHandlerFactories = Collections.singletonList(shf);
  438. } catch (NoSuchBeanDefinitionException e) {
  439. // ignore
  440. }
  441. }
  442. if(this.sipHandlerFactories == null) {
  443. logger.info(ResourceMessage.getMessage(301, SipHandlerAdapter.class.getName(), DefaultSipHandlerFactory.class.getName()));
  444. this.sipHandlerFactories = Collections.singletonList((SipHandlerFactory)new DefaultSipHandlerFactory());
  445. }
  446. if(logger.isDebugEnabled()) {
  447. logger.debug(ResourceMessage.getMessage(9303, SipHandlerFactory.class.getName(), this.sipHandlerFactories));
  448. }
  449. }
  450. @SuppressWarnings("unchecked")
  451. private void initErrorHandlers() {
  452. this.errorHandlers = null;
  453. if(this.detectAllErrorHandlers) {
  454. if(logger.isTraceEnabled()) {
  455. logger.trace(ResourceMessage.getMessage(9301, ErrorHandler.class.getName(), ac));
  456. }
  457. Map matchedBeans =
  458. BeanFactoryUtils.beansOfTypeIncludingAncestors(ac, ErrorHandler.class, true, false);
  459. if(logger.isDebugEnabled()) {
  460. logger.debug("initErrorHandlers:[matchedBeans=" + matchedBeans + "]");
  461. }
  462. if(!matchedBeans.isEmpty()) {
  463. this.errorHandlers = new ArrayList(matchedBeans.values());
  464. Collections.sort(this.errorHandlers, new OrderComparator());
  465. }
  466. } else {
  467. try {
  468. if(logger.isTraceEnabled()) {
  469. logger.trace(ResourceMessage.getMessage(9302, ERROR_HANDLER_BEAN_NAME, ErrorHandler.class.getName()));
  470. }
  471. ErrorHandler eh =
  472. (ErrorHandler)this.ac.getBean(ERROR_HANDLER_BEAN_NAME, ErrorHandler.class);
  473. this.errorHandlers = Collections.singletonList(eh);
  474. } catch (NoSuchBeanDefinitionException e) {
  475. // ignore
  476. }
  477. }
  478. if(this.errorHandlers == null) {
  479. logger.info(ResourceMessage.getMessage(301, ErrorHandler.class.getName(), DefaultErrorHandler.class.getName()));
  480. this.errorHandlers = Collections.singletonList((ErrorHandler)new DefaultErrorHandler());
  481. }
  482. if(logger.isDebugEnabled()) {
  483. logger.debug(ResourceMessage.getMessage(9303, ErrorHandler.class.getName(), this.errorHandlers));
  484. }
  485. }
  486. private void setupState(SignalingAttributes attr, Map<Object, String> stateMap) {
  487. Set<Map.Entry<Object, String>> set = stateMap.entrySet();
  488. for(Map.Entry<Object, String> entry: set) {
  489. // ?Entry???????????
  490. attr.setStateName(entry.getKey(), entry.getValue());
  491. }
  492. }
  493. private void setupState(SignalingAttributes attr, String stateName) {
  494. // ??????
  495. StringTokenizer token = new StringTokenizer(stateName, stateNameSeparator);
  496. int countTokens = token.countTokens();
  497. if(countTokens == 1) {
  498. // ????????SipApplicationSession????
  499. attr.setStateName(attr.getSipApplicationSession(), stateName);
  500. return;
  501. } else if(countTokens == 2){
  502. // ?????key??????????
  503. // ???SipSesion?ID???????????
  504. // ?session.getId() + ";" + calling???????????????ID?SipSession????
  505. // ?????calling?????????????
  506. String key = token.nextToken();
  507. String name = token.nextToken();
  508. attr.setStateName(key, name);
  509. } else {
  510. // TODO ????????????????????
  511. throw new IllegalArgumentException("Cannot parse state-name:[state-name:" + stateName +
  512. "],[separator:" + stateNameSeparator + "]");
  513. }
  514. }
  515. }