1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
|
/*
* $Id: AbstractConnector.java 11517 2008-03-31 21:34:19Z dirk.olmes $
* --------------------------------------------------------------------------------------
* Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.transport;
import org.mule.DefaultExceptionStrategy;
import org.mule.MuleSessionHandler;
import org.mule.RegistryContext;
import org.mule.api.MessagingException;
import org.mule.api.MuleContext;
import org.mule.api.MuleEvent;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.MuleRuntimeException;
import org.mule.api.config.ThreadingProfile;
import org.mule.api.context.WorkManager;
import org.mule.api.context.notification.ServerNotification;
import org.mule.api.context.notification.ServerNotificationHandler;
import org.mule.api.endpoint.EndpointURI;
import org.mule.api.endpoint.InboundEndpoint;
import org.mule.api.endpoint.OutboundEndpoint;
import org.mule.api.lifecycle.DisposeException;
import org.mule.api.lifecycle.InitialisationException;
import org.mule.api.registry.ServiceDescriptorFactory;
import org.mule.api.registry.ServiceException;
import org.mule.api.service.Service;
import org.mule.api.transport.Connectable;
import org.mule.api.transport.ConnectionStrategy;
import org.mule.api.transport.Connector;
import org.mule.api.transport.ConnectorException;
import org.mule.api.transport.DispatchException;
import org.mule.api.transport.MessageAdapter;
import org.mule.api.transport.MessageDispatcher;
import org.mule.api.transport.MessageDispatcherFactory;
import org.mule.api.transport.MessageReceiver;
import org.mule.api.transport.MessageRequester;
import org.mule.api.transport.MessageRequesterFactory;
import org.mule.api.transport.ReplyToHandler;
import org.mule.api.transport.SessionHandler;
import org.mule.config.i18n.CoreMessages;
import org.mule.context.notification.ConnectionNotification;
import org.mule.context.notification.MessageNotification;
import org.mule.context.notification.OptimisedNotificationHandler;
import org.mule.lifecycle.AlreadyInitialisedException;
import org.mule.model.streaming.DelegatingInputStream;
import org.mule.routing.filters.WildcardFilter;
import org.mule.transformer.TransformerUtils;
import org.mule.transport.service.TransportFactory;
import org.mule.transport.service.TransportServiceDescriptor;
import org.mule.transport.service.TransportServiceException;
import org.mule.util.BeanUtils;
import org.mule.util.ClassUtils;
import org.mule.util.CollectionUtils;
import org.mule.util.ObjectNameHelper;
import org.mule.util.ObjectUtils;
import org.mule.util.StringUtils;
import org.mule.util.concurrent.NamedThreadFactory;
import org.mule.util.concurrent.WaitableBoolean;
import java.beans.ExceptionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.resource.spi.work.WorkEvent;
import javax.resource.spi.work.WorkListener;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
/**
* <code>AbstractConnector</code> provides base functionality for all connectors
* provided with Mule. Connectors are the mechanism used to connect to external
* systems and protocols in order to send and receive data. <p/> The
* <code>AbstractConnector</code> provides getter and setter methods for endpoint
* name, transport name and protocol. It also provides methods to stop and start
* connecotors and sets up a dispatcher threadpool which allows deriving connectors
* the possibility to dispatch work to separate threads. This functionality is
* controlled with the <i> doThreading</i> property on the threadingProfiles for
* dispachers and receivers. The lifecycle for a connector is -
* <ol>
* <li>Create
* <li>Initialise
* <li>Connect
* <li>Connect receivers
* <li>Start
* <li>Start Receivers
* <li>Stop
* <li>Stop Receivers
* <li>Disconnect
* <li>Disconnect Receivers
* <li>Dispose
* <li>Dispose Receivers
* </ol>
*/
public abstract class AbstractConnector
implements Connector, ExceptionListener, Connectable, WorkListener
{
/**
* Default number of concurrent transactional receivers.
*/
public static final int DEFAULT_NUM_CONCURRENT_TX_RECEIVERS = 4;
/**
* logger used by this class
*/
protected final Log logger = LogFactory.getLog(getClass());
/**
* Specifies if the endpoint started
*/
protected final AtomicBoolean started = new AtomicBoolean(false);
/**
* True once the endpoint has been initialsed
*/
protected final AtomicBoolean initialised = new AtomicBoolean(false);
/**
* The name that identifies the endpoint
*/
protected volatile String name;
/**
* The exception strategy used by this connector
*/
protected volatile ExceptionListener exceptionListener;
/**
* Determines in the connector is alive and well
*/
protected final AtomicBoolean disposed = new AtomicBoolean(false);
/**
* Determines in connector has been told to dispose
*/
protected final AtomicBoolean disposing = new AtomicBoolean(false);
/**
* Factory used to create dispatchers for this connector
*/
protected volatile MessageDispatcherFactory dispatcherFactory;
/**
* Factory used to create requesters for this connector
*/
protected volatile MessageRequesterFactory requesterFactory;
/**
* A pool of dispatchers for this connector, keyed by endpoint
*/
protected final GenericKeyedObjectPool dispatchers = new GenericKeyedObjectPool();
/**
* A pool of requesters for this connector, keyed by endpoint
*/
protected final GenericKeyedObjectPool requesters = new GenericKeyedObjectPool();
/**
* The collection of listeners on this connector. Keyed by entrypoint
*/
protected final ConcurrentMap receivers = new ConcurrentHashMap();
/**
* Defines the dispatcher threading profile
*/
private volatile ThreadingProfile dispatcherThreadingProfile;
/**
* Defines the requester threading profile
*/
private volatile ThreadingProfile requesterThreadingProfile;
/**
* Defines the receiver threading profile
*/
private volatile ThreadingProfile receiverThreadingProfile;
/**
* @see {@link #isCreateMultipleTransactedReceivers()}
*/
protected volatile boolean createMultipleTransactedReceivers = true;
/**
* @see {@link #getNumberOfConcurrentTransactedReceivers()}
*/
protected volatile int numberOfConcurrentTransactedReceivers = DEFAULT_NUM_CONCURRENT_TX_RECEIVERS;
protected volatile ConnectionStrategy connectionStrategy;
protected final WaitableBoolean connected = new WaitableBoolean(false);
protected final WaitableBoolean connecting = new WaitableBoolean(false);
/**
* If the connect method was called via the start method, this will be set so
* that when the connector comes on line it will be started
*/
protected final WaitableBoolean startOnConnect = new WaitableBoolean(false);
/**
* Optimise the handling of message notifications. If dynamic is set to false then the
* cached notification handler implements a shortcut for message notifications.
*/
private boolean dynamicNotification = false;
private ServerNotificationHandler cachedNotificationHandler;
private final List supportedProtocols;
/**
* A shared work manager for all receivers registered with this connector.
*/
private final AtomicReference/*<WorkManager>*/ receiverWorkManager = new AtomicReference();
/**
* A shared work manager for all requesters created for this connector.
*/
private final AtomicReference/*<WorkManager>*/ dispatcherWorkManager = new AtomicReference();
/**
* A shared work manager for all requesters created for this connector.
*/
private final AtomicReference/*<WorkManager>*/ requesterWorkManager = new AtomicReference();
/**
* A generic scheduling service for tasks that need to be performed periodically.
*/
private final AtomicReference/*<ScheduledExecutorService>*/ scheduler = new AtomicReference();
/**
* Holds the service configuration for this connector
*/
protected volatile TransportServiceDescriptor serviceDescriptor;
/**
* The map of service overrides that can be used to extend the capabilities of the
* connector
*/
protected volatile Properties serviceOverrides;
/**
* The strategy used for reading and writing session information to and fromt he
* transport
*/
protected volatile SessionHandler sessionHandler = new MuleSessionHandler();
protected MuleContext muleContext;
public AbstractConnector()
{
setDynamicNotification(false);
// always add at least the default protocol
supportedProtocols = new ArrayList();
supportedProtocols.add(getProtocol().toLowerCase());
connectionStrategy = new SingleAttemptConnectionStrategy();
// TODO dispatcher pool configuration should be extracted, maybe even
// moved into the factory?
// NOTE: testOnBorrow MUST be FALSE. this is a bit of a design bug in
// commons-pool since validate is used for both activation and passivation,
// but has no way of knowing which way it is going.
dispatchers.setTestOnBorrow(false);
dispatchers.setTestOnReturn(true);
requesters.setTestOnBorrow(false);
requesters.setTestOnReturn(true);
}
/*
* (non-Javadoc)
*
* @see org.mule.transport.UMOConnector#getName()
*/
public String getName()
{
return name;
}
/*
* (non-Javadoc)
*
* @see org.mule.transport.UMOConnector#setName(java.lang.String)
*/
public void setName(String newName)
{
if (newName == null)
{
throw new IllegalArgumentException(CoreMessages.objectIsNull("Connector name").toString());
}
if (logger.isDebugEnabled())
{
logger.debug("Set Connector name to: " + newName);
}
name = newName;
}
public final synchronized void initialise() throws InitialisationException
{
if (initialised.get())
{
InitialisationException e = new AlreadyInitialisedException("Connector '" + getProtocol() + "." + getName() + "'", this);
throw e;
// Just log a warning since initializing twice is bad but might not be the end of the world.
//logger.warn(e);
}
if (logger.isInfoEnabled())
{
logger.info("Initialising: " + this);
}
// Use lazy-init (in get() methods) for this instead.
//dispatcherThreadingProfile = muleContext.getDefaultMessageDispatcherThreadingProfile();
//requesterThreadingProfile = muleContext.getDefaultMessageRequesterThreadingProfile();
//receiverThreadingProfile = muleContext.getDefaultMessageReceiverThreadingProfile();
// Initialise the structure of this connector
this.initFromServiceDescriptor();
this.doInitialise();
// We do the management context injection here just in case we're using a default ExceptionStrategy
//We always create a default just in case anything goes wrong before
if(exceptionListener==null)
{
exceptionListener = new DefaultExceptionStrategy();
((DefaultExceptionStrategy)exceptionListener).setMuleContext(muleContext);
((DefaultExceptionStrategy)exceptionListener).initialise();
}
try
{
initWorkManagers();
}
catch (MuleException e)
{
throw new InitialisationException(e, this);
}
initialised.set(true);
}
public final synchronized void start() throws MuleException
{
this.checkDisposed();
if (!this.isStarted())
{
//TODO: Not sure about this. Right now the connector will connect only once
// there is an endpoint associated with it and that endpoint is connected.
// Do we also need the option of connecting the connector without any endpoints?
// if (!this.isConnected())
// {
// startOnConnect.set(true);
// this.getConnectionStrategy().connect(this);
// // Only start once we are connected
// return;
// }
if (!this.isConnected())
{
startOnConnect.set(true);
// Don't call getConnectionStrategy(), it clones the connection strategy.
// Connectors should have a single reconnection thread, unlike per receiver/dispatcher
connectionStrategy.connect(this);
// Only start once we are connected
return;
}
if (logger.isInfoEnabled())
{
logger.info("Starting: " + this);
}
// the scheduler is recreated after stop()
ScheduledExecutorService currentScheduler = (ScheduledExecutorService) scheduler.get();
if (currentScheduler == null || currentScheduler.isShutdown())
{
scheduler.set(this.getScheduler());
}
this.doStart();
started.set(true);
if (receivers != null)
{
for (Iterator iterator = receivers.values().iterator(); iterator.hasNext();)
{
MessageReceiver mr = (MessageReceiver) iterator.next();
if (logger.isDebugEnabled())
{
logger.debug("Starting receiver on endpoint: " + mr.getEndpoint().getEndpointURI());
}
mr.start();
}
}
if (logger.isInfoEnabled())
{
logger.info("Started: " + this);
}
}
}
/*
* (non-Javadoc)
*
* @see org.mule.api.transport.Connector#isStarted()
*/
public boolean isStarted()
{
return started.get();
}
public final synchronized void stop() throws MuleException
{
if (this.isDisposed())
{
return;
}
if (this.isStarted())
{
if (logger.isInfoEnabled())
{
logger.info("Stopping: " + this);
}
// shutdown our scheduler service
((ScheduledExecutorService) scheduler.get()).shutdown();
this.doStop();
started.set(false);
// Stop all the receivers on this connector (this will cause them to
// disconnect too)
if (receivers != null)
{
for (Iterator iterator = receivers.values().iterator(); iterator.hasNext();)
{
MessageReceiver mr = (MessageReceiver) iterator.next();
if (logger.isDebugEnabled())
{
logger.debug("Stopping receiver on endpoint: " + mr.getEndpoint().getEndpointURI());
}
mr.stop();
}
}
}
if (this.isConnected())
{
try
{
this.disconnect();
}
catch (Exception e)
{
// TODO MULE-863: What should we really do?
logger.error("Failed to disconnect: " + e.getMessage(), e);
}
}
// make sure the scheduler is gone
scheduler.set(null);
// we do not need to stop the work managers because they do no harm (will just be idle)
// and will be reused on restart without problems.
//TODO RM* THis shouldn't be here this.initialised.set(false);
// started=false already issued above right after doStop()
if (logger.isInfoEnabled())
{
logger.info("Stopped: " + this);
}
}
/*
* (non-Javadoc)
*
* @see org.mule.api.transport.Connector#shutdown()
*/
public final synchronized void dispose()
{
disposing.set(true);
if (logger.isInfoEnabled())
{
logger.info("Disposing: " + this);
}
try
{
this.stop();
}
catch (MuleException e)
{
// TODO MULE-863: What should we really do?
logger.warn("Failed to stop during shutdown: " + e.getMessage(), e);
}
this.disposeReceivers();
this.disposeDispatchers();
this.disposeRequesters();
this.disposeWorkManagers();
this.doDispose();
disposed.set(true);
initialised.set(false);
if (logger.isInfoEnabled())
{
logger.info("Disposed: " + this);
}
}
protected void initWorkManagers() throws MuleException
{
if (receiverWorkManager.get() == null)
{
WorkManager newWorkManager = this.getReceiverThreadingProfile().createWorkManager(
getName() + ".receiver");
if (receiverWorkManager.compareAndSet(null, newWorkManager))
{
newWorkManager.start();
}
}
if (dispatcherWorkManager.get() == null)
{
WorkManager newWorkManager = this.getDispatcherThreadingProfile().createWorkManager(
getName() + ".dispatcher");
if (dispatcherWorkManager.compareAndSet(null, newWorkManager))
{
newWorkManager.start();
}
}
}
protected void disposeWorkManagers()
{
logger.debug("Disposing dispatcher work manager");
WorkManager workManager = (WorkManager) dispatcherWorkManager.get();
if (workManager != null)
{
workManager.dispose();
}
dispatcherWorkManager.set(null);
logger.debug("Disposing receiver work manager");
workManager = (WorkManager) receiverWorkManager.get();
if (workManager != null)
{
workManager.dispose();
}
receiverWorkManager.set(null);
}
protected void disposeReceivers()
{
if (receivers != null)
{
logger.debug("Disposing Receivers");
for (Iterator iterator = receivers.values().iterator(); iterator.hasNext();)
{
MessageReceiver receiver = (MessageReceiver) iterator.next();
try
{
this.destroyReceiver(receiver, receiver.getEndpoint());
}
catch (Throwable e)
{
// TODO MULE-863: What should we really do?
logger.error("Failed to destroy receiver: " + receiver, e);
}
}
receivers.clear();
logger.debug("Receivers Disposed");
}
}
protected void disposeDispatchers()
{
if (dispatchers != null)
{
logger.debug("Disposing Dispatchers");
dispatchers.clear();
logger.debug("Dispatchers Disposed");
}
}
protected void disposeRequesters()
{
if (requesters != null)
{
logger.debug("Disposing Requesters");
requesters.clear();
logger.debug("Requesters Disposed");
}
}
/*
* (non-Javadoc)
*
* @see org.mule.api.transport.Connector#isAlive()
*/
public boolean isDisposed()
{
return disposed.get();
}
/*
* (non-Javadoc)
*
* @see org.mule.api.transport.Connector#handleException(java.lang.Object,
* java.lang.Throwable)
*/
public void handleException(Exception exception)
{
if (exceptionListener == null)
{
throw new MuleRuntimeException(
CoreMessages.exceptionOnConnectorNotExceptionListener(this.getName()), exception);
}
else
{
exceptionListener.exceptionThrown(exception);
}
}
/*
* (non-Javadoc)
*
* @see org.mule.util.ExceptionListener#onException(java.lang.Throwable)
*/
public void exceptionThrown(Exception e)
{
handleException(e);
}
/**
* @return the ExceptionStrategy for this endpoint
* @see ExceptionListener
*/
public ExceptionListener getExceptionListener()
{
return exceptionListener;
}
/**
* @param listener the ExceptionStrategy to use with this endpoint
* @see ExceptionListener
*/
public void setExceptionListener(ExceptionListener listener)
{
exceptionListener = listener;
}
/**
* @return Returns the dispatcherFactory.
*/
public MessageDispatcherFactory getDispatcherFactory()
{
return dispatcherFactory;
}
/**
* @param dispatcherFactory The dispatcherFactory to set.
*/
public void setDispatcherFactory(MessageDispatcherFactory dispatcherFactory)
{
KeyedPoolableObjectFactory poolFactory;
if (dispatcherFactory instanceof KeyedPoolableObjectFactory)
{
poolFactory = (KeyedPoolableObjectFactory) dispatcherFactory;
}
else
{
// need to adapt the factory for use by commons-pool
poolFactory = new KeyedPoolMessageDispatcherFactoryAdapter(dispatcherFactory);
}
this.dispatchers.setFactory(poolFactory);
// we keep a reference to the unadapted factory, otherwise people might end
// up with ClassCastExceptions on downcast to their implementation (sigh)
this.dispatcherFactory = dispatcherFactory;
}
/**
* @return Returns the requesterFactory.
*/
public MessageRequesterFactory getRequesterFactory()
{
return requesterFactory;
}
/**
* @param requesterFactory The requesterFactory to set.
*/
public void setRequesterFactory(MessageRequesterFactory requesterFactory)
{
KeyedPoolableObjectFactory poolFactory;
if (requesterFactory instanceof KeyedPoolableObjectFactory)
{
poolFactory = (KeyedPoolableObjectFactory) requesterFactory;
}
else
{
// need to adapt the factory for use by commons-pool
poolFactory = new KeyedPoolMessageRequesterFactoryAdapter(requesterFactory);
}
requesters.setFactory(poolFactory);
// we keep a reference to the unadapted factory, otherwise people might end
// up with ClassCastExceptions on downcast to their implementation (sigh)
this.requesterFactory = requesterFactory;
}
/**
* Returns the maximum number of dispatchers that can be concurrently active per
* endpoint.
*
* @return max. number of active dispatchers
*/
public int getMaxDispatchersActive()
{
return this.dispatchers.getMaxActive();
}
/**
* Configures the maximum number of dispatchers that can be concurrently active
* per endpoint
*
* @param maxActive max. number of active dispatchers
*/
public void setMaxDispatchersActive(int maxActive)
{
this.dispatchers.setMaxActive(maxActive);
// adjust maxIdle in tandem to avoid thrashing
this.dispatchers.setMaxIdle(maxActive);
}
private MessageDispatcher getDispatcher(OutboundEndpoint endpoint) throws MuleException
{
this.checkDisposed();
if (endpoint == null)
{
throw new IllegalArgumentException("Endpoint must not be null");
}
if (!supportsProtocol(endpoint.getConnector().getProtocol()))
{
throw new IllegalArgumentException(
CoreMessages.connectorSchemeIncompatibleWithEndpointScheme(this.getProtocol(),
endpoint.getEndpointURI().toString()).getMessage());
}
MessageDispatcher dispatcher = null;
try
{
if (logger.isDebugEnabled())
{
logger.debug("Borrowing a dispatcher for endpoint: " + endpoint.getEndpointURI());
}
dispatcher = (MessageDispatcher)dispatchers.borrowObject(endpoint);
if (logger.isDebugEnabled())
{
logger.debug("Borrowed a dispatcher for endpoint: " + endpoint.getEndpointURI() + " = "
+ dispatcher.toString());
}
return dispatcher;
}
catch (Exception ex)
{
throw new ConnectorException(CoreMessages.connectorCausedError(), this, ex);
}
finally
{
try
{
if (logger.isDebugEnabled())
{
logger.debug("Borrowed dispatcher: " + ObjectUtils.toString(dispatcher, "null"));
}
}
catch (Exception ex)
{
throw new ConnectorException(CoreMessages.connectorCausedError(), this, ex);
}
}
}
private void returnDispatcher(OutboundEndpoint endpoint, MessageDispatcher dispatcher)
{
if (endpoint != null && dispatcher != null)
{
try
{
if (logger.isDebugEnabled())
{
logger.debug("Returning dispatcher for endpoint: " + endpoint.getEndpointURI() + " = "
+ dispatcher.toString());
}
}
catch (Exception ex)
{
//Logging failed
}
finally
{
try
{
dispatchers.returnObject(endpoint, dispatcher);
}
catch (Exception e)
{
// TODO MULE-863: What should we really do?
// ignore - if the dispatcher is broken, it will likely get cleaned
// up by the factory
//RM* I think we should at least log this error so give some indication of what is failing
logger.error("Failed to dispose dispatcher for endpoint: " + endpoint +
". This will cause a memory leak. Please report to", e);
}
}
}
}
/**
* Returns the maximum number of requesters that can be concurrently active per
* endpoint.
*
* @return max. number of active requesters
*/
public int getMaxRequestersActive()
{
return this.requesters.getMaxActive();
}
/**
* Configures the maximum number of requesters that can be concurrently active
* per endpoint
*
* @param maxActive max. number of active requesters
*/
public void setMaxRequestersActive(int maxActive)
{
this.requesters.setMaxActive(maxActive);
// adjust maxIdle in tandem to avoid thrashing
this.requesters.setMaxIdle(maxActive);
}
private MessageRequester getRequester(InboundEndpoint endpoint) throws MuleException
{
this.checkDisposed();
if (endpoint == null)
{
throw new IllegalArgumentException("Endpoint must not be null");
}
if (!supportsProtocol(endpoint.getConnector().getProtocol()))
{
throw new IllegalArgumentException(
CoreMessages.connectorSchemeIncompatibleWithEndpointScheme(this.getProtocol(),
endpoint.getEndpointURI().toString()).getMessage());
}
MessageRequester requester = null;
try
{
if (logger.isDebugEnabled())
{
logger.debug("Borrowing a requester for endpoint: " + endpoint.getEndpointURI());
}
requester = (MessageRequester)requesters.borrowObject(endpoint);
if (logger.isDebugEnabled())
{
logger.debug("Borrowed a requester for endpoint: " + endpoint.getEndpointURI() + " = "
+ requester.toString());
}
return requester;
}
catch (Exception ex)
{
throw new ConnectorException(CoreMessages.connectorCausedError(), this, ex);
}
finally
{
try
{
if (logger.isDebugEnabled())
{
logger.debug("Borrowed requester: " + ObjectUtils.toString(requester, "null"));
}
}
catch (Exception ex)
{
throw new ConnectorException(CoreMessages.connectorCausedError(), this, ex);
}
}
}
private void returnRequester(InboundEndpoint endpoint, MessageRequester requester)
{
if (endpoint != null && requester != null)
{
try
{
if (logger.isDebugEnabled())
{
logger.debug("Returning requester for endpoint: " + endpoint.getEndpointURI() + " = "
+ requester.toString());
}
}
catch (Exception ex)
{
//Logging failed
}
finally
{
try
{
requesters.returnObject(endpoint, requester);
}
catch (Exception e)
{
// TODO MULE-863: What should we really do?
// ignore - if the requester is broken, it will likely get cleaned
// up by the factory
//RM* I think we should at least log this error so give some indication of what is failing
logger.error("Failed to dispose requester for endpoint: " + endpoint +
". This will cause a memory leak. Please report to", e);
}
}
}
}
protected void checkDisposed() throws DisposeException
{
if (this.isDisposed())
{
throw new DisposeException(CoreMessages.cannotUseDisposedConnector(), this);
}
}
public MessageReceiver registerListener(Service service, InboundEndpoint endpoint) throws Exception
{
if (endpoint == null)
{
throw new IllegalArgumentException("The endpoint cannot be null when registering a listener");
}
if (service == null)
{
throw new IllegalArgumentException("The service cannot be null when registering a listener");
}
EndpointURI endpointUri = endpoint.getEndpointURI();
if (endpointUri == null)
{
throw new ConnectorException(CoreMessages.endpointIsNullForListener(), this);
}
logger.info("Registering listener: " + service.getName() + " on endpointUri: "
+ endpointUri.toString());
if (getReceiver(service, endpoint) != null)
{
throw new ConnectorException(CoreMessages.listenerAlreadyRegistered(endpointUri), this);
}
MessageReceiver receiver = createReceiver(service, endpoint);
Object receiverKey = getReceiverKey(service, endpoint);
receiver.setReceiverKey(receiverKey.toString());
// Since we're managing the creation we also need to initialise
receiver.initialise();
receivers.put(receiverKey, receiver);
// receivers.put(getReceiverKey(service, endpoint), receiver);
return receiver;
}
/**
* The method determines the key used to store the receiver against.
*
* @param service the service for which the endpoint is being registered
* @param endpoint the endpoint being registered for the service
* @return the key to store the newly created receiver against
*/
protected Object getReceiverKey(Service service, InboundEndpoint endpoint)
{
return StringUtils.defaultIfEmpty(endpoint.getEndpointURI().getFilterAddress(), endpoint
.getEndpointURI().getAddress());
}
public final void unregisterListener(Service service, InboundEndpoint endpoint) throws Exception
{
if (service == null)
{
throw new IllegalArgumentException(
"The service must not be null when you unregister a listener");
}
if (endpoint == null)
{
throw new IllegalArgumentException("The endpoint must not be null when you unregister a listener");
}
EndpointURI endpointUri = endpoint.getEndpointURI();
if (endpointUri == null)
{
throw new IllegalArgumentException(
"The endpointUri must not be null when you unregister a listener");
}
if (logger.isInfoEnabled())
{
logger.info("Removing listener on endpointUri: " + endpointUri);
}
if (receivers != null && !receivers.isEmpty())
{
MessageReceiver receiver = (MessageReceiver)receivers.remove(getReceiverKey(service,
endpoint));
if (receiver != null)
{
destroyReceiver(receiver, endpoint);
receiver.dispose();
}
}
}
/**
* Getter for property 'dispatcherThreadingProfile'.
*
* @return Value for property 'dispatcherThreadingProfile'.
*/
public ThreadingProfile getDispatcherThreadingProfile()
{
if (dispatcherThreadingProfile == null && muleContext != null)
{
dispatcherThreadingProfile = muleContext.getDefaultMessageDispatcherThreadingProfile();
}
return dispatcherThreadingProfile;
}
/**
* Setter for property 'dispatcherThreadingProfile'.
*
* @param dispatcherThreadingProfile Value to set for property
* 'dispatcherThreadingProfile'.
*/
public void setDispatcherThreadingProfile(ThreadingProfile dispatcherThreadingProfile)
{
this.dispatcherThreadingProfile = dispatcherThreadingProfile;
}
/**
* Getter for property 'requesterThreadingProfile'.
*
* @return Value for property 'requesterThreadingProfile'.
*/
public ThreadingProfile getRequesterThreadingProfile()
{
if (requesterThreadingProfile == null && muleContext != null)
{
requesterThreadingProfile = muleContext.getDefaultMessageRequesterThreadingProfile();
}
return requesterThreadingProfile;
}
/**
* Setter for property 'requesterThreadingProfile'.
*
* @param requesterThreadingProfile Value to set for property
* 'requesterThreadingProfile'.
*/
public void setRequesterThreadingProfile(ThreadingProfile requesterThreadingProfile)
{
this.requesterThreadingProfile = requesterThreadingProfile;
}
/**
* Getter for property 'receiverThreadingProfile'.
*
* @return Value for property 'receiverThreadingProfile'.
*/
public ThreadingProfile getReceiverThreadingProfile()
{
if (receiverThreadingProfile == null && muleContext != null)
{
receiverThreadingProfile = muleContext.getDefaultMessageReceiverThreadingProfile();
}
return receiverThreadingProfile;
}
/**
* Setter for property 'receiverThreadingProfile'.
*
* @param receiverThreadingProfile Value to set for property
* 'receiverThreadingProfile'.
*/
public void setReceiverThreadingProfile(ThreadingProfile receiverThreadingProfile)
{
this.receiverThreadingProfile = receiverThreadingProfile;
}
public void destroyReceiver(MessageReceiver receiver, InboundEndpoint endpoint) throws Exception
{
receiver.dispose();
}
protected abstract void doInitialise() throws InitialisationException;
/**
* Template method to perform any work when destroying the connectoe
*/
protected abstract void doDispose();
/**
* Template method to perform any work when starting the connectoe
*
* @throws MuleException if the method fails
*/
protected abstract void doStart() throws MuleException;
/**
* Template method to perform any work when stopping the connectoe
*
* @throws MuleException if the method fails
*/
protected abstract void doStop() throws MuleException;
public List getDefaultInboundTransformers()
{
if (serviceDescriptor == null)
{
throw new RuntimeException("serviceDescriptor not initialized");
}
return TransformerUtils.getDefaultInboundTransformers(serviceDescriptor);
}
public List getDefaultResponseTransformers()
{
if (serviceDescriptor == null)
{
throw new RuntimeException("serviceDescriptor not initialized");
}
return TransformerUtils.getDefaultResponseTransformers(serviceDescriptor);
}
public List getDefaultOutboundTransformers()
{
if (serviceDescriptor == null)
{
throw new RuntimeException("serviceDescriptor not initialized");
}
return TransformerUtils.getDefaultOutboundTransformers(serviceDescriptor);
}
/**
* Getter for property 'replyToHandler'.
*
* @return Value for property 'replyToHandler'.
*/
public ReplyToHandler getReplyToHandler()
{
return new DefaultReplyToHandler(getDefaultResponseTransformers());
}
/**
* Fires a server notification to all registered listeners
*
* @param notification the notification to fire.
*/
public void fireNotification(ServerNotification notification)
{
cachedNotificationHandler.fireNotification(notification);
}
/**
* Getter for property 'connectionStrategy'.
*
* @return Value for property 'connectionStrategy'.
*/
//TODO RM* REMOVE
public ConnectionStrategy getConnectionStrategy()
{
// not happy with this but each receiver needs its own instance
// of the connection strategy and using a factory just introduces extra
// implementation
try
{
return (ConnectionStrategy) BeanUtils.cloneBean(connectionStrategy);
}
catch (Exception e)
{
throw new MuleRuntimeException(CoreMessages.failedToClone("connectionStrategy"), e);
}
}
/**
* Setter for property 'connectionStrategy'.
*
* @param connectionStrategy Value to set for property 'connectionStrategy'.
*/
public void setConnectionStrategy(ConnectionStrategy connectionStrategy)
{
this.connectionStrategy = connectionStrategy;
}
/** {@inheritDoc} */
public boolean isDisposing()
{
return disposing.get();
}
public boolean isRemoteSyncEnabled()
{
return false;
}
public boolean isSyncEnabled(String protocol)
{
return false;
}
public MessageReceiver getReceiver(Service service, InboundEndpoint endpoint)
{
if (receivers != null)
{
Object key = getReceiverKey(service, endpoint);
if (key != null)
{
return (MessageReceiver) receivers.get(key);
}
else
{
throw new RuntimeException("getReceiverKey() returned a null key");
}
}
else
{
throw new RuntimeException("Connector has not been initialized.");
}
}
/**
* Getter for property 'receivers'.
*
* @return Value for property 'receivers'.
*/
public Map getReceivers()
{
return Collections.unmodifiableMap(receivers);
}
public MessageReceiver lookupReceiver(String key)
{
if (key != null)
{
return (MessageReceiver) receivers.get(key);
}
else
{
throw new IllegalArgumentException("Receiver key must not be null");
}
}
public MessageReceiver[] getReceivers(String wildcardExpression)
{
WildcardFilter filter = new WildcardFilter(wildcardExpression);
filter.setCaseSensitive(false);
List found = new ArrayList();
for (Iterator iterator = receivers.entrySet().iterator(); iterator.hasNext();)
{
Map.Entry e = (Map.Entry) iterator.next();
if (filter.accept(e.getKey()))
{
found.add(e.getValue());
}
}
return (MessageReceiver[]) CollectionUtils.toArrayOfComponentType(found,
MessageReceiver.class);
}
public void connect() throws Exception
{
this.checkDisposed();
if (connected.get())
{
return;
}
/*
Until the recursive startConnector() -> connect() -> doConnect() -> connect()
calls are unwound between a connector and connection strategy, this call has
to be here, and not below (commented out currently). Otherwise, e.g. WebspherMQ
goes into an endless reconnect thrashing loop, see MULE-1150 for more details.
*/
try
{
if (connecting.get())
{
this.doConnect();
}
if (connecting.compareAndSet(false, true))
{
if (logger.isDebugEnabled())
{
logger.debug("Connecting: " + this);
}
connectionStrategy.connect(this);
logger.info("Connected: " + getConnectionDescription());
// This method calls itself so the connecting flag is set first, then
// the connection is made on the second call
return;
}
// see the explanation above
//this.doConnect();
connected.set(true);
connecting.set(false);
this.fireNotification(new ConnectionNotification(this, getConnectEventId(),
ConnectionNotification.CONNECTION_CONNECTED));
}
catch (Exception e)
{
connected.set(false);
connecting.set(false);
this.fireNotification(new ConnectionNotification(this, getConnectEventId(),
ConnectionNotification.CONNECTION_FAILED));
if (e instanceof ConnectException || e instanceof FatalConnectException)
{
// rethrow
throw e;
}
else
{
throw new ConnectException(e, this);
}
}
if (startOnConnect.get())
{
this.start();
}
//TODO RM*. If the connection strategy is called on the receivers, the connector strategy gets called too,
//to ensure its connected. Therefore the connect method on the connector needs to be idempotent and not try
//and connect dispatchers or receivers
// else
// {
// for (Iterator iterator = receivers.values().iterator(); iterator.hasNext();)
// {
// MessageReceiver receiver = (MessageReceiver)iterator.next();
// if (logger.isDebugEnabled())
// {
// logger.debug("Connecting receiver on endpoint: "
// + receiver.getEndpoint().getEndpointURI());
// }
// receiver.connect();
// }
// }
}
public void disconnect() throws Exception
{
startOnConnect.set(this.isStarted());
this.fireNotification(new ConnectionNotification(this, getConnectEventId(),
ConnectionNotification.CONNECTION_DISCONNECTED));
connected.set(false);
try
{
this.doDisconnect();
}
finally
{
this.stop();
}
logger.info("Disconnected: " + this.getConnectionDescription());
}
public String getConnectionDescription()
{
return this.toString();
}
public final boolean isConnected()
{
return connected.get();
}
/**
* Template method where any connections should be made for the connector
*
* @throws Exception
*/
protected abstract void doConnect() throws Exception;
/**
* Template method where any connected resources used by the connector should be
* disconnected
*
* @throws Exception
*/
protected abstract void doDisconnect() throws Exception;
/**
* The resource id used when firing ConnectEvents from this connector
*
* @return the resource id used when firing ConnectEvents from this connector
*/
protected String getConnectEventId()
{
return getName();
}
/**
* For better throughput when using TransactedMessageReceivers this will enable a
* number of concurrent receivers, based on the value returned by
* {@link #getNumberOfConcurrentTransactedReceivers()}. This property is used by
* transports that support transactions, specifically receivers that extend the
* TransactedPollingMessageReceiver.
*
* @return true if multiple receivers will be enabled for this connection
*/
public boolean isCreateMultipleTransactedReceivers()
{
return createMultipleTransactedReceivers;
}
/**
* @see {@link #isCreateMultipleTransactedReceivers()}
* @param createMultipleTransactedReceivers if true, multiple receivers will be
* created for this connection
*/
public void setCreateMultipleTransactedReceivers(boolean createMultipleTransactedReceivers)
{
this.createMultipleTransactedReceivers = createMultipleTransactedReceivers;
}
/**
* Returns the number of concurrent receivers that will be launched when
* {@link #isCreateMultipleTransactedReceivers()} returns <code>true</code>.
*
* @see #DEFAULT_NUM_CONCURRENT_TX_RECEIVERS
*/
public int getNumberOfConcurrentTransactedReceivers()
{
return numberOfConcurrentTransactedReceivers;
}
/**
* @see {@link #getNumberOfConcurrentTransactedReceivers()}
* @param count the number of concurrent transacted receivers to start
*/
public void setNumberOfConcurrentTransactedReceivers(int count)
{
numberOfConcurrentTransactedReceivers = count;
}
public void setDynamicNotification(boolean dynamic)
{
dynamicNotification = dynamic;
}
protected void updateCachedNotificationHandler()
{
if (null != muleContext)
{
if (dynamicNotification)
{
cachedNotificationHandler = muleContext.getNotificationManager();
}
else
{
cachedNotificationHandler =
new OptimisedNotificationHandler(muleContext.getNotificationManager(), MessageNotification.class);
}
}
}
public boolean isEnableMessageEvents()
{
return cachedNotificationHandler.isNotificationEnabled(MessageNotification.class);
}
/**
* Registers other protocols 'understood' by this connector. These must contain
* scheme meta info. Any protocol registered must begin with the protocol of this
* connector, i.e. If the connector is axis the protocol for jms over axis will
* be axis:jms. Here, 'axis' is the scheme meta info and 'jms' is the protocol.
* If the protocol argument does not start with the connector's protocol, it will
* be appended.
*
* @param protocol the supported protocol to register
*/
public void registerSupportedProtocol(String protocol)
{
protocol = protocol.toLowerCase();
if (protocol.startsWith(getProtocol().toLowerCase()))
{
registerSupportedProtocolWithoutPrefix(protocol);
}
else
{
supportedProtocols.add(getProtocol().toLowerCase() + ":" + protocol);
}
}
/**
* Registers other protocols 'understood' by this connector. These must contain
* scheme meta info. Unlike the {@link #registerSupportedProtocol(String)} method,
* this allows you to register protocols that are not prefixed with the connector
* protocol. This is useful where you use a Service Finder to discover which
* Transport implementation to use. For example the 'wsdl' transport is a generic
* 'finder' transport that will use Axis, Xfire or Glue to create the WSDL
* client. These transport protocols would be wsdl-axis, wsdl-xfire and
* wsdl-glue, but they can all support 'wsdl' protocol too.
*
* @param protocol the supported protocol to register
*/
protected void registerSupportedProtocolWithoutPrefix(String protocol)
{
supportedProtocols.add(protocol.toLowerCase());
}
public void unregisterSupportedProtocol(String protocol)
{
protocol = protocol.toLowerCase();
if (protocol.startsWith(getProtocol().toLowerCase()))
{
supportedProtocols.remove(protocol);
}
else
{
supportedProtocols.remove(getProtocol().toLowerCase() + ":" + protocol);
}
}
/**
* @return true if the protocol is supported by this connector.
*/
public boolean supportsProtocol(String protocol)
{
return supportedProtocols.contains(protocol.toLowerCase());
}
/**
* Returns an unmodifiable list of the protocols supported by this connector
*
* @return an unmodifiable list of the protocols supported by this connector
*/
public List getSupportedProtocols()
{
return Collections.unmodifiableList(supportedProtocols);
}
/**
* Sets A list of protocols that the connector can accept
*
* @param supportedProtocols
*/
public void setSupportedProtocols(List supportedProtocols)
{
for (Iterator iterator = supportedProtocols.iterator(); iterator.hasNext();)
{
String s = (String) iterator.next();
registerSupportedProtocol(s);
}
}
/**
* Returns a work manager for message receivers.
*/
protected WorkManager getReceiverWorkManager(String receiverName) throws MuleException
{
return (WorkManager) receiverWorkManager.get();
}
/**
* Returns a work manager for message dispatchers.
*
* @throws MuleException in case of error
*/
protected WorkManager getDispatcherWorkManager() throws MuleException
{
return (WorkManager) dispatcherWorkManager.get();
}
/**
* Returns a work manager for message requesters.
*
* @throws MuleException in case of error
*/
protected WorkManager getRequesterWorkManager() throws MuleException
{
return (WorkManager) requesterWorkManager.get();
}
/**
* Returns a Scheduler service for periodic tasks, currently limited to internal
* use. Note: getScheduler() currently conflicts with the same method in the
* Quartz transport
*/
public ScheduledExecutorService getScheduler()
{
if (scheduler.get() == null)
{
ThreadFactory threadFactory = new NamedThreadFactory(this.getName() + ".scheduler");
ScheduledThreadPoolExecutor newExecutor = new ScheduledThreadPoolExecutor(4, threadFactory);
newExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
newExecutor.setKeepAliveTime(this.getReceiverThreadingProfile().getThreadTTL(),
TimeUnit.MILLISECONDS);
newExecutor.allowCoreThreadTimeOut(true);
if (!scheduler.compareAndSet(null, newExecutor))
{
// someone else was faster, ditch our copy.
newExecutor.shutdown();
}
}
return (ScheduledExecutorService) scheduler.get();
}
/**
* Getter for property 'sessionHandler'.
*
* @return Value for property 'sessionHandler'.
*/
public SessionHandler getSessionHandler()
{
return sessionHandler;
}
/**
* Setter for property 'sessionHandler'.
*
* @param sessionHandler Value to set for property 'sessionHandler'.
*/
public void setSessionHandler(SessionHandler sessionHandler)
{
this.sessionHandler = sessionHandler;
}
public void workAccepted(WorkEvent event)
{
this.handleWorkException(event, "workAccepted");
}
public void workRejected(WorkEvent event)
{
this.handleWorkException(event, "workRejected");
}
public void workStarted(WorkEvent event)
{
this.handleWorkException(event, "workStarted");
}
public void workCompleted(WorkEvent event)
{
this.handleWorkException(event, "workCompleted");
}
protected void handleWorkException(WorkEvent event, String type)
{
if (event == null)
{
return;
}
Throwable e = event.getException();
if (e == null)
{
return;
}
if (e.getCause() != null)
{
e = e.getCause();
}
logger.error("Work caused exception on '" + type + "'. Work being executed was: "
+ event.getWork().toString());
if (e instanceof Exception)
{
this.handleException((Exception) e);
}
else
{
throw new MuleRuntimeException(CoreMessages.connectorCausedError(this.getName()), e);
}
}
// TODO the following methods should probably be lifecycle-enabled;
// for now they are only stubs to get the refactoring going.
public void dispatch(OutboundEndpoint endpoint, MuleEvent event) throws DispatchException
{
MessageDispatcher dispatcher = null;
try
{
dispatcher = this.getDispatcher(endpoint);
dispatcher.dispatch(event);
}
catch (DispatchException dex)
{
throw dex;
}
catch (MuleException ex)
{
throw new DispatchException(event.getMessage(), endpoint, ex);
}
finally
{
this.returnDispatcher(endpoint, dispatcher);
}
}
/**
* This method will return the dispatcher to the pool or, if the payload is an inputstream,
* replace the payload with a new DelegatingInputStream which returns the dispatcher to
* the pool when the stream is closed.
*
* @param endpoint
* @param dispatcher
* @param result
*/
protected void setupDispatchReturn(final OutboundEndpoint endpoint,
final MessageDispatcher dispatcher,
MuleMessage result)
{
if (result != null && result.getPayload() instanceof InputStream)
{
DelegatingInputStream is = new DelegatingInputStream((InputStream)result.getPayload())
{
public void close() throws IOException
{
try
{
super.close();
}
finally
{
returnDispatcher(endpoint, dispatcher);
}
}
};
result.setPayload(is);
}
else
{
this.returnDispatcher(endpoint, dispatcher);
}
}
public MuleMessage request(String uri, long timeout) throws Exception
{
return request(getMuleContext().getRegistry().lookupEndpointFactory().getInboundEndpoint(uri),
timeout);
}
public MuleMessage request(InboundEndpoint endpoint, long timeout) throws Exception
{
MessageRequester requester = null;
MuleMessage result = null;
try
{
requester = this.getRequester(endpoint);
result = requester.request(timeout);
return result;
}
finally
{
setupRequestReturn(endpoint, requester, result);
}
}
/**
* This method will return the requester to the pool or, if the payload is an inputstream,
* replace the payload with a new DelegatingInputStream which returns the requester to
* the pool when the stream is closed.
*
* @param endpoint
* @param requester
* @param result
*/
protected void setupRequestReturn(final InboundEndpoint endpoint,
final MessageRequester requester,
MuleMessage result)
{
if (result != null && result.getPayload() instanceof InputStream)
{
DelegatingInputStream is = new DelegatingInputStream((InputStream)result.getPayload())
{
public void close() throws IOException
{
try
{
super.close();
}
finally
{
returnRequester(endpoint, requester);
}
}
};
result.setPayload(is);
}
else
{
this.returnRequester(endpoint, requester);
}
}
public MuleMessage send(OutboundEndpoint endpoint, MuleEvent event) throws DispatchException
{
MessageDispatcher dispatcher = null;
try
{
dispatcher = this.getDispatcher(endpoint);
return dispatcher.send(event);
}
catch (DispatchException dex)
{
throw dex;
}
catch (MuleException ex)
{
throw new DispatchException(event.getMessage(), endpoint, ex);
}
finally
{
this.returnDispatcher(endpoint, dispatcher);
}
}
// -------- Methods from the removed AbstractServiceEnabled Connector
/**
* When this connector is created via the
* {@link org.mule.transport.service.TransportFactory} the endpoint used to
* determine the connector type is passed to this method so that any properties
* set on the endpoint that can be used to initialise the connector are made
* available.
*
* @param endpointUri the {@link EndpointURI} use to create this connector
* @throws InitialisationException If there are any problems with the
* configuration set on the Endpoint or if another exception is
* thrown it is wrapped in an InitialisationException.
*/
public void initialiseFromUrl(EndpointURI endpointUri) throws InitialisationException
{
if (!supportsProtocol(endpointUri.getFullScheme()))
{
throw new InitialisationException(
CoreMessages.schemeNotCompatibleWithConnector(endpointUri.getFullScheme(),
this.getClass()), this);
}
Properties props = new Properties();
props.putAll(endpointUri.getParams());
// auto set username and password
if (endpointUri.getUserInfo() != null)
{
props.setProperty("username", endpointUri.getUser());
String passwd = endpointUri.getPassword();
if (passwd != null)
{
props.setProperty("password", passwd);
}
}
String host = endpointUri.getHost();
if (host != null)
{
props.setProperty("hostname", host);
props.setProperty("host", host);
}
if (endpointUri.getPort() > -1)
{
props.setProperty("port", String.valueOf(endpointUri.getPort()));
}
org.mule.util.BeanUtils.populateWithoutFail(this, props, true);
setName(ObjectNameHelper.getConnectorName(this));
//initialise();
}
/**
* Initialises this connector from its {@link TransportServiceDescriptor} This
* will be called before the {@link #doInitialise()} method is called.
*
* @throws InitialisationException InitialisationException If there are any
* problems with the configuration or if another exception is thrown
* it is wrapped in an InitialisationException.
*/
protected synchronized void initFromServiceDescriptor() throws InitialisationException
{
try
{
serviceDescriptor = (TransportServiceDescriptor)
RegistryContext.getRegistry().lookupServiceDescriptor(ServiceDescriptorFactory.PROVIDER_SERVICE_TYPE, getProtocol().toLowerCase(), serviceOverrides);
if (serviceDescriptor == null)
{
throw new ServiceException(CoreMessages.noServiceTransportDescriptor(getProtocol()));
}
if (logger.isDebugEnabled())
{
logger.debug("Loading DispatcherFactory for connector: " + getName() + " (" + getClass().getName() + ")");
}
MessageDispatcherFactory df = serviceDescriptor.createDispatcherFactory();
if (df != null)
{
this.setDispatcherFactory(df);
}
else if (logger.isDebugEnabled())
{
logger.debug("Transport '" + getProtocol() + "' will not support outbound endpoints: ");
}
if (logger.isDebugEnabled())
{
logger.debug("Loading RequesterFactory for connector: " + getName() + " (" + getClass().getName() + ")");
}
MessageRequesterFactory rf = serviceDescriptor.createRequesterFactory();
if (rf != null)
{
this.setRequesterFactory(rf);
}
else if (logger.isDebugEnabled())
{
logger.debug("Transport '" + getProtocol() + "' will not support requests: ");
}
sessionHandler = serviceDescriptor.createSessionHandler();
// TODO Do we still need to support this for 2.x?
// Set any manager default properties for the connector. These are set on
// the Manager with a protocol e.g. jms.specification=1.1
// This provides a really convenient way to set properties on an object
// from unit tests
// Map props = new HashMap();
// PropertiesUtils.getPropertiesWithPrefix(muleContext.getRegistry().lookupProperties(), getProtocol()
// .toLowerCase(), props);
// if (props.size() > 0)
// {
// props = PropertiesUtils.removeNamespaces(props);
// org.mule.util.BeanUtils.populateWithoutFail(this, props, true);
// }
}
catch (Exception e)
{
throw new InitialisationException(e, this);
}
}
/**
* Get the {@link TransportServiceDescriptor} for this connector. This will be
* null if the connector was created by the developer. To create a connector the
* proper way the developer should use the {@link TransportFactory} and pass in
* an endpoint.
*
* @return the {@link TransportServiceDescriptor} for this connector
*/
protected TransportServiceDescriptor getServiceDescriptor()
{
if (serviceDescriptor == null)
{
throw new IllegalStateException("This connector has not yet been initialised: " + name);
}
return serviceDescriptor;
}
/**
* Create a Message receiver for this connector
*
* @param service the service that will receive events from this receiver,
* the listener
* @param endpoint the endpoint that defies this inbound communication
* @return an instance of the message receiver defined in this connectors'
* {@link org.mule.transport.service.TransportServiceDescriptor}
* initialised using the service and endpoint.
* @throws Exception if there is a problem creating the receiver. This exception
* really depends on the underlying transport, thus any exception
* could be thrown
*/
protected MessageReceiver createReceiver(Service service, InboundEndpoint endpoint)
throws Exception
{
return getServiceDescriptor().createMessageReceiver(this, service, endpoint);
}
/**
* Gets a <code>MessageAdapter</code> for the endpoint for the given message
* (data)
*
* @param message the data with which to initialise the
* <code>MessageAdapter</code>
* @return the <code>MessageAdapter</code> for the endpoint
* @throws org.mule.api.MessagingException if the message parameter is not
* supported
* @see org.mule.api.transport.MessageAdapter
*/
public MessageAdapter getMessageAdapter(Object message) throws MessagingException
{
try
{
return serviceDescriptor.createMessageAdapter(message);
}
catch (TransportServiceException e)
{
throw new MessagingException(CoreMessages.failedToCreate("Message Adapter"),
message, e);
}
}
/**
* A map of fully qualified class names that should override those in the
* connectors' service descriptor This map will be null if there are no overrides
*
* @return a map of override values or null
*/
public Map getServiceOverrides()
{
return serviceOverrides;
}
/**
* Set the Service overrides on this connector.
*
* @param serviceOverrides the override values to use
*/
public void setServiceOverrides(Map serviceOverrides)
{
this.serviceOverrides = new Properties();
this.serviceOverrides.putAll(serviceOverrides);
}
/**
* Will get the output stream for this type of transport. Typically this
* will be called only when Streaming is being used on an outbound endpoint.
* If Streaming is not supported by this transport an {@link UnsupportedOperationException}
* is thrown. Note that the stream MUST release resources on close. For help doing so, see
* {@link org.mule.model.streaming.CallbackOutputStream}.
*
* @param endpoint the endpoint that releates to this Dispatcher
* @param message the current message being processed
* @return the output stream to use for this request
* @throws MuleException in case of any error
*/
public OutputStream getOutputStream(OutboundEndpoint endpoint, MuleMessage message)
throws MuleException
{
throw new UnsupportedOperationException(
CoreMessages.streamingNotSupported(this.getProtocol()).toString());
}
public MuleContext getMuleContext()
{
return muleContext;
}
public void setMuleContext(MuleContext context)
{
this.muleContext = context;
updateCachedNotificationHandler();
}
// @Override
public String toString()
{
final StringBuffer sb = new StringBuffer(120);
sb.append(ClassUtils.getSimpleName(this.getClass()));
sb.append("{this=").append(Integer.toHexString(System.identityHashCode(this)));
sb.append(", started=").append(started);
sb.append(", initialised=").append(initialised);
sb.append(", name='").append(name).append('\'');
sb.append(", disposed=").append(disposed);
sb.append(", numberOfConcurrentTransactedReceivers=").append(numberOfConcurrentTransactedReceivers);
sb.append(", createMultipleTransactedReceivers=").append(createMultipleTransactedReceivers);
sb.append(", connected=").append(connected);
sb.append(", supportedProtocols=").append(supportedProtocols);
sb.append(", serviceOverrides=").append(serviceOverrides);
sb.append('}');
return sb.toString();
}
}
|