mina-1.1.7.dfsg/0000755000175000017500000000000011044712500013254 5ustar drazzibdrazzibmina-1.1.7.dfsg/docs/0000755000175000017500000000000011044712500014204 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/0000755000175000017500000000000011044712500015340 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/pom.xml0000644000175000017500000000164211002320016016647 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-filter-ssl Apache MINA SSL Filter jar org.apache.mina mina-core ${pom.version} compile org.slf4j slf4j-simple 1.4.3 test mina-1.1.7.dfsg/filter-ssl/src/0000755000175000017500000000000011002320014016114 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/0000755000175000017500000000000011002320015017041 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/resources/0000755000175000017500000000000011002320015021053 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/resources/META-INF/0000755000175000017500000000000011044712500022225 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320016025151 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/filter-ssl/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320016024050 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/filter-ssl/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320016025071 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/filter-ssl/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320016023742 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/filter-ssl/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320016027267 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/filter-ssl/src/main/java/0000755000175000017500000000000011002320014017761 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/java/org/0000755000175000017500000000000011002320014020550 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/0000755000175000017500000000000011002320014021771 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/0000755000175000017500000000000011002320014022715 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/filter/0000755000175000017500000000000011044712500024215 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/filter/SSLFilter.java0000644000175000017500000005651411002320015026670 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ByteBufferProxy; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoFuture; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.support.DefaultWriteFuture; import org.apache.mina.filter.support.SSLHandler; import org.apache.mina.util.SessionLog; /** * An SSL filter that encrypts and decrypts the data exchanged in the session. * Adding this filter triggers SSL handshake procedure immediately by sending * a SSL 'hello' message, so you don't need to call * {@link #startSSL(IoSession)} manually unless you are implementing StartTLS * (see below). *

* This filter uses an {@link SSLEngine} which was introduced in Java 5, so * Java version 5 or above is mandatory to use this filter. And please note that * this filter only works for TCP/IP connections. *

* This filter logs debug information using {@link SessionLog}. * *

Implementing StartTLS

*

* You can use {@link #DISABLE_ENCRYPTION_ONCE} attribute to implement StartTLS: *

 * public void messageReceived(IoSession session, Object message) {
 *    if (message instanceof MyStartTLSRequest) {
 *        // Insert SSLFilter to get ready for handshaking
 *        session.getFilterChain().addFirst(sslFilter);
 *
 *        // Disable encryption temporarilly.
 *        // This attribute will be removed by SSLFilter
 *        // inside the Session.write() call below.
 *        session.setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);
 *
 *        // Write StartTLSResponse which won't be encrypted.
 *        session.write(new MyStartTLSResponse(OK));
 *        
 *        // Now DISABLE_ENCRYPTION_ONCE attribute is cleared.
 *        assert session.getAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE) == null;
 *    }
 * }
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class SSLFilter extends IoFilterAdapter { /** * A session attribute key that stores underlying {@link SSLSession} * for each session. */ public static final String SSL_SESSION = SSLFilter.class.getName() + ".SSLSession"; /** * A session attribute key that makes next one write request bypass * this filter (not encrypting the data). This is a marker attribute, * which means that you can put whatever as its value. ({@link Boolean#TRUE} * is preferred.) The attribute is automatically removed from the session * attribute map as soon as {@link IoSession#write(Object)} is invoked, * and therefore should be put again if you want to make more messages * bypass this filter. This is especially useful when you implement * StartTLS. */ public static final String DISABLE_ENCRYPTION_ONCE = SSLFilter.class .getName() + ".DisableEncryptionOnce"; /** * A session attribute key that makes this filter to emit a * {@link IoHandler#messageReceived(IoSession, Object)} event with a * special message ({@link #SESSION_SECURED} or {@link #SESSION_UNSECURED}). * This is a marker attribute, which means that you can put whatever as its * value. ({@link Boolean#TRUE} is preferred.) By default, this filter * doesn't emit any events related with SSL session flow control. */ public static final String USE_NOTIFICATION = SSLFilter.class.getName() + ".UseNotification"; /** * A special message object which is emitted with a {@link IoHandler#messageReceived(IoSession, Object)} * event when the session is secured and its {@link #USE_NOTIFICATION} * attribute is set. */ public static final SSLFilterMessage SESSION_SECURED = new SSLFilterMessage( "SESSION_SECURED"); /** * A special message object which is emitted with a {@link IoHandler#messageReceived(IoSession, Object)} * event when the session is not secure anymore and its {@link #USE_NOTIFICATION} * attribute is set. */ public static final SSLFilterMessage SESSION_UNSECURED = new SSLFilterMessage( "SESSION_UNSECURED"); private static final String NEXT_FILTER = SSLFilter.class.getName() + ".NextFilter"; private static final String SSL_HANDLER = SSLFilter.class.getName() + ".SSLHandler"; // SSL Context private SSLContext sslContext; private boolean client; private boolean needClientAuth; private boolean wantClientAuth; private String[] enabledCipherSuites; private String[] enabledProtocols; /** * Creates a new SSL filter using the specified {@link SSLContext}. */ public SSLFilter(SSLContext sslContext) { if (sslContext == null) { throw new NullPointerException("sslContext"); } this.sslContext = sslContext; } /** * Returns the underlying {@link SSLSession} for the specified session. * * @return null if no {@link SSLSession} is initialized yet. */ public SSLSession getSSLSession(IoSession session) { return (SSLSession) session.getAttribute(SSL_SESSION); } /** * (Re)starts SSL session for the specified session if not started yet. * Please note that SSL session is automatically started by default, and therefore * you don't need to call this method unless you've used TLS closure. * * @return true if the SSL session has been started, false if already started. * @throws SSLException if failed to start the SSL session */ public boolean startSSL(IoSession session) throws SSLException { SSLHandler handler = getSSLSessionHandler(session); boolean started; synchronized (handler) { if (handler.isOutboundDone()) { NextFilter nextFilter = (NextFilter) session .getAttribute(NEXT_FILTER); handler.destroy(); handler.init(); handler.handshake(nextFilter); started = true; } else { started = false; } } handler.flushScheduledEvents(); return started; } /** * Returns true if and only if the specified session is * encrypted/decrypted over SSL/TLS currently. This method will start * to retun false after TLS close_notify message * is sent and any messages written after then is not goinf to get encrypted. */ public boolean isSSLStarted(IoSession session) { SSLHandler handler = getSSLSessionHandler0(session); if (handler == null) { return false; } synchronized (handler) { return !handler.isOutboundDone(); } } /** * Stops the SSL session by sending TLS close_notify message to * initiate TLS closure. * * @param session the {@link IoSession} to initiate TLS closure * @throws SSLException if failed to initiate TLS closure * @throws IllegalArgumentException if this filter is not managing the specified session */ public WriteFuture stopSSL(IoSession session) throws SSLException { SSLHandler handler = getSSLSessionHandler(session); NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER); WriteFuture future; synchronized (handler) { future = initiateClosure(nextFilter, session); } handler.flushScheduledEvents(); return future; } /** * Returns true if the engine is set to use client mode * when handshaking. */ public boolean isUseClientMode() { return client; } /** * Configures the engine to use client (or server) mode when handshaking. */ public void setUseClientMode(boolean clientMode) { this.client = clientMode; } /** * Returns true if the engine will require client authentication. * This option is only useful to engines in the server mode. */ public boolean isNeedClientAuth() { return needClientAuth; } /** * Configures the engine to require client authentication. * This option is only useful for engines in the server mode. */ public void setNeedClientAuth(boolean needClientAuth) { this.needClientAuth = needClientAuth; } /** * Returns true if the engine will request client authentication. * This option is only useful to engines in the server mode. */ public boolean isWantClientAuth() { return wantClientAuth; } /** * Configures the engine to request client authentication. * This option is only useful for engines in the server mode. */ public void setWantClientAuth(boolean wantClientAuth) { this.wantClientAuth = wantClientAuth; } /** * Returns the list of cipher suites to be enabled when {@link SSLEngine} * is initialized. * * @return null means 'use {@link SSLEngine}'s default.' */ public String[] getEnabledCipherSuites() { return enabledCipherSuites; } /** * Sets the list of cipher suites to be enabled when {@link SSLEngine} * is initialized. * * @param cipherSuites null means 'use {@link SSLEngine}'s default.' */ public void setEnabledCipherSuites(String[] cipherSuites) { this.enabledCipherSuites = cipherSuites; } /** * Returns the list of protocols to be enabled when {@link SSLEngine} * is initialized. * * @return null means 'use {@link SSLEngine}'s default.' */ public String[] getEnabledProtocols() { return enabledProtocols; } /** * Sets the list of protocols to be enabled when {@link SSLEngine} * is initialized. * * @param protocols null means 'use {@link SSLEngine}'s default.' */ public void setEnabledProtocols(String[] protocols) { this.enabledProtocols = protocols; } public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { if (parent.contains(SSLFilter.class)) { throw new IllegalStateException( "A filter chain cannot contain more than one SSLFilter."); } IoSession session = parent.getSession(); session.setAttribute(NEXT_FILTER, nextFilter); // Create an SSL handler and start handshake. SSLHandler handler = new SSLHandler(this, sslContext, session); session.setAttribute(SSL_HANDLER, handler); } public void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { SSLHandler handler = getSSLSessionHandler(parent.getSession()); synchronized (handler) { handler.handshake(nextFilter); } handler.flushScheduledEvents(); } public void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { IoSession session = parent.getSession(); stopSSL(session); session.removeAttribute(NEXT_FILTER); session.removeAttribute(SSL_HANDLER); } // IoFilter impl. public void sessionClosed(NextFilter nextFilter, IoSession session) throws SSLException { SSLHandler handler = getSSLSessionHandler(session); try { synchronized (handler) { if (isSSLStarted(session)) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Closed: " + getSSLSessionHandler(session)); } } // release resources handler.destroy(); } handler.flushScheduledEvents(); } finally { // notify closed session nextFilter.sessionClosed(session); } } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws SSLException { SSLHandler handler = getSSLSessionHandler(session); synchronized (handler) { if (!isSSLStarted(session) && handler.isInboundDone()) { handler.scheduleMessageReceived(nextFilter, message); } else { ByteBuffer buf = (ByteBuffer) message; if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Data Read: " + handler + " (" + buf + ')'); } try { // forward read encrypted data to SSL handler handler.messageReceived(nextFilter, buf.buf()); // Handle data to be forwarded to application or written to net handleSSLData(nextFilter, handler); if (handler.isInboundDone()) { if (handler.isOutboundDone()) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " SSL Session closed."); } handler.destroy(); } else { initiateClosure(nextFilter, session); } if (buf.hasRemaining()) { // Forward the data received after closure. handler.scheduleMessageReceived(nextFilter, buf); } } } catch (SSLException ssle) { if (!handler.isHandshakeComplete()) { SSLException newSSLE = new SSLHandshakeException( "SSL handshake failed."); newSSLE.initCause(ssle); ssle = newSSLE; } throw ssle; } } } handler.flushScheduledEvents(); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) { if (message instanceof EncryptedBuffer) { EncryptedBuffer buf = (EncryptedBuffer) message; buf.release(); nextFilter.messageSent(session, buf.originalBuffer); } else { // ignore extra buffers used for handshaking } } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws SSLException { boolean needsFlush = true; SSLHandler handler = getSSLSessionHandler(session); synchronized (handler) { if (!isSSLStarted(session)) { handler.scheduleFilterWrite(nextFilter, writeRequest); } // Don't encrypt the data if encryption is disabled. else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) { // Remove the marker attribute because it is temporary. session.removeAttribute(DISABLE_ENCRYPTION_ONCE); handler.scheduleFilterWrite(nextFilter, writeRequest); } else { // Otherwise, encrypt the buffer. ByteBuffer buf = (ByteBuffer) writeRequest.getMessage(); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Filtered Write: " + handler); } if (handler.isWritingEncryptedData()) { // data already encrypted; simply return buffer if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " already encrypted: " + buf); } handler.scheduleFilterWrite(nextFilter, writeRequest); } else if (handler.isHandshakeComplete()) { // SSL encrypt if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " encrypt: " + buf); } int pos = buf.position(); handler.encrypt(buf.buf()); buf.position(pos); ByteBuffer encryptedBuffer = new EncryptedBuffer(SSLHandler .copy(handler.getOutNetBuffer()), buf); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " encrypted buf: " + encryptedBuffer); } handler.scheduleFilterWrite(nextFilter, new WriteRequest(encryptedBuffer, writeRequest .getFuture())); } else { if (!session.isConnected()) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Write request on closed session."); } } else { if (SessionLog.isDebugEnabled(session)) { SessionLog .debug(session, " Handshaking is not complete yet. Buffering write request."); } handler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest); } needsFlush = false; } } } if (needsFlush) { handler.flushScheduledEvents(); } } public void filterClose(final NextFilter nextFilter, final IoSession session) throws SSLException { SSLHandler handler = getSSLSessionHandler0(session); if (handler == null) { // The connection might already have closed, or // SSL might have not started yet. nextFilter.filterClose(session); return; } WriteFuture future = null; try { synchronized (handler) { if (isSSLStarted(session)) { future = initiateClosure(nextFilter, session); future.addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { nextFilter.filterClose(session); } }); } } handler.flushScheduledEvents(); } finally { if (future == null) { nextFilter.filterClose(session); } } } private WriteFuture initiateClosure(NextFilter nextFilter, IoSession session) throws SSLException { SSLHandler handler = getSSLSessionHandler(session); // if already shut down if (!handler.closeOutbound()) { return DefaultWriteFuture.newNotWrittenFuture(session); } // there might be data to write out here? WriteFuture future = handler.writeNetBuffer(nextFilter); if (handler.isInboundDone()) { handler.destroy(); } if (session.containsAttribute(USE_NOTIFICATION)) { handler.scheduleMessageReceived(nextFilter, SESSION_UNSECURED); } return future; } // Utiliities private void handleSSLData(NextFilter nextFilter, SSLHandler handler) throws SSLException { // Flush any buffered write requests occurred before handshaking. if (handler.isHandshakeComplete()) { handler.flushPreHandshakeEvents(); } // Write encrypted data to be written (if any) handler.writeNetBuffer(nextFilter); // handle app. data read (if any) handleAppDataRead(nextFilter, handler); } private void handleAppDataRead(NextFilter nextFilter, SSLHandler handler) { IoSession session = handler.getSession(); handler.getAppBuffer().flip(); if (!handler.getAppBuffer().hasRemaining()) { handler.getAppBuffer().clear(); return; } if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " appBuffer: " + handler.getAppBuffer()); } // forward read app data ByteBuffer readBuffer = SSLHandler.copy(handler.getAppBuffer()); handler.getAppBuffer().clear(); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " app data read: " + readBuffer + " (" + readBuffer.getHexDump() + ')'); } handler.scheduleMessageReceived(nextFilter, readBuffer); } private SSLHandler getSSLSessionHandler(IoSession session) { SSLHandler handler = getSSLSessionHandler0(session); if (handler == null) { throw new IllegalStateException(); } if (handler.getParent() != this) { throw new IllegalArgumentException("Not managed by this filter."); } return handler; } private SSLHandler getSSLSessionHandler0(IoSession session) { return (SSLHandler) session.getAttribute(SSL_HANDLER); } /** * A message that is sent from {@link SSLFilter} when the connection became * secure or is not secure anymore. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public static class SSLFilterMessage { private final String name; private SSLFilterMessage(String name) { this.name = name; } public String toString() { return name; } } private static class EncryptedBuffer extends ByteBufferProxy { private final ByteBuffer originalBuffer; private EncryptedBuffer(ByteBuffer buf, ByteBuffer originalBuffer) { super(buf); this.originalBuffer = originalBuffer; } } } mina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/filter/support/0000755000175000017500000000000011044712500025731 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/filter/support/SSLByteBufferPool.java0000644000175000017500000001333611002320015032041 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.support; import java.nio.ByteBuffer; import javax.net.ssl.SSLEngine; import org.apache.mina.util.Stack; /** * Simple ByteBuffer pool used by SSLHandler. * ByteBuffers are by default allocated as direct byte buffers. To use non-direct * ByteBuffers, set system property mina.sslfilter.directbuffer to false. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ class SSLByteBufferPool { private static final int PACKET_BUFFER_INDEX = 0; private static final int APPLICATION_BUFFER_INDEX = 1; private static boolean initiated = false; private static final String DIRECT_MEMORY_PROP = "mina.sslfilter.directbuffer"; private static boolean useDirectAllocatedBuffers = true; private static int packetBufferSize; private static int appBufferSize; private static int[] bufferStackSizes; private static final Stack[] bufferStacks = new Stack[] { new Stack(), new Stack(), }; /** * Initiate buffer pool and buffer sizes from SSLEngine session. * * @param sslEngine SSLEngine */ static synchronized void initiate(SSLEngine sslEngine) { if (!initiated) { // Use direct allocated memory or not? String prop = System.getProperty(DIRECT_MEMORY_PROP); if (prop != null) { useDirectAllocatedBuffers = Boolean .getBoolean(DIRECT_MEMORY_PROP); } // init buffer sizes from SSLEngine packetBufferSize = sslEngine.getSession().getPacketBufferSize(); // application buffer size has been doubled because SSLEngine // returns BUFFER_OVERFLOW even if there is enough room for the buffer. // So for now we use a size double the packet size as a workaround. appBufferSize = packetBufferSize * 2; initiateBufferStacks(); initiated = true; } } /** * Get bytebuffer with size the size of the largest SSL/TLS packet that may occur * (as defined by SSLSession). */ static ByteBuffer getPacketBuffer() { if (!initiated) { throw new IllegalStateException("Not initialized"); } return allocate(PACKET_BUFFER_INDEX); } /** * Get ByteBuffer with the size of the largest application buffer that may occur * (as defined by SSLSession). */ static ByteBuffer getApplicationBuffer() { if (!initiated) { throw new IllegalStateException("Not initialized"); } return allocate(APPLICATION_BUFFER_INDEX); } /** * Allocate or get the buffer which is capable of the specified size. */ private static ByteBuffer allocate(int idx) { Stack stack = bufferStacks[idx]; ByteBuffer buf; synchronized (stack) { buf = (ByteBuffer) stack.pop(); if (buf == null) { buf = createBuffer(bufferStackSizes[idx]); } } buf.clear(); return buf; } /** * Releases the specified buffer to buffer pool. */ public static void release(ByteBuffer buf) { // Sweep buffer for security. org.apache.mina.common.ByteBuffer.wrap(buf).sweep().release(); int stackIndex = getBufferStackIndex(buf.capacity()); if (stackIndex >= PACKET_BUFFER_INDEX) { Stack stack = bufferStacks[getBufferStackIndex(buf.capacity())]; synchronized (stack) { stack.push(buf); } } } /** * Expand size of provided buffer * @param buf buffer to be expande * @param newCapacity new capacity */ public static ByteBuffer expandBuffer(ByteBuffer buf, int newCapacity) { ByteBuffer newBuf = createBuffer(newCapacity); buf.flip(); newBuf.put(buf); release(buf); return newBuf; } private static void initiateBufferStacks() { bufferStackSizes = new int[2]; bufferStackSizes[PACKET_BUFFER_INDEX] = packetBufferSize; bufferStackSizes[APPLICATION_BUFFER_INDEX] = appBufferSize; } private static int getBufferStackIndex(int size) { if (size == packetBufferSize) return PACKET_BUFFER_INDEX; if (size == appBufferSize) return APPLICATION_BUFFER_INDEX; return -1; // not reused } private static ByteBuffer createBuffer(int capacity) { if (useDirectAllocatedBuffers) { try { return ByteBuffer.allocateDirect(capacity); } catch (OutOfMemoryError e) { useDirectAllocatedBuffers = false; System.err .println("OutOfMemoryError: No more direct buffers available; trying heap buffer instead"); } } return ByteBuffer.allocate(capacity); } } mina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/filter/support/package.html0000644000175000017500000000025711002320015030204 0ustar drazzibdrazzib Internal classes used by org.apache.mina.filter package. mina-1.1.7.dfsg/filter-ssl/src/main/java/org/apache/mina/filter/support/SSLHandler.java0000644000175000017500000006225711002320015030535 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.support; import java.nio.ByteBuffer; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.DefaultWriteFuture; import org.apache.mina.filter.SSLFilter; import org.apache.mina.util.SessionLog; /** * A helper class using the SSLEngine API to decrypt/encrypt data. *

* Each connection has a SSLEngine that is used through the lifetime of the connection. * We allocate byte buffers for use as the outbound and inbound network buffers. * These buffers handle all of the intermediary data for the SSL connection. To make things easy, * we'll require outNetBuffer be completely flushed before trying to wrap any more data. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 561232 $, $Date: 2007-07-31 14:19:37 +0900 (Tue, 31 Jul 2007) $ */ public class SSLHandler { private final SSLFilter parent; private final SSLContext ctx; private final IoSession session; private final Queue preHandshakeEventQueue = new LinkedList(); private final Queue filterWriteEventQueue = new ConcurrentLinkedQueue(); private final Queue messageReceivedEventQueue = new ConcurrentLinkedQueue(); private SSLEngine sslEngine; /** * Encrypted data from the net */ private ByteBuffer inNetBuffer; /** * Encrypted data to be written to the net */ private ByteBuffer outNetBuffer; /** * Applicaton cleartext data to be read by application */ private ByteBuffer appBuffer; /** * Empty buffer used during initial handshake and close operations */ private final ByteBuffer hsBB = ByteBuffer.allocate(0); /** * Handshake status */ private SSLEngineResult.HandshakeStatus handshakeStatus; private boolean initialHandshakeComplete; /** * Handshake complete? */ private boolean handshakeComplete; private boolean writingEncryptedData; /** * Constuctor. * * @param sslc * @throws SSLException */ public SSLHandler(SSLFilter parent, SSLContext sslc, IoSession session) throws SSLException { this.parent = parent; this.session = session; this.ctx = sslc; init(); } public void init() throws SSLException { if (sslEngine != null) { return; } sslEngine = ctx.createSSLEngine(); sslEngine.setUseClientMode(parent.isUseClientMode()); if (parent.isWantClientAuth()) { sslEngine.setWantClientAuth(true); } if (parent.isNeedClientAuth()) { sslEngine.setNeedClientAuth(true); } if (parent.getEnabledCipherSuites() != null) { sslEngine.setEnabledCipherSuites(parent.getEnabledCipherSuites()); } if (parent.getEnabledProtocols() != null) { sslEngine.setEnabledProtocols(parent.getEnabledProtocols()); } sslEngine.beginHandshake(); handshakeStatus = sslEngine.getHandshakeStatus();//SSLEngineResult.HandshakeStatus.NEED_UNWRAP; handshakeComplete = false; initialHandshakeComplete = false; SSLByteBufferPool.initiate(sslEngine); appBuffer = SSLByteBufferPool.getApplicationBuffer(); inNetBuffer = SSLByteBufferPool.getPacketBuffer(); outNetBuffer = SSLByteBufferPool.getPacketBuffer(); outNetBuffer.position(0); outNetBuffer.limit(0); writingEncryptedData = false; } /** * Release allocated ByteBuffers. */ public void destroy() { if (sslEngine == null) { return; } // Close inbound and flush all remaining data if available. try { sslEngine.closeInbound(); } catch (SSLException e) { SessionLog.debug(session, "Unexpected exception from SSLEngine.closeInbound().", e); } try { do { outNetBuffer.clear(); } while (sslEngine.wrap(hsBB, outNetBuffer).bytesProduced() > 0); } catch (SSLException e) { SessionLog.debug(session, "Unexpected exception from SSLEngine.wrap().", e); } sslEngine.closeOutbound(); sslEngine = null; SSLByteBufferPool.release(appBuffer); SSLByteBufferPool.release(inNetBuffer); SSLByteBufferPool.release(outNetBuffer); preHandshakeEventQueue.clear(); } public SSLFilter getParent() { return parent; } public IoSession getSession() { return session; } /** * Check we are writing encrypted data. */ public boolean isWritingEncryptedData() { return writingEncryptedData; } /** * Check if handshake is completed. */ public boolean isHandshakeComplete() { return handshakeComplete; } public boolean isInboundDone() { return sslEngine == null || sslEngine.isInboundDone(); } public boolean isOutboundDone() { return sslEngine == null || sslEngine.isOutboundDone(); } /** * Check if there is any need to complete handshake. */ public boolean needToCompleteHandshake() { return (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP && !isInboundDone()); } public void schedulePreHandshakeWriteRequest(NextFilter nextFilter, WriteRequest writeRequest) { preHandshakeEventQueue.offer(new Event(EventType.FILTER_WRITE, nextFilter, writeRequest)); } public void flushPreHandshakeEvents() throws SSLException { Event scheduledWrite; while ((scheduledWrite = preHandshakeEventQueue.poll()) != null) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Flushing buffered write request: " + scheduledWrite.data); } parent.filterWrite(scheduledWrite.nextFilter, session, (WriteRequest) scheduledWrite.data); } } public void scheduleFilterWrite(NextFilter nextFilter, WriteRequest writeRequest) { filterWriteEventQueue.offer(new Event(EventType.FILTER_WRITE, nextFilter, writeRequest)); } public void scheduleMessageReceived(NextFilter nextFilter, Object message) { messageReceivedEventQueue.offer(new Event(EventType.RECEIVED, nextFilter, message)); } public void flushScheduledEvents() { // Fire events only when no lock is hold for this handler. if (Thread.holdsLock(this)) { return; } Event e; // We need synchronization here inevitably because filterWrite can be // called simultaneously and cause 'bad record MAC' integrity error. synchronized (this) { while ((e = filterWriteEventQueue.poll()) != null) { e.nextFilter.filterWrite(session, (WriteRequest) e.data); } } while ((e = messageReceivedEventQueue.poll()) != null) { e.nextFilter.messageReceived(session, e.data); } } /** * Call when data read from net. Will perform inial hanshake or decrypt provided * Buffer. * Decrytpted data reurned by getAppBuffer(), if any. * * @param buf buffer to decrypt * @throws SSLException on errors */ public void messageReceived(NextFilter nextFilter, ByteBuffer buf) throws SSLException { if (buf.limit() > inNetBuffer.remaining()) { // We have to expand inNetBuffer inNetBuffer = SSLByteBufferPool.expandBuffer(inNetBuffer, inNetBuffer.capacity() + (buf.limit() * 2)); // We also expand app. buffer (twice the size of in net. buffer) appBuffer = SSLByteBufferPool.expandBuffer(appBuffer, inNetBuffer .capacity() * 2); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " expanded inNetBuffer:" + inNetBuffer); SessionLog.debug(session, " expanded appBuffer:" + appBuffer); } } // append buf to inNetBuffer inNetBuffer.put(buf); if (!handshakeComplete) { handshake(nextFilter); } else { decrypt(nextFilter); } if (isInboundDone()) { // Rewind the MINA buffer if not all data is processed and inbound is finished. buf.position(buf.position() - inNetBuffer.position()); inNetBuffer.clear(); } } /** * Get decrypted application data. * * @return buffer with data */ public ByteBuffer getAppBuffer() { return appBuffer; } /** * Get encrypted data to be sent. * * @return buffer with data */ public ByteBuffer getOutNetBuffer() { return outNetBuffer; } /** * Encrypt provided buffer. Encytpted data reurned by getOutNetBuffer(). * * @param src data to encrypt * @throws SSLException on errors */ public void encrypt(ByteBuffer src) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } // The data buffer is (must be) empty, we can reuse the entire // buffer. outNetBuffer.clear(); // Loop until there is no more data in src while (src.hasRemaining()) { if (src.remaining() > ((outNetBuffer.capacity() - outNetBuffer .position()) / 2)) { // We have to expand outNetBuffer // Note: there is no way to know the exact size required, but enrypted data // shouln't need to be larger than twice the source data size? outNetBuffer = SSLByteBufferPool.expandBuffer(outNetBuffer, src .capacity() * 2); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " expanded outNetBuffer:" + outNetBuffer); } } SSLEngineResult result = sslEngine.wrap(src, outNetBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Wrap res:" + result); } if (result.getStatus() == SSLEngineResult.Status.OK) { if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { doTasks(); } } else { throw new SSLException("SSLEngine error during encrypt: " + result.getStatus() + " src: " + src + "outNetBuffer: " + outNetBuffer); } } outNetBuffer.flip(); } /** * Start SSL shutdown process. * * @return true if shutdown process is started. * false if shutdown process is already finished. * * @throws SSLException on errors */ public boolean closeOutbound() throws SSLException { if (sslEngine == null || sslEngine.isOutboundDone()) { return false; } sslEngine.closeOutbound(); // By RFC 2616, we can "fire and forget" our close_notify // message, so that's what we'll do here. outNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(hsBB, outNetBuffer); if (result.getStatus() != SSLEngineResult.Status.CLOSED) { throw new SSLException("Improper close state: " + result); } outNetBuffer.flip(); return true; } /** * Decrypt in net buffer. Result is stored in app buffer. * * @throws SSLException */ private void decrypt(NextFilter nextFilter) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } unwrap(nextFilter); } /** * @param status * @throws SSLException */ private void checkStatus(SSLEngineResult res) throws SSLException { SSLEngineResult.Status status = res.getStatus(); /* * The status may be: * OK - Normal operation * OVERFLOW - Should never happen since the application buffer is * sized to hold the maximum packet size. * UNDERFLOW - Need to read more data from the socket. It's normal. * CLOSED - The other peer closed the socket. Also normal. */ if (status != SSLEngineResult.Status.OK && status != SSLEngineResult.Status.CLOSED && status != SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new SSLException("SSLEngine error during decrypt: " + status + " inNetBuffer: " + inNetBuffer + "appBuffer: " + appBuffer); } } /** * Perform any handshaking processing. */ public void handshake(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doHandshake()"); } for (;;) { if (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED) { session.setAttribute(SSLFilter.SSL_SESSION, sslEngine .getSession()); if (SessionLog.isDebugEnabled(session)) { SSLSession sslSession = sslEngine.getSession(); SessionLog.debug(session, " handshakeStatus=FINISHED"); SessionLog.debug(session, " sslSession CipherSuite used " + sslSession.getCipherSuite()); } handshakeComplete = true; if (!initialHandshakeComplete && session.containsAttribute(SSLFilter.USE_NOTIFICATION)) { // SESSION_SECURED is fired only when it's the first handshake. // (i.e. renegotiation shouldn't trigger SESSION_SECURED.) initialHandshakeComplete = true; scheduleMessageReceived(nextFilter, SSLFilter.SESSION_SECURED); } break; } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_TASK"); } handshakeStatus = doTasks(); } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { // we need more data read if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_UNWRAP"); } SSLEngineResult.Status status = unwrapHandshake(nextFilter); if (status == SSLEngineResult.Status.BUFFER_UNDERFLOW || isInboundDone()) { // We need more data or the session is closed break; } } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_WRAP"); } // First make sure that the out buffer is completely empty. Since we // cannot call wrap with data left on the buffer if (outNetBuffer.hasRemaining()) { if (SessionLog.isDebugEnabled(session)) { SessionLog .debug(session, " Still data in out buffer!"); } break; } outNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(hsBB, outNetBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Wrap res:" + result); } outNetBuffer.flip(); handshakeStatus = result.getHandshakeStatus(); writeNetBuffer(nextFilter); } else { throw new IllegalStateException("Invalid Handshaking State" + handshakeStatus); } } } public WriteFuture writeNetBuffer(NextFilter nextFilter) throws SSLException { // Check if any net data needed to be writen if (!getOutNetBuffer().hasRemaining()) { // no; bail out return DefaultWriteFuture.newNotWrittenFuture(session); } // set flag that we are writing encrypted data // (used in SSLFilter.filterWrite()) writingEncryptedData = true; // write net data WriteFuture writeFuture = null; try { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " write outNetBuffer: " + getOutNetBuffer()); } org.apache.mina.common.ByteBuffer writeBuffer = copy(getOutNetBuffer()); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " session write: " + writeBuffer); } //debug("outNetBuffer (after copy): {0}", sslHandler.getOutNetBuffer()); writeFuture = new DefaultWriteFuture(session); parent.filterWrite(nextFilter, session, new WriteRequest( writeBuffer, writeFuture)); // loop while more writes required to complete handshake while (needToCompleteHandshake()) { try { handshake(nextFilter); } catch (SSLException ssle) { SSLException newSSLE = new SSLHandshakeException( "SSL handshake failed."); newSSLE.initCause(ssle); throw newSSLE; } if (getOutNetBuffer().hasRemaining()) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " write outNetBuffer2: " + getOutNetBuffer()); } org.apache.mina.common.ByteBuffer writeBuffer2 = copy(getOutNetBuffer()); writeFuture = new DefaultWriteFuture(session); parent.filterWrite(nextFilter, session, new WriteRequest( writeBuffer2, writeFuture)); } } } finally { writingEncryptedData = false; } return writeFuture; } private void unwrap(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " unwrap()"); } // Prepare the net data for reading. inNetBuffer.flip(); SSLEngineResult res = unwrap0(); // prepare to be written again inNetBuffer.compact(); checkStatus(res); renegotiateIfNeeded(nextFilter, res); } private SSLEngineResult.Status unwrapHandshake(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " unwrapHandshake()"); } // Prepare the net data for reading. inNetBuffer.flip(); SSLEngineResult res = unwrap0(); handshakeStatus = res.getHandshakeStatus(); checkStatus(res); // If handshake finished, no data was produced, and the status is still ok, // try to unwrap more if (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED && res.getStatus() == SSLEngineResult.Status.OK && inNetBuffer.hasRemaining()) { res = unwrap0(); // prepare to be written again inNetBuffer.compact(); renegotiateIfNeeded(nextFilter, res); } else { // prepare to be written again inNetBuffer.compact(); } return res.getStatus(); } private void renegotiateIfNeeded(NextFilter nextFilter, SSLEngineResult res) throws SSLException { if (res.getStatus() != SSLEngineResult.Status.CLOSED && res.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW && res.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // Renegotiation required. SessionLog.debug(session, " Renegotiating..."); handshakeComplete = false; handshakeStatus = res.getHandshakeStatus(); handshake(nextFilter); } } private SSLEngineResult unwrap0() throws SSLException { SSLEngineResult res; do { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " inNetBuffer: " + inNetBuffer); SessionLog.debug(session, " appBuffer: " + appBuffer); } res = sslEngine.unwrap(inNetBuffer, appBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Unwrap res:" + res); } } while (res.getStatus() == SSLEngineResult.Status.OK && (handshakeComplete && res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING || res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP)); return res; } /** * Do all the outstanding handshake tasks in the current Thread. */ private SSLEngineResult.HandshakeStatus doTasks() { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTasks()"); } /* * We could run this in a separate thread, but I don't see the need * for this when used from SSLFilter. Use thread filters in MINA instead? */ Runnable runnable; while ((runnable = sslEngine.getDelegatedTask()) != null) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTask: " + runnable); } runnable.run(); } if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTasks(): " + sslEngine.getHandshakeStatus()); } return sslEngine.getHandshakeStatus(); } /** * Creates a new Mina byte buffer that is a deep copy of the remaining bytes * in the given buffer (between index buf.position() and buf.limit()) * * @param src the buffer to copy * @return the new buffer, ready to read from */ public static org.apache.mina.common.ByteBuffer copy(java.nio.ByteBuffer src) { org.apache.mina.common.ByteBuffer copy = org.apache.mina.common.ByteBuffer .allocate(src.remaining()); copy.put(src); copy.flip(); return copy; } private static class EventType { public static final EventType RECEIVED = new EventType("RECEIVED"); public static final EventType FILTER_WRITE = new EventType( "FILTER_WRITE"); private final String value; private EventType(String value) { this.value = value; } public String toString() { return value; } } private static class Event { private final EventType type; private final NextFilter nextFilter; private final Object data; Event(EventType type, NextFilter nextFilter, Object data) { this.type = type; this.nextFilter = nextFilter; this.data = data; } public Object getData() { return data; } public NextFilter getNextFilter() { return nextFilter; } public EventType getType() { return type; } } } mina-1.1.7.dfsg/filter-ssl/src/test/0000755000175000017500000000000011002320014017073 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-ssl/src/test/java/0000755000175000017500000000000011002320014020014 5ustar drazzibdrazzibmina-1.1.7.dfsg/pom.xml0000644000175000017500000001333711002320032014565 0ustar drazzibdrazzib 4.0.0 org.apache apache 3 Apache MINA Project http://mina.apache.org/ org.apache.mina 1.1.7 build Apache MINA Root Build POM pom http://mina.apache.org/ 2004 jira http://issues.apache.org/jira/browse/DIRMINA scm:svn:http://svn.apache.org/repos/asf/mina/tags/1.1.7 http://svn.apache.org/viewvc/mina/tags/1.1.7 scm:svn:https://svn.apache.org/repos/asf/mina/tags/1.1.7 apache.websites scp://people.apache.org/www/mina.apache.org/report/1.1/ mail

dev@mina.apache.org
MINA (Multipurpose Infrastructure for Network Applications) is a network application framework which helps users develop high performance and highly scalable network applications easily. Apache 2.0 License http://www.apache.org/licenses/LICENSE-2.0 repo junit junit 3.8.1 test core filter-ssl filter-codec-netty filter-compression integration-spring integration-jmx example org.apache.maven.plugins maven-compiler-plugin UTF-8 1.5 1.5 true true true maven-surefire-plugin **/Abstract* **/DatagramBindTest.java **/VmPipeTrafficControlTest.java **/*RegressionTest* org.apache.maven.plugins maven-source-plugin attach-sources jar maven-assembly-plugin release.xml mina-${pom.version} false gnu maven-release-plugin https://svn.apache.org/repos/asf/mina/tags org.apache.maven.plugins maven-javadoc-plugin false true true UTF-8 UTF-8 Apache MINA ${project.version} API Documentation Apache MINA ${project.version} API Documentation UTF-8 *.support:*.example.* http://java.sun.com/j2se/1.5.0/docs/api/ http://www.slf4j.org/api/ http://static.springframework.org/spring/docs/2.0.x/api/ en_US org.apache.maven.plugins maven-jxr-plugin false true UTF-8 UTF-8 Apache MINA ${project.version} Cross Reference Apache MINA ${project.version} Cross Reference mina-1.1.7.dfsg/core/0000755000175000017500000000000011044712500014204 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/pom.xml0000644000175000017500000000206611002320031015511 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-core Apache MINA Core API jar org.slf4j slf4j-api 1.4.3 compile org.slf4j slf4j-simple 1.4.3 test easymock easymock 1.2_Java1.3 test mina-1.1.7.dfsg/core/src/0000755000175000017500000000000011002320030014756 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/docs/0000755000175000017500000000000011044712500015723 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/0000755000175000017500000000000011002320030015702 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/resources/0000755000175000017500000000000011002320030017714 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/resources/META-INF/0000755000175000017500000000000011044712500021071 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320030024011 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/core/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320030022710 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/core/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320030023731 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/core/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320030022602 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/core/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320030026127 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/core/src/main/java/0000755000175000017500000000000011002320020016622 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/0000755000175000017500000000000011002320020017411 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/0000755000175000017500000000000011002320020020632 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/0000755000175000017500000000000011002320030021557 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/management/0000755000175000017500000000000011044712500023710 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/management/StatCollector.java0000644000175000017500000002623711002320023027334 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.management; import java.net.SocketAddress; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoServiceListener; import org.apache.mina.common.IoSession; /** * Collects statistics of an {@link IoService}. It's polling all the sessions of a given * IoService. It's attaching a {@link IoSessionStat} object to all the sessions polled * and filling the throughput values. * * Usage : *
 * IoService service = ...
 * StatCollector collector = new StatCollector( service );
 * collector.start();
 * 
* * By default the {@link StatCollector} is polling the sessions every 5 seconds. You can * give a different polling time using a second constructor. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class StatCollector { /** * The session attribute key for {@link IoSessionStat}. */ public static final String KEY = StatCollector.class.getName() + ".stat"; /** * @noinspection StaticNonFinalField */ private static volatile int nextId = 0; private final int id = nextId++; private final Object calcLock = new Object(); private final IoService service; private Worker worker; private int pollingInterval = 5000; private Queue polledSessions; // resume of session stats, for simplifying acces to the statistics private AtomicLong totalProcessedSessions = new AtomicLong(); private float msgWrittenThroughput = 0f; private float msgReadThroughput = 0f; private float bytesWrittenThroughput = 0f; private float bytesReadThroughput = 0f; private final IoServiceListener serviceListener = new IoServiceListener() { public void serviceActivated(IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config) { } public void serviceDeactivated(IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config) { } public void sessionCreated(IoSession session) { addSession(session); } public void sessionDestroyed(IoSession session) { removeSession(session); } }; /** * Create a stat collector for the given service with a default polling time of 5 seconds. * @param service the IoService to inspect */ public StatCollector(IoService service) { this(service, 5000); } /** * create a stat collector for the given given service * @param service the IoService to inspect * @param pollingInterval milliseconds */ public StatCollector(IoService service, int pollingInterval) { this.service = service; this.pollingInterval = pollingInterval; } /** * Start collecting stats for the {@link IoSession} of the service. * New sessions or destroyed will be automaticly added or removed. */ public void start() { synchronized (this) { if (worker != null && worker.isAlive()) throw new RuntimeException("Stat collecting already started"); // add all current sessions polledSessions = new ConcurrentLinkedQueue(); for (Iterator iter = service .getManagedServiceAddresses().iterator(); iter.hasNext();) { SocketAddress element = iter.next(); for (Iterator iter2 = service.getManagedSessions( element).iterator(); iter2.hasNext();) { addSession(iter2.next()); } } // listen for new ones service.addListener(serviceListener); // start polling worker = new Worker(); worker.start(); } } /** * Stop collecting stats. all the {@link IoSessionStat} object will be removed of the * polled session attachements. */ public void stop() { synchronized (this) { if (worker == null) { return; } service.removeListener(serviceListener); // stop worker worker.stop = true; worker.interrupt(); while (worker.isAlive()) { try { worker.join(); } catch (InterruptedException e) { //ignore since this is shutdown time } } for (Iterator iter = polledSessions.iterator(); iter.hasNext();) { IoSession session = (IoSession) iter.next(); session.removeAttribute(KEY); } polledSessions.clear(); worker = null; } } /** * is the stat collector started and polling the {@link IoSession} of the {@link IoService} * @return true if started */ public boolean isRunning() { synchronized (this) { return worker != null && worker.stop != true; } } private void addSession(IoSession session) { IoSessionStat sessionStats = new IoSessionStat(); session.setAttribute(KEY, sessionStats); totalProcessedSessions.incrementAndGet(); polledSessions.add(session); } private void removeSession(IoSession session) { // remove the session from the list of polled sessions polledSessions.remove(session); // add the bytes processed between last polling and session closing // prevent non seen byte with non-connected protocols like HTTP and datagrams IoSessionStat sessStat = (IoSessionStat) session.getAttribute(KEY); // computing with time between polling and closing long currentTime = System.currentTimeMillis(); synchronized (calcLock) { bytesReadThroughput += (session.getReadBytes() - sessStat.lastByteRead) / ((currentTime - sessStat.lastPollingTime) / 1000f); bytesWrittenThroughput += (session.getWrittenBytes() - sessStat.lastByteWrite) / ((currentTime - sessStat.lastPollingTime) / 1000f); msgReadThroughput += (session.getReadMessages() - sessStat.lastMessageRead) / ((currentTime - sessStat.lastPollingTime) / 1000f); msgWrittenThroughput += (session.getWrittenMessages() - sessStat.lastMessageWrite) / ((currentTime - sessStat.lastPollingTime) / 1000f); } session.removeAttribute(KEY); } /** * total number of sessions processed by the stat collector * @return number of sessions */ public long getTotalProcessedSessions() { return totalProcessedSessions.get(); } public float getBytesReadThroughput() { return bytesReadThroughput; } public float getBytesWrittenThroughput() { return bytesWrittenThroughput; } public float getMsgReadThroughput() { return msgReadThroughput; } public float getMsgWrittenThroughput() { return msgWrittenThroughput; } public long getSessionCount() { return polledSessions.size(); } private class Worker extends Thread { boolean stop = false; private Worker() { super("StatCollectorWorker-" + id); } public void run() { while (!stop) { for (Iterator iter = polledSessions.iterator(); iter.hasNext();) { IoSession session = (IoSession) iter.next(); IoSessionStat sessStat = (IoSessionStat) session .getAttribute(KEY); sessStat.lastByteRead = session.getReadBytes(); sessStat.lastByteWrite = session.getWrittenBytes(); sessStat.lastMessageRead = session.getReadMessages(); sessStat.lastMessageWrite = session.getWrittenMessages(); } // wait polling time try { Thread.sleep(pollingInterval); } catch (InterruptedException e) { } float tmpMsgWrittenThroughput = 0f; float tmpMsgReadThroughput = 0f; float tmpBytesWrittenThroughput = 0f; float tmpBytesReadThroughput = 0f; for (Iterator iter = polledSessions.iterator(); iter.hasNext();) { // upadating individual session statistics IoSession session = (IoSession) iter.next(); IoSessionStat sessStat = (IoSessionStat) session .getAttribute(KEY); sessStat.byteReadThroughput = (session.getReadBytes() - sessStat.lastByteRead) / (pollingInterval / 1000f); tmpBytesReadThroughput += sessStat.byteReadThroughput; sessStat.byteWrittenThroughput = (session.getWrittenBytes() - sessStat.lastByteWrite) / (pollingInterval / 1000f); tmpBytesWrittenThroughput += sessStat.byteWrittenThroughput; sessStat.messageReadThroughput = (session.getReadMessages() - sessStat.lastMessageRead) / (pollingInterval / 1000f); tmpMsgReadThroughput += sessStat.messageReadThroughput; sessStat.messageWrittenThroughput = (session .getWrittenMessages() - sessStat.lastMessageWrite) / (pollingInterval / 1000f); tmpMsgWrittenThroughput += sessStat.messageWrittenThroughput; synchronized (calcLock) { msgWrittenThroughput = tmpMsgWrittenThroughput; msgReadThroughput = tmpMsgReadThroughput; bytesWrittenThroughput = tmpBytesWrittenThroughput; bytesReadThroughput = tmpBytesReadThroughput; sessStat.lastPollingTime = System.currentTimeMillis(); } } } } } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/management/package.html0000644000175000017500000000024311002320023026155 0ustar drazzibdrazzib Utilities that manage and monitor a MINA application. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/management/IoSessionStat.java0000644000175000017500000000576211002320023027321 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.management; import org.apache.mina.common.IoSession; /** * The collected stats for a session. It's used by {@link StatCollector} to attach * throughput stats to an {@link IoSession}. You can accces a session stat using * {@link IoSession} getAttribute method : *
 * IoSession session = ...
 * IoSessionStat stat = session.getAttribute( StatCollector.KEY );
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoSessionStat { long lastByteRead = -1; long lastByteWrite = -1; long lastMessageRead = -1; long lastMessageWrite = -1; float byteWrittenThroughput = 0; float byteReadThroughput = 0; float messageWrittenThroughput = 0; float messageReadThroughput = 0; // last time the session was polled long lastPollingTime = System.currentTimeMillis(); /** * Bytes read per second * @return bytes per second */ public float getByteReadThroughput() { return byteReadThroughput; } /** * Bytes written per second * @return bytes per second */ public float getByteWrittenThroughput() { return byteWrittenThroughput; } /** * Messages read per second * @return messages per second */ public float getMessageReadThroughput() { return messageReadThroughput; } /** * Messages written per second * @return messages per second */ public float getMessageWrittenThroughput() { return messageWrittenThroughput; } /** * used for the StatCollector, last polling value */ long getLastByteRead() { return lastByteRead; } /** * used for the StatCollector, last polling value */ long getLastByteWrite() { return lastByteWrite; } /** * used for the StatCollector, last polling value */ long getLastMessageRead() { return lastMessageRead; } /** * used for the StatCollector, last polling value */ long getLastMessageWrite() { return lastMessageWrite; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/0000755000175000017500000000000011002320023023615 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/0000755000175000017500000000000011044712500025130 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAddress.java0000644000175000017500000000406411002320023030472 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe; import java.net.SocketAddress; /** * A {@link SocketAddress} which represents in-VM pipe port number. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class VmPipeAddress extends SocketAddress implements Comparable { private static final long serialVersionUID = 3257844376976830515L; private final int port; /** * Creates a new instance with the specifid port number. */ public VmPipeAddress(int port) { this.port = port; } /** * Returns the port number. */ public int getPort() { return port; } public int hashCode() { return port; } public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (o instanceof VmPipeAddress) { VmPipeAddress that = (VmPipeAddress) o; return this.port == that.port; } return false; } public int compareTo(VmPipeAddress o) { return this.port - o.port; } public String toString() { return "vm:" + port; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/package.html0000644000175000017500000000156111002320023027401 0ustar drazzibdrazzib In-VM pipe support which removes the overhead of local loopback communication.

What is 'in-VM pipe'?

In-VM pipe is a direct event forwarding mechanism between two ProtocolHandlers in the same Java Virtual Machine. Using in-VM pipe, you can remove the overhead of encoding and decoding which is caused uselessly by local loopback network communication. Here are some useful situations possible:

  • SMTP server and SPAM filtering server,
  • web server and Servlet/JSP container.

Please refer to Tennis example.

mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java0000644000175000017500000001003011002320023030633 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe; import java.io.IOException; import java.net.SocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.support.BaseIoAcceptor; import org.apache.mina.common.support.BaseIoAcceptorConfig; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.transport.vmpipe.support.VmPipe; /** * Binds the specified {@link IoHandler} to the specified * {@link VmPipeAddress}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class VmPipeAcceptor extends BaseIoAcceptor { static final Map boundHandlers = new HashMap(); private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() { }; private final IoServiceConfig defaultConfig = new BaseIoAcceptorConfig() { public IoSessionConfig getSessionConfig() { return CONFIG; } }; public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException { if (handler == null) throw new NullPointerException("handler"); if (address != null && !(address instanceof VmPipeAddress)) throw new IllegalArgumentException("address must be VmPipeAddress."); if (config == null) { config = getDefaultConfig(); } synchronized (boundHandlers) { if (address == null || ((VmPipeAddress) address).getPort() == 0) { for (int i = 1; i < Integer.MAX_VALUE; i++) { address = new VmPipeAddress(i); if (!boundHandlers.containsKey(address)) { break; } } } else if (boundHandlers.containsKey(address)) { throw new IOException("Address already bound: " + address); } boundHandlers.put(address, new VmPipe(this, (VmPipeAddress) address, handler, config, getListeners())); } getListeners().fireServiceActivated(this, address, handler, config); } public void unbind(SocketAddress address) { if (address == null) throw new NullPointerException("address"); VmPipe pipe; synchronized (boundHandlers) { if (!boundHandlers.containsKey(address)) { throw new IllegalArgumentException("Address not bound: " + address); } pipe = boundHandlers.remove(address); } getListeners().fireServiceDeactivated(this, pipe.getAddress(), pipe.getHandler(), pipe.getConfig()); } public void unbindAll() { synchronized (boundHandlers) { for (SocketAddress address : new ArrayList( boundHandlers.keySet())) { unbind(address); } } } public IoServiceConfig getDefaultConfig() { return defaultConfig; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/0000755000175000017500000000000011044712500026644 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java0000644000175000017500000000436111002320023030700 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe.support; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.support.IoServiceListenerSupport; import org.apache.mina.transport.vmpipe.VmPipeAcceptor; import org.apache.mina.transport.vmpipe.VmPipeAddress; /** * @todo Document me! * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 585081 $, $Date: 2007-10-16 17:45:14 +0900 (Tue, 16 Oct 2007) $ */ public class VmPipe { private final VmPipeAcceptor acceptor; private final VmPipeAddress address; private final IoHandler handler; private final IoServiceConfig config; private final IoServiceListenerSupport listeners; public VmPipe(VmPipeAcceptor acceptor, VmPipeAddress address, IoHandler handler, IoServiceConfig config, IoServiceListenerSupport listeners) { this.acceptor = acceptor; this.address = address; this.handler = handler; this.config = config; this.listeners = listeners; } public VmPipeAcceptor getAcceptor() { return acceptor; } public VmPipeAddress getAddress() { return address; } public IoHandler getHandler() { return handler; } public IoServiceConfig getConfig() { return config; } public IoServiceListenerSupport getListeners() { return listeners; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/package.html0000644000175000017500000000027111002320023031112 0ustar drazzibdrazzib Internal classes used by org.apache.mina.transport.vmpipe package. ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.0000644000175000017500000000765211002320023033333 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe.support; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.mina.common.IdleStatus; /** * Dectects idle sessions and fires sessionIdle events to them. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 585077 $, $Date: 2007-10-16 17:36:14 +0900 (Tue, 16 Oct 2007) $ */ public class VmPipeIdleStatusChecker { private static final VmPipeIdleStatusChecker INSTANCE = new VmPipeIdleStatusChecker(); public static VmPipeIdleStatusChecker getInstance() { return INSTANCE; } private final Set sessions = new HashSet(); private final Worker worker = new Worker(); private VmPipeIdleStatusChecker() { worker.start(); } public void addSession(VmPipeSessionImpl session) { synchronized (sessions) { sessions.add(session); } } private class Worker extends Thread { private Worker() { super("VmPipeIdleStatusChecker"); setDaemon(true); } public void run() { for (;;) { try { Thread.sleep(1000); } catch (InterruptedException e) { } long currentTime = System.currentTimeMillis(); synchronized (sessions) { Iterator it = sessions.iterator(); while (it.hasNext()) { VmPipeSessionImpl session = it.next(); if (!session.isConnected()) { it.remove(); } else { notifyIdleSession(session, currentTime); } } } } } } private void notifyIdleSession(VmPipeSessionImpl session, long currentTime) { notifyIdleSession0(session, currentTime, session .getIdleTimeInMillis(IdleStatus.BOTH_IDLE), IdleStatus.BOTH_IDLE, Math.max(session.getLastIoTime(), session .getLastIdleTime(IdleStatus.BOTH_IDLE))); notifyIdleSession0(session, currentTime, session .getIdleTimeInMillis(IdleStatus.READER_IDLE), IdleStatus.READER_IDLE, Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE))); notifyIdleSession0(session, currentTime, session .getIdleTimeInMillis(IdleStatus.WRITER_IDLE), IdleStatus.WRITER_IDLE, Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE))); } private void notifyIdleSession0(VmPipeSessionImpl session, long currentTime, long idleTime, IdleStatus status, long lastIoTime) { if (idleTime > 0 && lastIoTime != 0 && (currentTime - lastIoTime) >= idleTime) { session.increaseIdleCount(status); session.getFilterChain().fireSessionIdle(session, status); } } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeFilterChain.java0000644000175000017500000002151411002320023033010 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe.support; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.AbstractIoFilterChain; /** * @todo Document me! * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 635494 $, $Date: 2008-03-10 18:04:45 +0900 (Mon, 10 Mar 2008) $ */ public class VmPipeFilterChain extends AbstractIoFilterChain { private final Queue eventQueue = new ConcurrentLinkedQueue(); private volatile boolean flushEnabled; private volatile boolean sessionOpened; public VmPipeFilterChain(IoSession session) { super(session); } public void start() { flushEnabled = true; flushEvents(); flushPendingDataQueues( (VmPipeSessionImpl) getSession() ); } private void pushEvent(Event e) { eventQueue.offer(e); if ( flushEnabled ) { flushEvents(); } } private void flushEvents() { Event e; while ((e = eventQueue.poll()) != null) { fireEvent(e); } } private void fireEvent(Event e) { VmPipeSessionImpl session = (VmPipeSessionImpl) getSession(); EventType type = e.getType(); Object data = e.getData(); if (type == EventType.RECEIVED) { if( sessionOpened && session.getTrafficMask().isReadable() && session.getLock().tryLock()) { try { int byteCount = 1; if (data instanceof ByteBuffer) { byteCount = ((ByteBuffer) data).remaining(); } session.increaseReadBytes(byteCount); super.fireMessageReceived(session, data); } finally { session.getLock().unlock(); } flushPendingDataQueues( session ); } else { session.pendingDataQueue.add(data); } } else if (type == EventType.WRITE) { super.fireFilterWrite(session, (WriteRequest) data); } else if (type == EventType.SENT) { super.fireMessageSent(session, (WriteRequest) data); } else if (type == EventType.EXCEPTION) { super.fireExceptionCaught(session, (Throwable) data); } else if (type == EventType.IDLE) { super.fireSessionIdle(session, (IdleStatus) data); } else if (type == EventType.OPENED) { super.fireSessionOpened(session); sessionOpened = true; } else if (type == EventType.CREATED) { session.getLock().lock(); try { super.fireSessionCreated(session); } finally { session.getLock().unlock(); } } else if (type == EventType.CLOSED) { super.fireSessionClosed(session); } else if (type == EventType.CLOSE) { super.fireFilterClose(session); } } private static void flushPendingDataQueues( VmPipeSessionImpl s ) { s.updateTrafficMask(); s.getRemoteSession().updateTrafficMask(); } @Override public void fireFilterClose(IoSession session) { pushEvent(new Event(EventType.CLOSE, null)); } @Override public void fireFilterWrite(IoSession session, WriteRequest writeRequest) { pushEvent(new Event(EventType.WRITE, writeRequest)); } @Override public void fireExceptionCaught(IoSession session, Throwable cause) { pushEvent(new Event(EventType.EXCEPTION, cause)); } @Override public void fireMessageSent(IoSession session, WriteRequest request) { pushEvent(new Event(EventType.SENT, request)); } @Override public void fireSessionClosed(IoSession session) { pushEvent(new Event(EventType.CLOSED, null)); } @Override public void fireSessionCreated(IoSession session) { pushEvent(new Event(EventType.CREATED, null)); } @Override public void fireSessionIdle(IoSession session, IdleStatus status) { pushEvent(new Event(EventType.IDLE, status)); } @Override public void fireSessionOpened(IoSession session) { pushEvent(new Event(EventType.OPENED, null)); } @Override public void fireMessageReceived(IoSession session, Object message) { pushEvent(new Event(EventType.RECEIVED, message)); } @Override protected void doWrite(IoSession session, WriteRequest writeRequest) { VmPipeSessionImpl s = (VmPipeSessionImpl) session; if (s.isConnected()) { if ( s.getTrafficMask().isWritable() && s.getLock().tryLock()) { try { Object message = writeRequest.getMessage(); int byteCount = 1; Object messageCopy = message; if (message instanceof ByteBuffer) { ByteBuffer rb = (ByteBuffer) message; rb.mark(); byteCount = rb.remaining(); ByteBuffer wb = ByteBuffer.allocate(rb.remaining()); wb.put(rb); wb.flip(); rb.reset(); messageCopy = wb; } // Avoid unwanted side effect that scheduledWrite* becomes negative // by increasing them. s.increaseScheduledWriteBytes(byteCount); s.increaseScheduledWriteRequests(); s.increaseWrittenBytes(byteCount); s.increaseWrittenMessages(); s.getRemoteSession().getFilterChain().fireMessageReceived( s.getRemoteSession(), messageCopy); s.getFilterChain().fireMessageSent(s, writeRequest); } finally { s.getLock().unlock(); } flushPendingDataQueues( s ); } else { s.pendingDataQueue.add(writeRequest); } } else { writeRequest.getFuture().setWritten(false); } } @Override protected void doClose(IoSession session) { VmPipeSessionImpl s = (VmPipeSessionImpl) session; try { s.getLock().lock(); if (!session.getCloseFuture().isClosed()) { s.getServiceListeners().fireSessionDestroyed(s); s.getRemoteSession().close(); } } finally { s.getLock().unlock(); } } // FIXME Copied and pasted from {@link ExecutorFilter}. private static class EventType { public static final EventType CREATED = new EventType("CREATED"); public static final EventType OPENED = new EventType("OPENED"); public static final EventType CLOSED = new EventType("CLOSED"); public static final EventType RECEIVED = new EventType("RECEIVED"); public static final EventType SENT = new EventType("SENT"); public static final EventType IDLE = new EventType("IDLE"); public static final EventType EXCEPTION = new EventType("EXCEPTION"); public static final EventType WRITE = new EventType("WRITE"); public static final EventType CLOSE = new EventType("CLOSE"); private final String value; private EventType(String value) { this.value = value; } @Override public String toString() { return value; } } private static class Event { private final EventType type; private final Object data; private Event(EventType type, Object data) { this.type = type; this.data = data; } public Object getData() { return data; } public EventType getType() { return type; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeSessionImpl.java0000644000175000017500000001405511002320023033067 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe.support; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.common.support.IoServiceListenerSupport; /** * A {@link IoSession} for in-VM transport (VM_PIPE). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 575603 $, $Date: 2007-09-14 19:04:45 +0900 (Fri, 14 Sep 2007) $ */ public class VmPipeSessionImpl extends BaseIoSession { private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() { }; private final IoService service; private final IoServiceConfig serviceConfig; private final IoServiceListenerSupport serviceListeners; private final SocketAddress localAddress; private final SocketAddress remoteAddress; private final SocketAddress serviceAddress; private final IoHandler handler; private final VmPipeFilterChain filterChain; private final VmPipeSessionImpl remoteSession; private final Lock lock; final BlockingQueue pendingDataQueue; /* * Constructor for client-side session. */ public VmPipeSessionImpl( IoService service, IoServiceConfig serviceConfig, IoServiceListenerSupport serviceListeners, SocketAddress localAddress, IoHandler handler, VmPipe remoteEntry ) { this.service = service; this.serviceConfig = serviceConfig; this.serviceListeners = serviceListeners; this.lock = new ReentrantLock(); this.localAddress = localAddress; this.remoteAddress = this.serviceAddress = remoteEntry.getAddress(); this.handler = handler; this.filterChain = new VmPipeFilterChain(this); this.pendingDataQueue = new LinkedBlockingQueue(); remoteSession = new VmPipeSessionImpl(this, remoteEntry); } /* * Constructor for server-side session. */ private VmPipeSessionImpl(VmPipeSessionImpl remoteSession, VmPipe entry) { this.service = entry.getAcceptor(); this.serviceConfig = entry.getConfig(); this.serviceListeners = entry.getListeners(); this.lock = remoteSession.lock; this.localAddress = this.serviceAddress = remoteSession.remoteAddress; this.remoteAddress = remoteSession.localAddress; this.handler = entry.getHandler(); this.filterChain = new VmPipeFilterChain(this); this.remoteSession = remoteSession; this.pendingDataQueue = new LinkedBlockingQueue(); } public IoService getService() { return service; } IoServiceListenerSupport getServiceListeners() { return serviceListeners; } public IoServiceConfig getServiceConfig() { return serviceConfig; } public IoSessionConfig getConfig() { return CONFIG; } public IoFilterChain getFilterChain() { return filterChain; } public VmPipeSessionImpl getRemoteSession() { return remoteSession; } public IoHandler getHandler() { return handler; } @Override protected void close0() { filterChain.fireFilterClose(this); } @Override protected void write0(WriteRequest writeRequest) { this.filterChain.fireFilterWrite(this, writeRequest); } public TransportType getTransportType() { return TransportType.VM_PIPE; } public SocketAddress getRemoteAddress() { return remoteAddress; } public SocketAddress getLocalAddress() { return localAddress; } public SocketAddress getServiceAddress() { return serviceAddress; } @Override protected void updateTrafficMask() { if (getTrafficMask().isReadable() || getTrafficMask().isWritable()) { List data = new ArrayList(); pendingDataQueue.drainTo(data); for (Object aData : data) { if (aData instanceof WriteRequest) { // TODO Optimize unefficient data transfer. // Data will be returned to pendingDataQueue // if getTraffic().isWritable() is false. WriteRequest wr = (WriteRequest) aData; filterChain.doWrite(this, wr); } else { // TODO Optimize unefficient data transfer. // Data will be returned to pendingDataQueue // if getTraffic().isReadable() is false. filterChain.fireMessageReceived(this, aData); } } } } Lock getLock() { return lock; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java0000644000175000017500000001337511002320023031044 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe; import java.io.IOException; import java.net.SocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.support.AbstractIoFilterChain; import org.apache.mina.common.support.BaseIoConnector; import org.apache.mina.common.support.BaseIoConnectorConfig; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.common.support.DefaultConnectFuture; import org.apache.mina.transport.vmpipe.support.VmPipe; import org.apache.mina.transport.vmpipe.support.VmPipeFilterChain; import org.apache.mina.transport.vmpipe.support.VmPipeIdleStatusChecker; import org.apache.mina.transport.vmpipe.support.VmPipeSessionImpl; import org.apache.mina.util.AnonymousSocketAddress; /** * Connects to {@link IoHandler}s which is bound on the specified * {@link VmPipeAddress}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class VmPipeConnector extends BaseIoConnector { private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() { }; private final IoServiceConfig defaultConfig = new BaseIoConnectorConfig() { public IoSessionConfig getSessionConfig() { return CONFIG; } }; /** * Creates a new instance. */ public VmPipeConnector() { } public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config) { return connect(address, null, handler, config); } public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config) { if (address == null) throw new NullPointerException("address"); if (handler == null) throw new NullPointerException("handler"); if (!(address instanceof VmPipeAddress)) throw new IllegalArgumentException("address must be VmPipeAddress."); if (config == null) { config = getDefaultConfig(); } VmPipe entry = VmPipeAcceptor.boundHandlers.get(address); if (entry == null) { return DefaultConnectFuture.newFailedFuture(new IOException( "Endpoint unavailable: " + address)); } DefaultConnectFuture future = new DefaultConnectFuture(); VmPipeSessionImpl localSession = new VmPipeSessionImpl(this, config,getListeners(), new AnonymousSocketAddress(), handler, entry); // initialize connector session try { IoFilterChain filterChain = localSession.getFilterChain(); this.getFilterChainBuilder().buildFilterChain(filterChain); config.getFilterChainBuilder().buildFilterChain(filterChain); config.getThreadModel().buildFilterChain(filterChain); // The following sentences don't throw any exceptions. localSession.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE, future); getListeners().fireSessionCreated(localSession); VmPipeIdleStatusChecker.getInstance().addSession(localSession); } catch (Throwable t) { future.setException(t); return future; } // initialize acceptor session VmPipeSessionImpl remoteSession = localSession.getRemoteSession(); try { IoFilterChain filterChain = remoteSession.getFilterChain(); entry.getAcceptor().getFilterChainBuilder().buildFilterChain( filterChain); entry.getConfig().getFilterChainBuilder().buildFilterChain( filterChain); entry.getConfig().getThreadModel().buildFilterChain(filterChain); // The following sentences don't throw any exceptions. entry.getListeners().fireSessionCreated(remoteSession); VmPipeIdleStatusChecker.getInstance().addSession(remoteSession); } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); remoteSession.close(); } // Start chains, and then allow and messages read/written to be processed. This is to ensure that // sessionOpened gets received before a messageReceived ((VmPipeFilterChain) localSession.getFilterChain()).start(); ((VmPipeFilterChain) remoteSession.getFilterChain()).start(); return future; } public IoServiceConfig getDefaultConfig() { return defaultConfig; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/0000755000175000017500000000000011002320027025111 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/bio/0000755000175000017500000000000011002320027025662 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/0000755000175000017500000000000011044712500025705 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketSessionImpl.java0000644000175000017500000002616611002320027032172 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.TransportType; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.common.support.IoServiceListenerSupport; /** * An {@link IoSession} for socket transport (TCP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 585050 $, $Date: 2007-10-16 14:57:53 +0900 (Tue, 16 Oct 2007) $ */ class SocketSessionImpl extends BaseIoSession { private final IoService manager; private final IoServiceConfig serviceConfig; private final SocketSessionConfig config = new SessionConfigImpl(); private final SocketIoProcessor ioProcessor; private final SocketFilterChain filterChain; private final SocketChannel ch; private final Queue writeRequestQueue; private final IoHandler handler; private final SocketAddress remoteAddress; private final SocketAddress localAddress; private final SocketAddress serviceAddress; private final IoServiceListenerSupport serviceListeners; private SelectionKey key; private int readBufferSize = 1024; private boolean deferDecreaseReadBufferSize = true; /** * Creates a new instance. */ SocketSessionImpl(IoService manager, SocketIoProcessor ioProcessor, IoServiceListenerSupport listeners, IoServiceConfig serviceConfig, SocketChannel ch, IoHandler defaultHandler, SocketAddress serviceAddress) { this.manager = manager; this.serviceListeners = listeners; this.ioProcessor = ioProcessor; this.filterChain = new SocketFilterChain(this); this.ch = ch; this.writeRequestQueue = new ConcurrentLinkedQueue(); this.handler = defaultHandler; this.remoteAddress = ch.socket().getRemoteSocketAddress(); this.localAddress = ch.socket().getLocalSocketAddress(); this.serviceAddress = serviceAddress; this.serviceConfig = serviceConfig; // Apply the initial session settings IoSessionConfig sessionConfig = serviceConfig.getSessionConfig(); if (sessionConfig instanceof SocketSessionConfig) { SocketSessionConfig cfg = (SocketSessionConfig) sessionConfig; this.config.setKeepAlive(cfg.isKeepAlive()); this.config.setOobInline(cfg.isOobInline()); this.config.setReceiveBufferSize(cfg.getReceiveBufferSize()); this.config.setReuseAddress(cfg.isReuseAddress()); this.config.setSendBufferSize(cfg.getSendBufferSize()); this.config.setSoLinger(cfg.getSoLinger()); this.config.setTcpNoDelay(cfg.isTcpNoDelay()); if (this.config.getTrafficClass() != cfg.getTrafficClass()) { this.config.setTrafficClass(cfg.getTrafficClass()); } } } public IoService getService() { return manager; } public IoServiceConfig getServiceConfig() { return serviceConfig; } public IoSessionConfig getConfig() { return config; } SocketIoProcessor getIoProcessor() { return ioProcessor; } public IoFilterChain getFilterChain() { return filterChain; } SocketChannel getChannel() { return ch; } IoServiceListenerSupport getServiceListeners() { return serviceListeners; } SelectionKey getSelectionKey() { return key; } void setSelectionKey(SelectionKey key) { this.key = key; } public IoHandler getHandler() { return handler; } @Override protected void close0() { filterChain.fireFilterClose(this); } Queue getWriteRequestQueue() { return writeRequestQueue; } @Override protected void write0(WriteRequest writeRequest) { filterChain.fireFilterWrite(this, writeRequest); } public TransportType getTransportType() { return TransportType.SOCKET; } public SocketAddress getRemoteAddress() { return remoteAddress; } public SocketAddress getLocalAddress() { return localAddress; } public SocketAddress getServiceAddress() { return serviceAddress; } @Override protected void updateTrafficMask() { this.ioProcessor.updateTrafficMask(this); } int getReadBufferSize() { return readBufferSize; } void increaseReadBufferSize() { int newReadBufferSize = getReadBufferSize() << 1; if (newReadBufferSize <= ((SocketSessionConfig) getConfig()).getReceiveBufferSize() << 1) { // read buffer size shouldn't get bigger than // twice of the receive buffer size because of // read-write fairness. setReadBufferSize(newReadBufferSize); } } void decreaseReadBufferSize() { if (deferDecreaseReadBufferSize) { deferDecreaseReadBufferSize = false; return; } if (getReadBufferSize() > 64) { setReadBufferSize(getReadBufferSize() >>> 1); } } private void setReadBufferSize(int readBufferSize) { this.readBufferSize = readBufferSize; this.deferDecreaseReadBufferSize = true; } private class SessionConfigImpl extends BaseIoSessionConfig implements SocketSessionConfig { public boolean isKeepAlive() { try { return ch.socket().getKeepAlive(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setKeepAlive(boolean on) { try { ch.socket().setKeepAlive(on); } catch (SocketException e) { throw new RuntimeIOException(e); } } public boolean isOobInline() { try { return ch.socket().getOOBInline(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setOobInline(boolean on) { try { ch.socket().setOOBInline(on); } catch (SocketException e) { throw new RuntimeIOException(e); } } public boolean isReuseAddress() { try { return ch.socket().getReuseAddress(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setReuseAddress(boolean on) { try { ch.socket().setReuseAddress(on); } catch (SocketException e) { throw new RuntimeIOException(e); } } public int getSoLinger() { try { return ch.socket().getSoLinger(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setSoLinger(int linger) { try { if (linger < 0) { ch.socket().setSoLinger(false, 0); } else { ch.socket().setSoLinger(true, linger); } } catch (SocketException e) { throw new RuntimeIOException(e); } } public boolean isTcpNoDelay() { try { return ch.socket().getTcpNoDelay(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setTcpNoDelay(boolean on) { try { ch.socket().setTcpNoDelay(on); } catch (SocketException e) { throw new RuntimeIOException(e); } } public int getTrafficClass() { if (SocketSessionConfigImpl.isGetTrafficClassAvailable()) { try { return ch.socket().getTrafficClass(); } catch (SocketException e) { // Throw an exception only when setTrafficClass is also available. if (SocketSessionConfigImpl.isSetTrafficClassAvailable()) { throw new RuntimeIOException(e); } } } return 0; } public void setTrafficClass(int tc) { if (SocketSessionConfigImpl.isSetTrafficClassAvailable()) { try { ch.socket().setTrafficClass(tc); } catch (SocketException e) { throw new RuntimeIOException(e); } } } public int getSendBufferSize() { try { return ch.socket().getSendBufferSize(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setSendBufferSize(int size) { if (SocketSessionConfigImpl.isSetSendBufferSizeAvailable()) { try { ch.socket().setSendBufferSize(size); } catch (SocketException e) { throw new RuntimeIOException(e); } } } public int getReceiveBufferSize() { try { return ch.socket().getReceiveBufferSize(); } catch (SocketException e) { throw new RuntimeIOException(e); } } public void setReceiveBufferSize(int size) { if (SocketSessionConfigImpl.isSetReceiveBufferSizeAvailable()) { try { ch.socket().setReceiveBufferSize(size); } catch (SocketException e) { throw new RuntimeIOException(e); } } } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketConnectorConfig.java0000644000175000017500000000320711002320027032774 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import org.apache.mina.common.IoConnectorConfig; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.support.BaseIoConnectorConfig; /** * An {@link IoConnectorConfig} for {@link SocketConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class SocketConnectorConfig extends BaseIoConnectorConfig { private SocketSessionConfig sessionConfig = new SocketSessionConfigImpl(); /** * Creates a new instance. * * @throws RuntimeIOException if failed to get the default configuration */ public SocketConnectorConfig() { } public SocketSessionConfig getSessionConfig() { return sessionConfig; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramSessionConfig.java0000644000175000017500000000435211002320027032757 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.DatagramSocket; import org.apache.mina.common.IoSessionConfig; /** * An {@link IoSessionConfig} for datagram transport type. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface DatagramSessionConfig extends IoSessionConfig { /** * @see DatagramSocket#getBroadcast() */ boolean isBroadcast(); /** * @see DatagramSocket#setBroadcast(boolean) */ void setBroadcast(boolean broadcast); /** * @see DatagramSocket#getReuseAddress() */ boolean isReuseAddress(); /** * @see DatagramSocket#setReuseAddress(boolean) */ void setReuseAddress(boolean reuseAddress); /** * @see DatagramSocket#getReceiveBufferSize() */ int getReceiveBufferSize(); /** * @see DatagramSocket#setReceiveBufferSize(int) */ void setReceiveBufferSize(int receiveBufferSize); /** * @see DatagramSocket#getSendBufferSize() */ int getSendBufferSize(); /** * @see DatagramSocket#setSendBufferSize(int) */ void setSendBufferSize(int sendBufferSize); /** * @see DatagramSocket#getTrafficClass() */ int getTrafficClass(); /** * @see DatagramSocket#setTrafficClass(int) */ void setTrafficClass(int trafficClass); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketAcceptor.java0000644000175000017500000003645711002320027031471 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.support.BaseIoAcceptor; import org.apache.mina.util.NamePreservingRunnable; import org.apache.mina.util.NewThreadExecutor; /** * {@link IoAcceptor} for socket transport (TCP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 389042 $, $Date: 2006-03-27 07:49:41Z $ */ public class SocketAcceptor extends BaseIoAcceptor { private static final AtomicInteger nextId = new AtomicInteger(); private final Executor executor; private final Object lock = new Object(); private final int id = nextId.getAndIncrement(); private final String threadName = "SocketAcceptor-" + id; private SocketAcceptorConfig defaultConfig = new SocketAcceptorConfig(); private final Map channels = new ConcurrentHashMap(); private final Queue registerQueue = new ConcurrentLinkedQueue(); private final Queue cancelQueue = new ConcurrentLinkedQueue(); private final SocketIoProcessor[] ioProcessors; private final int processorCount; private volatile Selector selector; private Worker worker; private int processorDistributor = 0; /** * Create an acceptor with a single processing thread using a NewThreadExecutor */ public SocketAcceptor() { this(1, new NewThreadExecutor()); } /** * Create an acceptor with the desired number of processing threads * * @param processorCount Number of processing threads * @param executor Executor to use for launching threads */ public SocketAcceptor(int processorCount, Executor executor) { if (processorCount < 1) { throw new IllegalArgumentException( "Must have at least one processor"); } // The default reuseAddress of an accepted socket should be 'true'. defaultConfig.getSessionConfig().setReuseAddress(true); this.executor = executor; this.processorCount = processorCount; ioProcessors = new SocketIoProcessor[processorCount]; for (int i = 0; i < processorCount; i++) { ioProcessors[i] = new SocketIoProcessor( "SocketAcceptorIoProcessor-" + id + "." + i, executor); } } /** * Binds to the specified address and handles incoming connections with the specified * handler. Backlog value is configured to the value of backlog property. * * @throws IOException if failed to bind */ public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException { if (handler == null) { throw new NullPointerException("handler"); } if (address != null && !(address instanceof InetSocketAddress)) { throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); } if (config == null) { config = getDefaultConfig(); } RegistrationRequest request = new RegistrationRequest(address, handler, config); synchronized (lock) { startupWorker(); registerQueue.add(request); selector.wakeup(); } try { request.done.await(); } catch (InterruptedException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } if (request.exception != null) { throw request.exception; } } private void startupWorker() throws IOException { synchronized (lock) { if (worker == null) { selector = Selector.open(); worker = new Worker(); executor.execute(new NamePreservingRunnable(worker, threadName)); } } } public void unbind(SocketAddress address) { if (address == null) { throw new NullPointerException("address"); } CancellationRequest request = new CancellationRequest(address); synchronized (lock) { try { startupWorker(); } catch (IOException e) { // IOException is thrown only when Worker thread is not // running and failed to open a selector. We simply throw // IllegalArgumentException here because we can simply // conclude that nothing is bound to the selector. throw new IllegalArgumentException("Address not bound: " + address); } cancelQueue.add(request); selector.wakeup(); } try { request.done.await(); } catch (InterruptedException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } if (request.exception != null) { request.exception.fillInStackTrace(); throw request.exception; } } public void unbindAll() { List addresses = new ArrayList(channels .keySet()); for (SocketAddress address : addresses) { unbind(address); } } private class Worker implements Runnable { public void run() { Selector selector = SocketAcceptor.this.selector; for (;;) { try { int nKeys = selector.select(); registerNew(); if (nKeys > 0) { processSessions(selector.selectedKeys()); } cancelKeys(); if (selector.keys().isEmpty()) { synchronized (lock) { if (selector.keys().isEmpty() && registerQueue.isEmpty() && cancelQueue.isEmpty()) { worker = null; try { selector.close(); } catch (IOException e) { ExceptionMonitor.getInstance() .exceptionCaught(e); } finally { SocketAcceptor.this.selector = null; } break; } } } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } } private void processSessions(Set keys) throws IOException { Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (!key.isAcceptable()) { continue; } ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel ch = ssc.accept(); if (ch == null) { continue; } boolean success = false; try { RegistrationRequest req = (RegistrationRequest) key .attachment(); SocketSessionImpl session = new SocketSessionImpl( SocketAcceptor.this, nextProcessor(), getListeners(), req.config, ch, req.handler, req.address); getFilterChainBuilder().buildFilterChain( session.getFilterChain()); req.config.getFilterChainBuilder().buildFilterChain( session.getFilterChain()); req.config.getThreadModel().buildFilterChain( session.getFilterChain()); session.getIoProcessor().addNew(session); success = true; } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); } finally { if (!success) { ch.close(); } } } } } private SocketIoProcessor nextProcessor() { if (this.processorDistributor == Integer.MAX_VALUE) { this.processorDistributor = Integer.MAX_VALUE % this.processorCount; } return ioProcessors[processorDistributor++ % processorCount]; } public SocketAcceptorConfig getDefaultConfig() { return defaultConfig; } /** * Sets the config this acceptor will use by default. * * @param defaultConfig the default config. * @throws NullPointerException if the specified value is null. */ public void setDefaultConfig(SocketAcceptorConfig defaultConfig) { if (defaultConfig == null) { throw new NullPointerException("defaultConfig"); } this.defaultConfig = defaultConfig; } private void registerNew() { if (registerQueue.isEmpty()) { return; } Selector selector = this.selector; for (;;) { RegistrationRequest req = registerQueue.poll(); if (req == null) { break; } ServerSocketChannel ssc = null; try { ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); // Configure the server socket, SocketAcceptorConfig cfg; if (req.config instanceof SocketAcceptorConfig) { cfg = (SocketAcceptorConfig) req.config; } else { cfg = getDefaultConfig(); } ssc.socket().setReuseAddress(cfg.isReuseAddress()); ssc.socket().setReceiveBufferSize( cfg.getSessionConfig().getReceiveBufferSize()); // and bind. ssc.socket().bind(req.address, cfg.getBacklog()); if (req.address == null || req.address.getPort() == 0) { req.address = (InetSocketAddress) ssc.socket() .getLocalSocketAddress(); } ssc.register(selector, SelectionKey.OP_ACCEPT, req); channels.put(req.address, ssc); getListeners().fireServiceActivated(this, req.address, req.handler, req.config); } catch (IOException e) { req.exception = e; } finally { req.done.countDown(); if (ssc != null && req.exception != null) { try { ssc.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } } } private void cancelKeys() { if (cancelQueue.isEmpty()) { return; } Selector selector = this.selector; for (;;) { CancellationRequest request = cancelQueue.poll(); if (request == null) { break; } ServerSocketChannel ssc = channels.remove(request.address); // close the channel try { if (ssc == null) { request.exception = new IllegalArgumentException( "Address not bound: " + request.address); } else { SelectionKey key = ssc.keyFor(selector); request.registrationRequest = (RegistrationRequest) key .attachment(); key.cancel(); selector.wakeup(); // wake up again to trigger thread death ssc.close(); } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } finally { request.done.countDown(); if (request.exception == null) { getListeners().fireServiceDeactivated(this, request.address, request.registrationRequest.handler, request.registrationRequest.config); } } } } private static class RegistrationRequest { private InetSocketAddress address; private final IoHandler handler; private final IoServiceConfig config; private final CountDownLatch done = new CountDownLatch(1); private volatile IOException exception; private RegistrationRequest(SocketAddress address, IoHandler handler, IoServiceConfig config) { this.address = (InetSocketAddress) address; this.handler = handler; this.config = config; } } private static class CancellationRequest { private final SocketAddress address; private final CountDownLatch done = new CountDownLatch(1); private RegistrationRequest registrationRequest; private volatile RuntimeException exception; private CancellationRequest(SocketAddress address) { this.address = address; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/package.html0000644000175000017500000000076711002320027030171 0ustar drazzibdrazzib Socket (TCP/IP) and Datagram (UDP/IP) support based on Java NIO (New I/O) API.

Configuring the number of NIO selector loops

You can specify the number of Socket I/O thread to utilize multi-processors efficiently by specifying the number of processing threads in the constructor. The default is 1

mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramAcceptor.java0000644000175000017500000000445311002320027031750 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.util.concurrent.Executor; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.support.DelegatedIoAcceptor; import org.apache.mina.transport.socket.nio.support.DatagramAcceptorDelegate; import org.apache.mina.util.NewThreadExecutor; /** * {@link IoAcceptor} for datagram transport (UDP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class DatagramAcceptor extends DelegatedIoAcceptor { /** * Creates a new instance using a NewThreadExecutor */ public DatagramAcceptor() { init(new DatagramAcceptorDelegate(this, new NewThreadExecutor())); } /** * Creates a new instance. * * @param executor Executor to use for launching threads */ public DatagramAcceptor(Executor executor) { init(new DatagramAcceptorDelegate(this, executor)); } @Override public DatagramAcceptorConfig getDefaultConfig() { return (DatagramAcceptorConfig) super.getDefaultConfig(); } /** * Sets the config this acceptor will use by default. * * @param defaultConfig the default config. * @throws NullPointerException if the specified value is null. */ public void setDefaultConfig(DatagramAcceptorConfig defaultConfig) { ((DatagramAcceptorDelegate) delegate).setDefaultConfig(defaultConfig); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketSessionConfigImpl.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketSessionConfigImpl.java0000644000175000017500000002321211002320027033305 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoConnectorConfig; import org.apache.mina.common.support.BaseIoSessionConfig; /** * An {@link IoConnectorConfig} for {@link SocketConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 647053 $, $Date: 2008-04-11 14:40:04 +0900 (Fri, 11 Apr 2008) $ */ public class SocketSessionConfigImpl extends BaseIoSessionConfig implements SocketSessionConfig { private static Map TEST_ADDRESSES = new LinkedHashMap(); private static boolean SET_RECEIVE_BUFFER_SIZE_AVAILABLE = false; private static boolean SET_SEND_BUFFER_SIZE_AVAILABLE = false; private static boolean GET_TRAFFIC_CLASS_AVAILABLE = false; private static boolean SET_TRAFFIC_CLASS_AVAILABLE = false; private static boolean DEFAULT_REUSE_ADDRESS = false; private static int DEFAULT_RECEIVE_BUFFER_SIZE = 1024; private static int DEFAULT_SEND_BUFFER_SIZE = 1024; private static int DEFAULT_TRAFFIC_CLASS = 0; private static boolean DEFAULT_KEEP_ALIVE = false; private static boolean DEFAULT_OOB_INLINE = false; private static int DEFAULT_SO_LINGER = -1; private static boolean DEFAULT_TCP_NO_DELAY = false; static { initializeTestAddresses(); boolean success = false; for (Entry e : TEST_ADDRESSES .entrySet()) { success = initializeDefaultSocketParameters(e.getKey(), e .getValue()); if (success) { break; } } if (!success) { initializeFallbackDefaultSocketParameters(); } } private static void initializeFallbackDefaultSocketParameters() { Socket unconnectedSocket = new Socket(); // Use a unconnected socket. try { initializeDefaultSocketParameters(unconnectedSocket); } catch (SocketException se) { ExceptionMonitor.getInstance().exceptionCaught(se); try { unconnectedSocket.close(); } catch (IOException ioe) { ExceptionMonitor.getInstance().exceptionCaught(ioe); } } } private static void initializeTestAddresses() { try { // These two tests were disabled due to DIRMINA-560 // (IPv4 localhost TEST_ADDRESS causes server to hang) // IPv6 localhost //TEST_ADDRESSES.put(new InetSocketAddress(InetAddress // .getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0, 0, 0, 0, 1 }), 0), InetAddress // .getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0, 0, 0, 0, 1 })); // IPv4 localhost //TEST_ADDRESSES.put(new InetSocketAddress(InetAddress // .getByAddress(new byte[] { 127, 0, 0, 1 }), 0), InetAddress // .getByAddress(new byte[] { 127, 0, 0, 1 })); // Bind to wildcard interface and connect to IPv6 localhost TEST_ADDRESSES.put(new InetSocketAddress(0), InetAddress .getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 })); // Bind to wildcard interface and connect to IPv4 localhost TEST_ADDRESSES.put(new InetSocketAddress(0), InetAddress .getByAddress(new byte[] { 127, 0, 0, 1 })); } catch (UnknownHostException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } private static boolean initializeDefaultSocketParameters( InetSocketAddress bindAddress, InetAddress connectAddress) { ServerSocket ss = null; Socket socket = null; try { ss = new ServerSocket(); ss.bind(bindAddress); socket = new Socket(); // Timeout is set to 10 seconds in case of infinite blocking // on some platform. socket.connect(new InetSocketAddress(connectAddress, ss .getLocalPort()), 10000); initializeDefaultSocketParameters(socket); return true; } catch (Exception e) { return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } if (ss != null) { try { ss.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } } private static void initializeDefaultSocketParameters(Socket socket) throws SocketException { DEFAULT_REUSE_ADDRESS = socket.getReuseAddress(); DEFAULT_RECEIVE_BUFFER_SIZE = socket.getReceiveBufferSize(); DEFAULT_SEND_BUFFER_SIZE = socket.getSendBufferSize(); DEFAULT_KEEP_ALIVE = socket.getKeepAlive(); DEFAULT_OOB_INLINE = socket.getOOBInline(); DEFAULT_SO_LINGER = socket.getSoLinger(); DEFAULT_TCP_NO_DELAY = socket.getTcpNoDelay(); // Check if setReceiveBufferSize is supported. try { socket.setReceiveBufferSize(DEFAULT_RECEIVE_BUFFER_SIZE); SET_RECEIVE_BUFFER_SIZE_AVAILABLE = true; } catch (SocketException e) { SET_RECEIVE_BUFFER_SIZE_AVAILABLE = false; } // Check if setSendBufferSize is supported. try { socket.setSendBufferSize(DEFAULT_SEND_BUFFER_SIZE); SET_SEND_BUFFER_SIZE_AVAILABLE = true; } catch (SocketException e) { SET_SEND_BUFFER_SIZE_AVAILABLE = false; } // Check if getTrafficClass is supported. try { DEFAULT_TRAFFIC_CLASS = socket.getTrafficClass(); GET_TRAFFIC_CLASS_AVAILABLE = true; } catch (SocketException e) { GET_TRAFFIC_CLASS_AVAILABLE = false; DEFAULT_TRAFFIC_CLASS = 0; } } public static boolean isSetReceiveBufferSizeAvailable() { return SET_RECEIVE_BUFFER_SIZE_AVAILABLE; } public static boolean isSetSendBufferSizeAvailable() { return SET_SEND_BUFFER_SIZE_AVAILABLE; } public static boolean isGetTrafficClassAvailable() { return GET_TRAFFIC_CLASS_AVAILABLE; } public static boolean isSetTrafficClassAvailable() { return SET_TRAFFIC_CLASS_AVAILABLE; } private boolean reuseAddress = DEFAULT_REUSE_ADDRESS; private int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE; private int sendBufferSize = DEFAULT_SEND_BUFFER_SIZE; private int trafficClass = DEFAULT_TRAFFIC_CLASS; private boolean keepAlive = DEFAULT_KEEP_ALIVE; private boolean oobInline = DEFAULT_OOB_INLINE; private int soLinger = DEFAULT_SO_LINGER; private boolean tcpNoDelay = DEFAULT_TCP_NO_DELAY; /** * Creates a new instance. */ public SocketSessionConfigImpl() { } public boolean isReuseAddress() { return reuseAddress; } public void setReuseAddress(boolean reuseAddress) { this.reuseAddress = reuseAddress; } public int getReceiveBufferSize() { return receiveBufferSize; } public void setReceiveBufferSize(int receiveBufferSize) { this.receiveBufferSize = receiveBufferSize; } public int getSendBufferSize() { return sendBufferSize; } public void setSendBufferSize(int sendBufferSize) { this.sendBufferSize = sendBufferSize; } public int getTrafficClass() { return trafficClass; } public void setTrafficClass(int trafficClass) { this.trafficClass = trafficClass; } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } public boolean isOobInline() { return oobInline; } public void setOobInline(boolean oobInline) { this.oobInline = oobInline; } public int getSoLinger() { return soLinger; } public void setSoLinger(int soLinger) { this.soLinger = soLinger; } public boolean isTcpNoDelay() { return tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramConnectorConfig.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramConnectorConfig.java0000644000175000017500000000531111002320027033262 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import org.apache.mina.common.ExpiringSessionRecycler; import org.apache.mina.common.IoConnectorConfig; import org.apache.mina.common.IoSessionRecycler; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.support.BaseIoConnectorConfig; import org.apache.mina.transport.socket.nio.support.DatagramSessionConfigImpl; /** * An {@link IoConnectorConfig} for {@link DatagramConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class DatagramConnectorConfig extends BaseIoConnectorConfig implements DatagramServiceConfig { private static final IoSessionRecycler DEFAULT_RECYCLER = new ExpiringSessionRecycler(); /** * Current session recycler */ private IoSessionRecycler sessionRecycler = DEFAULT_RECYCLER; private DatagramSessionConfig sessionConfig = new DatagramSessionConfigImpl(); /** * Creates a new instance. * * @throws RuntimeIOException if failed to get the default configuration */ public DatagramConnectorConfig() { super(); } public DatagramSessionConfig getSessionConfig() { return sessionConfig; } public IoSessionRecycler getSessionRecycler() { return sessionRecycler; } // FIXME There can be a problem if a user changes the recycler after the service is activated. public void setSessionRecycler(IoSessionRecycler sessionRecycler) { if (sessionRecycler == null) { sessionRecycler = DEFAULT_RECYCLER; } this.sessionRecycler = sessionRecycler; } public Object clone() { DatagramConnectorConfig ret = (DatagramConnectorConfig) super.clone(); ret.sessionConfig = (DatagramSessionConfig) this.sessionConfig.clone(); return ret; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketSessionConfig.java0000644000175000017500000000641411002320027032470 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.Socket; import org.apache.mina.common.IoSessionConfig; /** * An {@link IoSessionConfig} for socket transport type. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface SocketSessionConfig extends IoSessionConfig { /** * @see Socket#getReuseAddress() */ boolean isReuseAddress(); /** * @see Socket#setReuseAddress(boolean) */ void setReuseAddress(boolean reuseAddress); /** * @see Socket#getReceiveBufferSize() */ int getReceiveBufferSize(); /** * @see Socket#setReceiveBufferSize(int) */ void setReceiveBufferSize(int receiveBufferSize); /** * @see Socket#getSendBufferSize() */ int getSendBufferSize(); /** * @see Socket#setSendBufferSize(int) */ void setSendBufferSize(int sendBufferSize); /** * @see Socket#getTrafficClass() */ int getTrafficClass(); /** * @see Socket#setTrafficClass(int) */ void setTrafficClass(int trafficClass); /** * @see Socket#getKeepAlive() */ boolean isKeepAlive(); /** * @see Socket#setKeepAlive(boolean) */ void setKeepAlive(boolean keepAlive); /** * @see Socket#getOOBInline() */ boolean isOobInline(); /** * @see Socket#setOOBInline(boolean) */ void setOobInline(boolean oobInline); /** * Please note that enabling SO_LINGER in Java NIO can result * in platform-dependent behavior and unexpected blocking of I/O thread. * * @see Socket#getSoLinger() * @see Sun Bug Database */ int getSoLinger(); /** * Please note that enabling SO_LINGER in Java NIO can result * in platform-dependent behavior and unexpected blocking of I/O thread. * * @param soLinger Please specify a negative value to disable SO_LINGER. * * @see Socket#setSoLinger(boolean, int) * @see Sun Bug Database */ void setSoLinger(int soLinger); /** * @see Socket#getTcpNoDelay() */ boolean isTcpNoDelay(); /** * @see Socket#setTcpNoDelay(boolean) */ void setTcpNoDelay(boolean tcpNoDelay); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketAcceptorConfig.java0000644000175000017500000000545311002320027032607 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.io.IOException; import java.net.ServerSocket; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.support.BaseIoAcceptorConfig; /** * An {@link IoAcceptorConfig} for {@link SocketAcceptor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class SocketAcceptorConfig extends BaseIoAcceptorConfig { private SocketSessionConfig sessionConfig = new SocketSessionConfigImpl(); private int backlog = 50; private boolean reuseAddress; /** * Creates a new instance. * * @throws RuntimeIOException if failed to get the default configuration */ public SocketAcceptorConfig() { ServerSocket s = null; try { s = new ServerSocket(); reuseAddress = s.getReuseAddress(); } catch (IOException e) { throw new RuntimeIOException( "Failed to get the default configuration.", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } sessionConfig.setReuseAddress(true); } public SocketSessionConfig getSessionConfig() { return sessionConfig; } /** * @see ServerSocket#getReuseAddress() */ public boolean isReuseAddress() { return reuseAddress; } /** * @see ServerSocket#setReuseAddress(boolean) */ public void setReuseAddress(boolean reuseAddress) { this.reuseAddress = reuseAddress; } public int getBacklog() { return backlog; } public void setBacklog(int backlog) { this.backlog = backlog; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramAcceptorConfig.java0000644000175000017500000000535511002320027033100 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import org.apache.mina.common.ExpiringSessionRecycler; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.common.IoSessionRecycler; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.support.BaseIoAcceptorConfig; import org.apache.mina.transport.socket.nio.support.DatagramSessionConfigImpl; /** * An {@link IoAcceptorConfig} for {@link DatagramAcceptor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class DatagramAcceptorConfig extends BaseIoAcceptorConfig implements DatagramServiceConfig { private static final IoSessionRecycler DEFAULT_RECYCLER = new ExpiringSessionRecycler(); /** * Current session recycler */ private IoSessionRecycler sessionRecycler = DEFAULT_RECYCLER; private DatagramSessionConfig sessionConfig = new DatagramSessionConfigImpl(); /** * Creates a new instance. * * @throws RuntimeIOException if failed to get the default configuration */ public DatagramAcceptorConfig() { super(); sessionConfig.setReuseAddress(true); } public DatagramSessionConfig getSessionConfig() { return sessionConfig; } public IoSessionRecycler getSessionRecycler() { return sessionRecycler; } // FIXME There can be a problem if a user changes the recycler after the service is activated. public void setSessionRecycler(IoSessionRecycler sessionRecycler) { if (sessionRecycler == null) { sessionRecycler = DEFAULT_RECYCLER; } this.sessionRecycler = sessionRecycler; } public Object clone() { DatagramAcceptorConfig ret = (DatagramAcceptorConfig) super.clone(); ret.sessionConfig = (DatagramSessionConfig) this.sessionConfig.clone(); return ret; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketFilterChain.java0000644000175000017500000000464411002320027032112 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.io.IOException; import java.util.Queue; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.common.support.AbstractIoFilterChain; /** * An {@link IoFilterChain} for socket transport (TCP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) */ class SocketFilterChain extends AbstractIoFilterChain { SocketFilterChain(IoSession parent) { super(parent); } @Override protected void doWrite(IoSession session, WriteRequest writeRequest) { SocketSessionImpl s = (SocketSessionImpl) session; Queue writeRequestQueue = s.getWriteRequestQueue(); // SocketIoProcessor.doFlush() will reset it after write is finished // because the buffer will be passed with messageSent event. ByteBuffer buffer = (ByteBuffer) writeRequest.getMessage(); buffer.mark(); int remaining = buffer.remaining(); if (remaining == 0) { s.increaseScheduledWriteRequests(); } else { s.increaseScheduledWriteBytes(buffer.remaining()); } writeRequestQueue.add(writeRequest); if (session.getTrafficMask().isWritable()) { s.getIoProcessor().flush(s); } } @Override protected void doClose(IoSession session) throws IOException { SocketSessionImpl s = (SocketSessionImpl) session; s.getIoProcessor().remove(s); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/0000755000175000017500000000000011044712500027421 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramService.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramService.java0000644000175000017500000000335311002320027033322 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio.support; /** * A base interface for {@link DatagramAcceptorDelegate} and {@link DatagramConnectorDelegate}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ interface DatagramService { /** * Requests this processor to flush the write buffer of the specified * session. This method is invoked by MINA internally. */ void flushSession(DatagramSessionImpl session); /** * Requests this processor to close the specified session. * This method is invoked by MINA internally. */ void closeSession(DatagramSessionImpl session); /** * Requests this processor to update the traffic mask for the specified * session. This method is invoked by MINA internally. */ void updateTrafficMask(DatagramSessionImpl session); }././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.0000644000175000017500000002225511002320027033327 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio.support; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.common.BroadcastIoSession; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.TransportType; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.transport.socket.nio.DatagramServiceConfig; import org.apache.mina.transport.socket.nio.DatagramSessionConfig; /** * An {@link IoSession} for datagram transport (UDP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 585050 $, $Date: 2007-10-16 14:57:53 +0900 (Tue, 16 Oct 2007) $ */ class DatagramSessionImpl extends BaseIoSession implements BroadcastIoSession { private final IoService wrapperManager; private final IoServiceConfig serviceConfig; private final DatagramSessionConfig config = new SessionConfigImpl(); private final DatagramService managerDelegate; private final DatagramFilterChain filterChain; private final DatagramChannel ch; private final Queue writeRequestQueue; private final IoHandler handler; private final SocketAddress localAddress; private final SocketAddress serviceAddress; private SocketAddress remoteAddress; private SelectionKey key; private int readBufferSize; /** * Creates a new instance. */ DatagramSessionImpl(IoService wrapperManager, DatagramService managerDelegate, IoServiceConfig serviceConfig, DatagramChannel ch, IoHandler defaultHandler, SocketAddress serviceAddress, SocketAddress localAddress) { this.wrapperManager = wrapperManager; this.managerDelegate = managerDelegate; this.filterChain = new DatagramFilterChain(this); this.ch = ch; this.writeRequestQueue = new ConcurrentLinkedQueue(); this.handler = defaultHandler; this.remoteAddress = ch.socket().getRemoteSocketAddress(); this.serviceAddress = serviceAddress; this.localAddress = localAddress; this.serviceConfig = serviceConfig; // Apply the initial session settings IoSessionConfig sessionConfig = serviceConfig.getSessionConfig(); if (sessionConfig instanceof DatagramSessionConfig) { DatagramSessionConfig cfg = (DatagramSessionConfig) sessionConfig; this.config.setBroadcast(cfg.isBroadcast()); this.config.setReceiveBufferSize(cfg.getReceiveBufferSize()); this.config.setReuseAddress(cfg.isReuseAddress()); this.config.setSendBufferSize(cfg.getSendBufferSize()); if (this.config.getTrafficClass() != cfg.getTrafficClass()) { this.config.setTrafficClass(cfg.getTrafficClass()); } } } public IoService getService() { return wrapperManager; } public IoServiceConfig getServiceConfig() { return serviceConfig; } public IoSessionConfig getConfig() { return config; } DatagramService getManagerDelegate() { return managerDelegate; } public IoFilterChain getFilterChain() { return filterChain; } DatagramChannel getChannel() { return ch; } SelectionKey getSelectionKey() { return key; } void setSelectionKey(SelectionKey key) { this.key = key; } public IoHandler getHandler() { return handler; } @Override protected void close0() { IoServiceConfig config = getServiceConfig(); if (config instanceof DatagramServiceConfig) { ((DatagramServiceConfig) config).getSessionRecycler().remove(this); } filterChain.fireFilterClose(this); } Queue getWriteRequestQueue() { return writeRequestQueue; } @Override protected void write0(WriteRequest writeRequest) { filterChain.fireFilterWrite(this, writeRequest); } public TransportType getTransportType() { return TransportType.DATAGRAM; } public SocketAddress getRemoteAddress() { return remoteAddress; } void setRemoteAddress(SocketAddress remoteAddress) { this.remoteAddress = remoteAddress; } public SocketAddress getLocalAddress() { return localAddress; } public SocketAddress getServiceAddress() { return serviceAddress; } @Override protected void updateTrafficMask() { managerDelegate.updateTrafficMask(this); } int getReadBufferSize() { return readBufferSize; } private class SessionConfigImpl extends DatagramSessionConfigImpl implements DatagramSessionConfig { @Override public int getReceiveBufferSize() { try { return ch.socket().getReceiveBufferSize(); } catch (SocketException e) { throw new RuntimeIOException(e); } } @Override public void setReceiveBufferSize(int receiveBufferSize) { if (DatagramSessionConfigImpl.isSetReceiveBufferSizeAvailable()) { try { ch.socket().setReceiveBufferSize(receiveBufferSize); // Re-retrieve the effective receive buffer size. receiveBufferSize = ch.socket().getReceiveBufferSize(); DatagramSessionImpl.this.readBufferSize = receiveBufferSize; } catch (SocketException e) { throw new RuntimeIOException(e); } } } @Override public boolean isBroadcast() { try { return ch.socket().getBroadcast(); } catch (SocketException e) { throw new RuntimeIOException(e); } } @Override public void setBroadcast(boolean broadcast) { try { ch.socket().setBroadcast(broadcast); } catch (SocketException e) { throw new RuntimeIOException(e); } } @Override public int getSendBufferSize() { try { return ch.socket().getSendBufferSize(); } catch (SocketException e) { throw new RuntimeIOException(e); } } @Override public void setSendBufferSize(int sendBufferSize) { if (DatagramSessionConfigImpl.isSetSendBufferSizeAvailable()) { try { ch.socket().setSendBufferSize(sendBufferSize); } catch (SocketException e) { throw new RuntimeIOException(e); } } } @Override public boolean isReuseAddress() { try { return ch.socket().getReuseAddress(); } catch (SocketException e) { throw new RuntimeIOException(e); } } @Override public void setReuseAddress(boolean reuseAddress) { try { ch.socket().setReuseAddress(reuseAddress); } catch (SocketException e) { throw new RuntimeIOException(e); } } @Override public int getTrafficClass() { if (DatagramSessionConfigImpl.isGetTrafficClassAvailable()) { try { return ch.socket().getTrafficClass(); } catch (SocketException e) { throw new RuntimeIOException(e); } } else { return 0; } } @Override public void setTrafficClass(int trafficClass) { if (DatagramSessionConfigImpl.isSetTrafficClassAvailable()) { try { ch.socket().setTrafficClass(trafficClass); } catch (SocketException e) { throw new RuntimeIOException(e); } } } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/package.html0000644000175000017500000000027511002320027031677 0ustar drazzibdrazzib Internal classes used by org.apache.mina.transport.socket.nio package. ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramFilterChain.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramFilterChain.0000644000175000017500000000533411002320027033251 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio.support; import java.util.Queue; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.common.support.AbstractIoFilterChain; /** * An {@link IoFilterChain} for datagram transport (UDP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) */ class DatagramFilterChain extends AbstractIoFilterChain { DatagramFilterChain(IoSession parent) { super(parent); } @Override protected void doWrite(IoSession session, WriteRequest writeRequest) { DatagramSessionImpl s = (DatagramSessionImpl) session; Queue writeRequestQueue = s.getWriteRequestQueue(); // SocketIoProcessor.doFlush() will reset it after write is finished // because the buffer will be passed with messageSent event. ByteBuffer buffer = (ByteBuffer) writeRequest.getMessage(); buffer.mark(); int remaining = buffer.remaining(); if (remaining == 0) { s.increaseScheduledWriteRequests(); } else { s.increaseScheduledWriteBytes(buffer.remaining()); } writeRequestQueue.add(writeRequest); if (session.getTrafficMask().isWritable()) { s.getManagerDelegate().flushSession(s); } } @Override protected void doClose(IoSession session) { DatagramSessionImpl s = (DatagramSessionImpl) session; DatagramService manager = s.getManagerDelegate(); if (manager instanceof DatagramConnectorDelegate) { manager.closeSession(s); } else { ((DatagramAcceptorDelegate) manager).getListeners() .fireSessionDestroyed(session); session.getCloseFuture().setClosed(); } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDele0000644000175000017500000005402511002320027033336 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio.support; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionRecycler; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.BaseIoAcceptor; import org.apache.mina.common.support.IoServiceListenerSupport; import org.apache.mina.transport.socket.nio.DatagramAcceptorConfig; import org.apache.mina.transport.socket.nio.DatagramServiceConfig; import org.apache.mina.transport.socket.nio.DatagramSessionConfig; import org.apache.mina.util.NamePreservingRunnable; /** * {@link IoAcceptor} for datagram transport (UDP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 588150 $, $Date: 2007-10-25 15:20:04 +0900 (Thu, 25 Oct 2007) $ */ public class DatagramAcceptorDelegate extends BaseIoAcceptor implements IoAcceptor, DatagramService { private static final AtomicInteger nextId = new AtomicInteger(); private final Object lock = new Object(); private final IoAcceptor wrapper; private final Executor executor; private final int id = nextId.getAndIncrement(); private volatile Selector selector; private DatagramAcceptorConfig defaultConfig = new DatagramAcceptorConfig(); private final Map channels = new ConcurrentHashMap(); private final Queue registerQueue = new ConcurrentLinkedQueue(); private final Queue cancelQueue = new ConcurrentLinkedQueue(); private final Queue flushingSessions = new ConcurrentLinkedQueue(); private Worker worker; /** * Creates a new instance. */ public DatagramAcceptorDelegate(IoAcceptor wrapper, Executor executor) { this.wrapper = wrapper; this.executor = executor; // The default reuseAddress of an accepted socket should be 'true'. defaultConfig.getSessionConfig().setReuseAddress(true); } public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException { if (handler == null) throw new NullPointerException("handler"); if (config == null) { config = getDefaultConfig(); } if (address != null && !(address instanceof InetSocketAddress)) throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); RegistrationRequest request = new RegistrationRequest(address, handler, config); synchronized (lock) { startupWorker(); registerQueue.add(request); selector.wakeup(); } synchronized (request) { while (!request.done) { try { request.wait(); } catch (InterruptedException e) { throw new RuntimeIOException(e); } } } if (request.exception != null) { throw (IOException) new IOException("Failed to bind") .initCause(request.exception); } } public void unbind(SocketAddress address) { if (address == null) throw new NullPointerException("address"); CancellationRequest request = new CancellationRequest(address); synchronized (lock) { try { startupWorker(); } catch (IOException e) { // IOException is thrown only when Worker thread is not // running and failed to open a selector. We simply throw // IllegalArgumentException here because we can simply // conclude that nothing is bound to the selector. throw new IllegalArgumentException("Address not bound: " + address); } cancelQueue.add(request); selector.wakeup(); } synchronized (request) { while (!request.done) { try { request.wait(); } catch (InterruptedException e) { throw new RuntimeIOException(e); } } } if (request.exception != null) { throw new RuntimeException("Failed to unbind", request.exception); } } public void unbindAll() { List addresses = new ArrayList(channels .keySet()); for (SocketAddress address : addresses) { unbind(address); } } @Override public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) { if (remoteAddress == null) { throw new NullPointerException("remoteAddress"); } if (localAddress == null) { throw new NullPointerException("localAddress"); } Selector selector = this.selector; DatagramChannel ch = channels.get(localAddress); if (selector == null || ch == null) { throw new IllegalArgumentException("Unknown localAddress: " + localAddress); } SelectionKey key = ch.keyFor(selector); if (key == null) { throw new IllegalArgumentException("Unknown localAddress: " + localAddress); } RegistrationRequest req = (RegistrationRequest) key.attachment(); IoSession session; IoSessionRecycler sessionRecycler = getSessionRecycler(req); synchronized (sessionRecycler) { session = sessionRecycler.recycle(localAddress, remoteAddress); if (session != null) { return session; } // If a new session needs to be created. // Note that the local address is the service address in the // acceptor side, and I didn't call getLocalSocketAddress(). // This avoids strange cases where getLocalSocketAddress() on the // underlying socket would return an IPv6 address while the // specified service address is an IPv4 address. DatagramSessionImpl datagramSession = new DatagramSessionImpl( wrapper, this, req.config, ch, req.handler, req.address, req.address); datagramSession.setRemoteAddress(remoteAddress); datagramSession.setSelectionKey(key); getSessionRecycler(req).put(datagramSession); session = datagramSession; } try { buildFilterChain(req, session); getListeners().fireSessionCreated(session); } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); } return session; } private IoSessionRecycler getSessionRecycler(RegistrationRequest req) { IoSessionRecycler sessionRecycler; if (req.config instanceof DatagramServiceConfig) { sessionRecycler = ((DatagramServiceConfig) req.config) .getSessionRecycler(); } else { sessionRecycler = defaultConfig.getSessionRecycler(); } return sessionRecycler; } @Override public IoServiceListenerSupport getListeners() { return super.getListeners(); } private void buildFilterChain(RegistrationRequest req, IoSession session) throws Exception { this.getFilterChainBuilder().buildFilterChain(session.getFilterChain()); req.config.getFilterChainBuilder().buildFilterChain( session.getFilterChain()); req.config.getThreadModel().buildFilterChain(session.getFilterChain()); } public DatagramAcceptorConfig getDefaultConfig() { return defaultConfig; } /** * Sets the config this acceptor will use by default. * * @param defaultConfig the default config. * @throws NullPointerException if the specified value is null. */ public void setDefaultConfig(DatagramAcceptorConfig defaultConfig) { if (defaultConfig == null) { throw new NullPointerException("defaultConfig"); } this.defaultConfig = defaultConfig; } private void startupWorker() throws IOException { synchronized (lock) { if (worker == null) { selector = Selector.open(); worker = new Worker(); executor.execute( new NamePreservingRunnable(worker, "DatagramAcceptor-" + id)); } } } public void flushSession(DatagramSessionImpl session) { if (scheduleFlush(session)) { Selector selector = this.selector; if (selector != null) { selector.wakeup(); } } } public void closeSession(DatagramSessionImpl session) { } private boolean scheduleFlush(DatagramSessionImpl session) { if (session.setScheduledForFlush(true)) { flushingSessions.add(session); return true; } else { return false; } } private class Worker implements Runnable { public void run() { Selector selector = DatagramAcceptorDelegate.this.selector; for (;;) { try { int nKeys = selector.select(); registerNew(); if (nKeys > 0) { processReadySessions(selector.selectedKeys()); } flushSessions(); cancelKeys(); if (selector.keys().isEmpty()) { synchronized (lock) { if (selector.keys().isEmpty() && registerQueue.isEmpty() && cancelQueue.isEmpty()) { worker = null; try { selector.close(); } catch (IOException e) { ExceptionMonitor.getInstance() .exceptionCaught(e); } finally { DatagramAcceptorDelegate.this.selector = null; } break; } } } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } } } private void processReadySessions(Set keys) { Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); DatagramChannel ch = (DatagramChannel) key.channel(); RegistrationRequest req = (RegistrationRequest) key.attachment(); try { if (key.isReadable()) { readSession(ch, req); } if (key.isWritable()) { for (Object o : getManagedSessions(req.address)) { scheduleFlush((DatagramSessionImpl) o); } } } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); } } } private void readSession(DatagramChannel channel, RegistrationRequest req) throws Exception { ByteBuffer readBuf = ByteBuffer .allocate(((DatagramSessionConfig) req.config .getSessionConfig()).getReceiveBufferSize()); try { SocketAddress remoteAddress = channel.receive(readBuf.buf()); if (remoteAddress != null) { DatagramSessionImpl session = (DatagramSessionImpl) newSession( remoteAddress, req.address); readBuf.flip(); ByteBuffer newBuf = ByteBuffer.allocate(readBuf.limit()); newBuf.put(readBuf); newBuf.flip(); session.increaseReadBytes(newBuf.remaining()); session.getFilterChain().fireMessageReceived(session, newBuf); } } finally { readBuf.release(); } } private void flushSessions() { if (flushingSessions.size() == 0) return; for (;;) { DatagramSessionImpl session = flushingSessions.poll(); if (session == null) break; session.setScheduledForFlush(false); try { boolean flushedAll = flush(session); if (flushedAll && !session.getWriteRequestQueue().isEmpty() && !session.isScheduledForFlush()) { scheduleFlush(session); } } catch (IOException e) { session.getFilterChain().fireExceptionCaught(session, e); } } } private boolean flush(DatagramSessionImpl session) throws IOException { // Clear OP_WRITE SelectionKey key = session.getSelectionKey(); if (key == null) { scheduleFlush(session); return false; } if (!key.isValid()) { return false; } key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); DatagramChannel ch = session.getChannel(); Queue writeRequestQueue = session.getWriteRequestQueue(); int writtenBytes = 0; int maxWrittenBytes = ((DatagramSessionConfig) session.getConfig()).getSendBufferSize() << 1; try { for (;;) { WriteRequest req = writeRequestQueue.peek(); if (req == null) break; ByteBuffer buf = (ByteBuffer) req.getMessage(); if (buf.remaining() == 0) { // pop and fire event writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); continue; } SocketAddress destination = req.getDestination(); if (destination == null) { destination = session.getRemoteAddress(); } int localWrittenBytes = ch.send(buf.buf(), destination); writtenBytes += localWrittenBytes; if (localWrittenBytes == 0 || writtenBytes >= maxWrittenBytes) { // Kernel buffer is full or wrote too much key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { // pop and fire event writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); } } } finally { session.increaseWrittenBytes(writtenBytes); } return true; } private void registerNew() { if (registerQueue.isEmpty()) return; Selector selector = this.selector; for (;;) { RegistrationRequest req = registerQueue.poll(); if (req == null) break; DatagramChannel ch = null; try { ch = DatagramChannel.open(); DatagramSessionConfig cfg; if (req.config.getSessionConfig() instanceof DatagramSessionConfig) { cfg = (DatagramSessionConfig) req.config.getSessionConfig(); } else { cfg = getDefaultConfig().getSessionConfig(); } ch.socket().setReuseAddress(cfg.isReuseAddress()); ch.socket().setBroadcast(cfg.isBroadcast()); ch.socket().setReceiveBufferSize(cfg.getReceiveBufferSize()); ch.socket().setSendBufferSize(cfg.getSendBufferSize()); if (ch.socket().getTrafficClass() != cfg.getTrafficClass()) { ch.socket().setTrafficClass(cfg.getTrafficClass()); } ch.configureBlocking(false); ch.socket().bind(req.address); if (req.address == null || req.address.getPort() == 0) { req.address = (InetSocketAddress) ch.socket() .getLocalSocketAddress(); } ch.register(selector, SelectionKey.OP_READ, req); channels.put(req.address, ch); getListeners().fireServiceActivated(this, req.address, req.handler, req.config); } catch (Throwable t) { req.exception = t; } finally { synchronized (req) { req.done = true; req.notify(); } if (ch != null && req.exception != null) { try { ch.disconnect(); ch.close(); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } } } private void cancelKeys() { if (cancelQueue.isEmpty()) return; Selector selector = this.selector; for (;;) { CancellationRequest request = cancelQueue.poll(); if (request == null) { break; } DatagramChannel ch = channels.remove(request.address); // close the channel try { if (ch == null) { request.exception = new IllegalArgumentException( "Address not bound: " + request.address); } else { SelectionKey key = ch.keyFor(selector); request.registrationRequest = (RegistrationRequest) key .attachment(); key.cancel(); selector.wakeup(); // wake up again to trigger thread death ch.disconnect(); ch.close(); } } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); } finally { synchronized (request) { request.done = true; request.notify(); } if (request.exception == null) { getListeners().fireServiceDeactivated(this, request.address, request.registrationRequest.handler, request.registrationRequest.config); } } } } public void updateTrafficMask(DatagramSessionImpl session) { // There's no point in changing the traffic mask for sessions originating // from this acceptor since new sessions are created every time data is // received. } private static class RegistrationRequest { private InetSocketAddress address; private final IoHandler handler; private final IoServiceConfig config; private Throwable exception; private boolean done; private RegistrationRequest(SocketAddress address, IoHandler handler, IoServiceConfig config) { this.address = (InetSocketAddress) address; this.handler = handler; this.config = config; } } private static class CancellationRequest { private final SocketAddress address; private boolean done; private RegistrationRequest registrationRequest; private RuntimeException exception; private CancellationRequest(SocketAddress address) { this.address = address; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDel0000644000175000017500000005023411002320027033361 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio.support; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionRecycler; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.AbstractIoFilterChain; import org.apache.mina.common.support.BaseIoConnector; import org.apache.mina.common.support.DefaultConnectFuture; import org.apache.mina.transport.socket.nio.DatagramConnectorConfig; import org.apache.mina.transport.socket.nio.DatagramServiceConfig; import org.apache.mina.transport.socket.nio.DatagramSessionConfig; import org.apache.mina.util.NamePreservingRunnable; /** * {@link IoConnector} for datagram transport (UDP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 588150 $, $Date: 2007-10-25 15:20:04 +0900 (Thu, 25 Oct 2007) $ */ public class DatagramConnectorDelegate extends BaseIoConnector implements DatagramService { private static final AtomicInteger nextId = new AtomicInteger(); private final Object lock = new Object(); private final IoConnector wrapper; private final Executor executor; private final int id = nextId.getAndIncrement(); private volatile Selector selector; private DatagramConnectorConfig defaultConfig = new DatagramConnectorConfig(); private final Queue registerQueue = new ConcurrentLinkedQueue(); private final Queue cancelQueue = new ConcurrentLinkedQueue(); private final Queue flushingSessions = new ConcurrentLinkedQueue(); private final Queue trafficControllingSessions = new ConcurrentLinkedQueue(); private Worker worker; /** * Creates a new instance. */ public DatagramConnectorDelegate(IoConnector wrapper, Executor executor) { this.wrapper = wrapper; this.executor = executor; } public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config) { return connect(address, null, handler, config); } public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config) { if (address == null) throw new NullPointerException("address"); if (handler == null) throw new NullPointerException("handler"); if (!(address instanceof InetSocketAddress)) throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); if (localAddress != null && !(localAddress instanceof InetSocketAddress)) { throw new IllegalArgumentException( "Unexpected local address type: " + localAddress.getClass()); } if (config == null) { config = getDefaultConfig(); } DatagramChannel ch = null; boolean initialized = false; try { ch = DatagramChannel.open(); DatagramSessionConfig cfg; if (config.getSessionConfig() instanceof DatagramSessionConfig) { cfg = (DatagramSessionConfig) config.getSessionConfig(); } else { cfg = getDefaultConfig().getSessionConfig(); } ch.socket().setReuseAddress(cfg.isReuseAddress()); ch.socket().setBroadcast(cfg.isBroadcast()); ch.socket().setReceiveBufferSize(cfg.getReceiveBufferSize()); ch.socket().setSendBufferSize(cfg.getSendBufferSize()); if (ch.socket().getTrafficClass() != cfg.getTrafficClass()) { ch.socket().setTrafficClass(cfg.getTrafficClass()); } if (localAddress != null) { ch.socket().bind(localAddress); } ch.connect(address); ch.configureBlocking(false); initialized = true; } catch (IOException e) { return DefaultConnectFuture.newFailedFuture(e); } finally { if (!initialized && ch != null) { try { ch.disconnect(); ch.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } RegistrationRequest request = new RegistrationRequest(ch, handler, config); synchronized (lock) { try { startupWorker(); } catch (IOException e) { try { ch.disconnect(); ch.close(); } catch (IOException e2) { ExceptionMonitor.getInstance().exceptionCaught(e2); } return DefaultConnectFuture.newFailedFuture(e); } registerQueue.add(request); selector.wakeup(); } return request; } public DatagramConnectorConfig getDefaultConfig() { return defaultConfig; } /** * Sets the config this connector will use by default. * * @param defaultConfig the default config. * @throws NullPointerException if the specified value is null. */ public void setDefaultConfig(DatagramConnectorConfig defaultConfig) { if (defaultConfig == null) { throw new NullPointerException("defaultConfig"); } this.defaultConfig = defaultConfig; } private void startupWorker() throws IOException { synchronized (lock) { if (worker == null) { selector = Selector.open(); worker = new Worker(); executor.execute( new NamePreservingRunnable(worker, "DatagramConnector-" + id)); } } } public void closeSession(DatagramSessionImpl session) { synchronized (lock) { try { startupWorker(); } catch (IOException e) { // IOException is thrown only when Worker thread is not // running and failed to open a selector. We simply return // silently here because it we can simply conclude that // this session is not managed by this connector or // already closed. return; } cancelQueue.add(session); selector.wakeup(); } } public void flushSession(DatagramSessionImpl session) { if (scheduleFlush(session)) { Selector selector = this.selector; if (selector != null) { selector.wakeup(); } } } private boolean scheduleFlush(DatagramSessionImpl session) { if (session.setScheduledForFlush(true)) { flushingSessions.add(session); return true; } else { return false; } } public void updateTrafficMask(DatagramSessionImpl session) { scheduleTrafficControl(session); Selector selector = this.selector; if (selector != null) { selector.wakeup(); } } private void scheduleTrafficControl(DatagramSessionImpl session) { trafficControllingSessions.add(session); } private void doUpdateTrafficMask() { if (trafficControllingSessions.isEmpty()) return; for (;;) { DatagramSessionImpl session = trafficControllingSessions.poll(); if (session == null) break; SelectionKey key = session.getSelectionKey(); // Retry later if session is not yet fully initialized. // (In case that Session.suspend??() or session.resume??() is // called before addSession() is processed) if (key == null) { scheduleTrafficControl(session); break; } // skip if channel is already closed if (!key.isValid()) { continue; } // The normal is OP_READ and, if there are write requests in the // session's write queue, set OP_WRITE to trigger flushing. int ops = SelectionKey.OP_READ; if (!session.getWriteRequestQueue().isEmpty()) { ops |= SelectionKey.OP_WRITE; } // Now mask the preferred ops with the mask of the current session int mask = session.getTrafficMask().getInterestOps(); key.interestOps(ops & mask); } } private class Worker implements Runnable { public void run() { Selector selector = DatagramConnectorDelegate.this.selector; for (;;) { try { int nKeys = selector.select(); registerNew(); doUpdateTrafficMask(); if (nKeys > 0) { processReadySessions(selector.selectedKeys()); } flushSessions(); cancelKeys(); if (selector.keys().isEmpty()) { synchronized (lock) { if (selector.keys().isEmpty() && registerQueue.isEmpty() && cancelQueue.isEmpty()) { worker = null; try { selector.close(); } catch (IOException e) { ExceptionMonitor.getInstance() .exceptionCaught(e); } finally { DatagramConnectorDelegate.this.selector = null; } break; } } } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } } } private void processReadySessions(Set keys) { Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); DatagramSessionImpl session = (DatagramSessionImpl) key .attachment(); // Let the recycler know that the session is still active. getSessionRecycler(session).recycle(session.getLocalAddress(), session.getRemoteAddress()); if (key.isReadable() && session.getTrafficMask().isReadable()) { readSession(session); } if (key.isWritable() && session.getTrafficMask().isWritable()) { scheduleFlush(session); } } } private IoSessionRecycler getSessionRecycler(IoSession session) { IoServiceConfig config = session.getServiceConfig(); IoSessionRecycler sessionRecycler; if (config instanceof DatagramServiceConfig) { sessionRecycler = ((DatagramServiceConfig) config) .getSessionRecycler(); } else { sessionRecycler = defaultConfig.getSessionRecycler(); } return sessionRecycler; } private void readSession(DatagramSessionImpl session) { ByteBuffer readBuf = ByteBuffer.allocate(session.getReadBufferSize()); try { int readBytes = session.getChannel().read(readBuf.buf()); if (readBytes > 0) { readBuf.flip(); ByteBuffer newBuf = ByteBuffer.allocate(readBuf.limit()); newBuf.put(readBuf); newBuf.flip(); session.increaseReadBytes(readBytes); session.getFilterChain().fireMessageReceived(session, newBuf); } } catch (IOException e) { session.getFilterChain().fireExceptionCaught(session, e); } finally { readBuf.release(); } } private void flushSessions() { if (flushingSessions.size() == 0) return; for (;;) { DatagramSessionImpl session = flushingSessions.poll(); if (session == null) break; session.setScheduledForFlush(false); try { boolean flushedAll = flush(session); if (flushedAll && !session.getWriteRequestQueue().isEmpty() && !session.isScheduledForFlush()) { scheduleFlush(session); } } catch (IOException e) { session.getFilterChain().fireExceptionCaught(session, e); } } } private boolean flush(DatagramSessionImpl session) throws IOException { // Clear OP_WRITE SelectionKey key = session.getSelectionKey(); if (key == null) { scheduleFlush(session); return false; } if (!key.isValid()) { return false; } key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); DatagramChannel ch = session.getChannel(); Queue writeRequestQueue = session.getWriteRequestQueue(); int writtenBytes = 0; int maxWrittenBytes = ((DatagramSessionConfig) session.getConfig()).getSendBufferSize() << 1; try { for (;;) { WriteRequest req = writeRequestQueue.peek(); if (req == null) break; ByteBuffer buf = (ByteBuffer) req.getMessage(); if (buf.remaining() == 0) { // pop and fire event writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); continue; } int localWrittenBytes = ch.write(buf.buf()); writtenBytes += localWrittenBytes; if (localWrittenBytes == 0 || writtenBytes >= maxWrittenBytes) { // Kernel buffer is full or wrote too much key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); // pop and fire event writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); } } } finally { session.increaseWrittenBytes(writtenBytes); } return true; } private void registerNew() { if (registerQueue.isEmpty()) return; Selector selector = this.selector; for (;;) { RegistrationRequest req = registerQueue.poll(); if (req == null) break; DatagramSessionImpl session = new DatagramSessionImpl(wrapper, this, req.config, req.channel, req.handler, req.channel .socket().getRemoteSocketAddress(), req.channel .socket().getLocalSocketAddress()); // AbstractIoFilterChain will notify the connect future. session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE, req); boolean success = false; try { SelectionKey key = req.channel.register(selector, SelectionKey.OP_READ, session); session.setSelectionKey(key); buildFilterChain(req, session); getSessionRecycler(session).put(session); // The CONNECT_FUTURE attribute is cleared and notified here. getListeners().fireSessionCreated(session); success = true; } catch (Throwable t) { // The CONNECT_FUTURE attribute is cleared and notified here. session.getFilterChain().fireExceptionCaught(session, t); } finally { if (!success) { try { req.channel.disconnect(); req.channel.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } } } private void buildFilterChain(RegistrationRequest req, IoSession session) throws Exception { getFilterChainBuilder().buildFilterChain(session.getFilterChain()); req.config.getFilterChainBuilder().buildFilterChain( session.getFilterChain()); req.config.getThreadModel().buildFilterChain(session.getFilterChain()); } private void cancelKeys() { if (cancelQueue.isEmpty()) return; Selector selector = this.selector; for (;;) { DatagramSessionImpl session = cancelQueue.poll(); if (session == null) break; else { SelectionKey key = session.getSelectionKey(); DatagramChannel ch = (DatagramChannel) key.channel(); try { ch.disconnect(); ch.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } getListeners().fireSessionDestroyed(session); session.getCloseFuture().setClosed(); key.cancel(); selector.wakeup(); // wake up again to trigger thread death } } } private static class RegistrationRequest extends DefaultConnectFuture { private final DatagramChannel channel; private final IoHandler handler; private final IoServiceConfig config; private RegistrationRequest(DatagramChannel channel, IoHandler handler, IoServiceConfig config) { this.channel = channel; this.handler = handler; this.config = config; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionConfigImpl.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionConfi0000644000175000017500000001350311002320027033402 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio.support; import java.net.DatagramSocket; import java.net.SocketException; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.transport.socket.nio.DatagramSessionConfig; /** * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DatagramSessionConfigImpl extends BaseIoSessionConfig implements DatagramSessionConfig { private static boolean SET_RECEIVE_BUFFER_SIZE_AVAILABLE = false; private static boolean SET_SEND_BUFFER_SIZE_AVAILABLE = false; private static boolean GET_TRAFFIC_CLASS_AVAILABLE = false; private static boolean SET_TRAFFIC_CLASS_AVAILABLE = false; private static boolean DEFAULT_BROADCAST = false; private static boolean DEFAULT_REUSE_ADDRESS = false; private static int DEFAULT_RECEIVE_BUFFER_SIZE = 1024; private static int DEFAULT_SEND_BUFFER_SIZE = 1024; private static int DEFAULT_TRAFFIC_CLASS = 0; static { initialize(); } private static void initialize() { DatagramSocket socket = null; try { socket = new DatagramSocket(); DEFAULT_BROADCAST = socket.getBroadcast(); DEFAULT_REUSE_ADDRESS = socket.getReuseAddress(); DEFAULT_RECEIVE_BUFFER_SIZE = socket.getReceiveBufferSize(); DEFAULT_SEND_BUFFER_SIZE = socket.getSendBufferSize(); // Check if setReceiveBufferSize is supported. try { socket.setReceiveBufferSize(DEFAULT_RECEIVE_BUFFER_SIZE); SET_RECEIVE_BUFFER_SIZE_AVAILABLE = true; } catch (SocketException e) { SET_RECEIVE_BUFFER_SIZE_AVAILABLE = false; } // Check if setSendBufferSize is supported. try { socket.setSendBufferSize(DEFAULT_SEND_BUFFER_SIZE); SET_SEND_BUFFER_SIZE_AVAILABLE = true; } catch (SocketException e) { SET_SEND_BUFFER_SIZE_AVAILABLE = false; } // Check if getTrafficClass is supported. try { DEFAULT_TRAFFIC_CLASS = socket.getTrafficClass(); GET_TRAFFIC_CLASS_AVAILABLE = true; } catch (SocketException e) { GET_TRAFFIC_CLASS_AVAILABLE = false; DEFAULT_TRAFFIC_CLASS = 0; } } catch (SocketException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } finally { if (socket != null) { socket.close(); } } } public static boolean isSetReceiveBufferSizeAvailable() { return SET_RECEIVE_BUFFER_SIZE_AVAILABLE; } public static boolean isSetSendBufferSizeAvailable() { return SET_SEND_BUFFER_SIZE_AVAILABLE; } public static boolean isGetTrafficClassAvailable() { return GET_TRAFFIC_CLASS_AVAILABLE; } public static boolean isSetTrafficClassAvailable() { return SET_TRAFFIC_CLASS_AVAILABLE; } private boolean broadcast = DEFAULT_BROADCAST; private boolean reuseAddress = DEFAULT_REUSE_ADDRESS; private int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE; private int sendBufferSize = DEFAULT_SEND_BUFFER_SIZE; private int trafficClass = DEFAULT_TRAFFIC_CLASS; /** * Creates a new instance. */ public DatagramSessionConfigImpl() { } /** * @see DatagramSocket#getBroadcast() */ public boolean isBroadcast() { return broadcast; } /** * @see DatagramSocket#setBroadcast(boolean) */ public void setBroadcast(boolean broadcast) { this.broadcast = broadcast; } /** * @see DatagramSocket#getReuseAddress() */ public boolean isReuseAddress() { return reuseAddress; } /** * @see DatagramSocket#setReuseAddress(boolean) */ public void setReuseAddress(boolean reuseAddress) { this.reuseAddress = reuseAddress; } /** * @see DatagramSocket#getReceiveBufferSize() */ public int getReceiveBufferSize() { return receiveBufferSize; } /** * @see DatagramSocket#setReceiveBufferSize(int) */ public void setReceiveBufferSize(int receiveBufferSize) { this.receiveBufferSize = receiveBufferSize; } /** * @see DatagramSocket#getSendBufferSize() */ public int getSendBufferSize() { return sendBufferSize; } /** * @see DatagramSocket#setSendBufferSize(int) */ public void setSendBufferSize(int sendBufferSize) { this.sendBufferSize = sendBufferSize; } /** * @see DatagramSocket#getTrafficClass() */ public int getTrafficClass() { return trafficClass; } /** * @see DatagramSocket#setTrafficClass(int) */ public void setTrafficClass(int trafficClass) { this.trafficClass = trafficClass; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramServiceConfig.java0000644000175000017500000000323111002320027032727 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSessionRecycler; /** * An {@link IoServiceConfig} for {@link DatagramAcceptor} and {@link DatagramConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface DatagramServiceConfig extends IoServiceConfig { DatagramSessionConfig getSessionConfig(); /** * Returns the {@link IoSessionRecycler} for this service. */ IoSessionRecycler getSessionRecycler(); /** * Sets the {@link IoSessionRecycler} for this service. * * @param sessionRecycler null to use the default recycler */ void setSessionRecycler(IoSessionRecycler sessionRecycler); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketIoProcessor.java0000644000175000017500000004375011002320027032172 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteTimeoutException; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.util.NamePreservingRunnable; /** * Performs all I/O operations for sockets which is connected or bound. This class is used by MINA internally. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 592224 $, $Date: 2007-11-06 11:11:40 +0900 (Tue, 06 Nov 2007) $, */ class SocketIoProcessor { /** * The maximum loop count for a write operation until * {@link #write(IoSession, IoBuffer)} returns non-zero value. * It is similar to what a spin lock is for in concurrency programming. * It improves memory utilization and write throughput significantly. */ private static final int WRITE_SPIN_COUNT = 256; private final Object lock = new Object(); private final String threadName; private final Executor executor; private volatile Selector selector; private final Queue newSessions = new ConcurrentLinkedQueue(); private final Queue removingSessions = new ConcurrentLinkedQueue(); private final Queue flushingSessions = new ConcurrentLinkedQueue(); private final Queue trafficControllingSessions = new ConcurrentLinkedQueue(); private Worker worker; private long lastIdleCheckTime = System.currentTimeMillis(); SocketIoProcessor(String threadName, Executor executor) { this.threadName = threadName; this.executor = executor; } void addNew(SocketSessionImpl session) throws IOException { newSessions.add(session); startupWorker(); } void remove(SocketSessionImpl session) throws IOException { scheduleRemove(session); startupWorker(); } private void startupWorker() throws IOException { synchronized (lock) { if (worker == null) { selector = Selector.open(); worker = new Worker(); executor.execute(new NamePreservingRunnable(worker, threadName)); } selector.wakeup(); } } void flush(SocketSessionImpl session) { if ( scheduleFlush(session) ) { Selector selector = this.selector; if (selector != null) { selector.wakeup(); } } } void updateTrafficMask(SocketSessionImpl session) { scheduleTrafficControl(session); Selector selector = this.selector; if (selector != null) { selector.wakeup(); } } private void scheduleRemove(SocketSessionImpl session) { removingSessions.add(session); } private boolean scheduleFlush(SocketSessionImpl session) { if (session.setScheduledForFlush(true)) { flushingSessions.add(session); return true; } return false; } private void scheduleTrafficControl(SocketSessionImpl session) { trafficControllingSessions.add(session); } private void doAddNew() { Selector selector = this.selector; for (;;) { SocketSessionImpl session = newSessions.poll(); if (session == null) break; SocketChannel ch = session.getChannel(); try { ch.configureBlocking(false); session.setSelectionKey(ch.register(selector, SelectionKey.OP_READ, session)); // AbstractIoFilterChain.CONNECT_FUTURE is cleared inside here // in AbstractIoFilterChain.fireSessionOpened(). session.getServiceListeners().fireSessionCreated(session); } catch (IOException e) { // Clear the AbstractIoFilterChain.CONNECT_FUTURE attribute // and call ConnectFuture.setException(). session.getFilterChain().fireExceptionCaught(session, e); } } } private void doRemove() { for (;;) { SocketSessionImpl session = removingSessions.poll(); if (session == null) break; SocketChannel ch = session.getChannel(); SelectionKey key = session.getSelectionKey(); // Retry later if session is not yet fully initialized. // (In case that Session.close() is called before addSession() is processed) if (key == null) { scheduleRemove(session); break; } // skip if channel is already closed if (!key.isValid()) { continue; } try { key.cancel(); ch.close(); } catch (IOException e) { session.getFilterChain().fireExceptionCaught(session, e); } finally { releaseWriteBuffers(session); session.getServiceListeners().fireSessionDestroyed(session); } } } private void process(Set selectedKeys) { for (SelectionKey key : selectedKeys) { SocketSessionImpl session = (SocketSessionImpl) key.attachment(); if (key.isReadable() && session.getTrafficMask().isReadable()) { read(session); } if (key.isWritable() && session.getTrafficMask().isWritable()) { scheduleFlush(session); } } selectedKeys.clear(); } private void read(SocketSessionImpl session) { ByteBuffer buf = ByteBuffer.allocate(session.getReadBufferSize()); SocketChannel ch = session.getChannel(); try { int readBytes = 0; int ret; try { while ((ret = ch.read(buf.buf())) > 0) { readBytes += ret; } } finally { buf.flip(); } session.increaseReadBytes(readBytes); if (readBytes > 0) { session.getFilterChain().fireMessageReceived(session, buf); buf = null; if (readBytes * 2 < session.getReadBufferSize()) { session.decreaseReadBufferSize(); } else if (readBytes == session.getReadBufferSize()) { session.increaseReadBufferSize(); } } if (ret < 0) { scheduleRemove(session); } } catch (Throwable e) { if (e instanceof IOException) scheduleRemove(session); session.getFilterChain().fireExceptionCaught(session, e); } finally { if (buf != null) buf.release(); } } private void notifyIdleness() { // process idle sessions long currentTime = System.currentTimeMillis(); if ((currentTime - lastIdleCheckTime) >= 1000) { lastIdleCheckTime = currentTime; Set keys = selector.keys(); if (keys != null) { for (SelectionKey key : keys) { SocketSessionImpl session = (SocketSessionImpl) key .attachment(); notifyIdleness(session, currentTime); } } } } private void notifyIdleness(SocketSessionImpl session, long currentTime) { notifyIdleness0(session, currentTime, session .getIdleTimeInMillis(IdleStatus.BOTH_IDLE), IdleStatus.BOTH_IDLE, Math.max(session.getLastIoTime(), session .getLastIdleTime(IdleStatus.BOTH_IDLE))); notifyIdleness0(session, currentTime, session .getIdleTimeInMillis(IdleStatus.READER_IDLE), IdleStatus.READER_IDLE, Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE))); notifyIdleness0(session, currentTime, session .getIdleTimeInMillis(IdleStatus.WRITER_IDLE), IdleStatus.WRITER_IDLE, Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE))); notifyWriteTimeout(session, currentTime, session .getWriteTimeoutInMillis(), session.getLastWriteTime()); } private void notifyIdleness0(SocketSessionImpl session, long currentTime, long idleTime, IdleStatus status, long lastIoTime) { if (idleTime > 0 && lastIoTime != 0 && (currentTime - lastIoTime) >= idleTime) { session.increaseIdleCount(status); session.getFilterChain().fireSessionIdle(session, status); } } private void notifyWriteTimeout(SocketSessionImpl session, long currentTime, long writeTimeout, long lastIoTime) { SelectionKey key = session.getSelectionKey(); if (writeTimeout > 0 && (currentTime - lastIoTime) >= writeTimeout && key != null && key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0) { session.getFilterChain().fireExceptionCaught(session, new WriteTimeoutException()); } } private void doFlush() { for (;;) { SocketSessionImpl session = flushingSessions.poll(); if (session == null) break; session.setScheduledForFlush(false); if (!session.isConnected()) { releaseWriteBuffers(session); continue; } SelectionKey key = session.getSelectionKey(); // Retry later if session is not yet fully initialized. // (In case that Session.write() is called before addSession() is processed) if (key == null) { scheduleFlush(session); break; } // Skip if the channel is already closed. if (!key.isValid()) { continue; } try { boolean flushedAll = doFlush(session); if( flushedAll && !session.getWriteRequestQueue().isEmpty() && !session.isScheduledForFlush()) { scheduleFlush( session ); } } catch (IOException e) { scheduleRemove(session); session.getFilterChain().fireExceptionCaught(session, e); } } } private void releaseWriteBuffers(SocketSessionImpl session) { Queue writeRequestQueue = session.getWriteRequestQueue(); WriteRequest req; if ((req = writeRequestQueue.poll()) != null) { ByteBuffer buf = (ByteBuffer) req.getMessage(); try { buf.release(); } catch (IllegalStateException e) { session.getFilterChain().fireExceptionCaught(session, e); } finally { // The first unwritten empty buffer must be // forwarded to the filter chain. if (buf.hasRemaining()) { req.getFuture().setWritten(false); } else { session.getFilterChain().fireMessageSent(session, req); } } // Discard others. while ((req = writeRequestQueue.poll()) != null) { try { ((ByteBuffer) req.getMessage()).release(); } catch (IllegalStateException e) { session.getFilterChain().fireExceptionCaught(session, e); } finally { req.getFuture().setWritten(false); } } } } private boolean doFlush(SocketSessionImpl session) throws IOException { SocketChannel ch = session.getChannel(); if (!ch.isConnected()) { scheduleRemove(session); return false; } // Clear OP_WRITE SelectionKey key = session.getSelectionKey(); key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); Queue writeRequestQueue = session.getWriteRequestQueue(); int writtenBytes = 0; int maxWrittenBytes = ((SocketSessionConfig) session.getConfig()).getSendBufferSize() << 1; try { for (;;) { WriteRequest req = writeRequestQueue.peek(); if (req == null) break; ByteBuffer buf = (ByteBuffer) req.getMessage(); if (buf.remaining() == 0) { writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); continue; } int localWrittenBytes = 0; for (int i = WRITE_SPIN_COUNT; i > 0; i --) { localWrittenBytes = ch.write(buf.buf()); if (localWrittenBytes != 0 || !buf.hasRemaining()) { break; } } writtenBytes += localWrittenBytes; if (localWrittenBytes == 0 || writtenBytes >= maxWrittenBytes) { // Kernel buffer is full or wrote too much. key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } } } finally { session.increaseWrittenBytes(writtenBytes); } return true; } private void doUpdateTrafficMask() { if (trafficControllingSessions.isEmpty()) return; for (;;) { SocketSessionImpl session = trafficControllingSessions.poll(); if (session == null) break; SelectionKey key = session.getSelectionKey(); // Retry later if session is not yet fully initialized. // (In case that Session.suspend??() or session.resume??() is // called before addSession() is processed) if (key == null) { scheduleTrafficControl(session); break; } // skip if channel is already closed if (!key.isValid()) { continue; } // The normal is OP_READ and, if there are write requests in the // session's write queue, set OP_WRITE to trigger flushing. int ops = SelectionKey.OP_READ; Queue writeRequestQueue = session .getWriteRequestQueue(); synchronized (writeRequestQueue) { if (!writeRequestQueue.isEmpty()) { ops |= SelectionKey.OP_WRITE; } } // Now mask the preferred ops with the mask of the current session int mask = session.getTrafficMask().getInterestOps(); key.interestOps(ops & mask); } } private class Worker implements Runnable { public void run() { Selector selector = SocketIoProcessor.this.selector; for (;;) { try { int nKeys = selector.select(1000); doAddNew(); doUpdateTrafficMask(); if (nKeys > 0) { process(selector.selectedKeys()); } doFlush(); doRemove(); notifyIdleness(); if (selector.keys().isEmpty()) { synchronized (lock) { if (selector.keys().isEmpty() && newSessions.isEmpty()) { worker = null; try { selector.close(); } catch (IOException e) { ExceptionMonitor.getInstance() .exceptionCaught(e); } finally { selector = null; } break; } } } } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/DatagramConnector.java0000644000175000017500000000447111002320027032142 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.util.concurrent.Executor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.support.DelegatedIoConnector; import org.apache.mina.transport.socket.nio.support.DatagramConnectorDelegate; import org.apache.mina.util.NewThreadExecutor; /** * {@link IoConnector} for datagram transport (UDP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class DatagramConnector extends DelegatedIoConnector { /** * Creates a new instance using a NewThreadExecutor */ public DatagramConnector() { init(new DatagramConnectorDelegate(this, new NewThreadExecutor())); } /** * Creates a new instance. * * @param executor Executor to use for launching threads */ public DatagramConnector(Executor executor) { init(new DatagramConnectorDelegate(this, executor)); } @Override public DatagramConnectorConfig getDefaultConfig() { return (DatagramConnectorConfig) super.getDefaultConfig(); } /** * Sets the default config this connector should use. * * @param defaultConfig the default config. * @throws NullPointerException if the specified value is null. */ public void setDefaultConfig(DatagramConnectorConfig defaultConfig) { ((DatagramConnectorDelegate) delegate).setDefaultConfig(defaultConfig); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/transport/socket/nio/SocketConnector.java0000644000175000017500000003614611002320027031656 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoConnectorConfig; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.support.AbstractIoFilterChain; import org.apache.mina.common.support.BaseIoConnector; import org.apache.mina.common.support.DefaultConnectFuture; import org.apache.mina.util.NamePreservingRunnable; import org.apache.mina.util.NewThreadExecutor; /** * {@link IoConnector} for socket transport (TCP/IP). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 389042 $, $Date: 2006-03-27 07:49:41Z $ */ public class SocketConnector extends BaseIoConnector { private static final AtomicInteger nextId = new AtomicInteger(); private final Object lock = new Object(); private final int id = nextId.getAndIncrement(); private final String threadName = "SocketConnector-" + id; private SocketConnectorConfig defaultConfig = new SocketConnectorConfig(); private final Queue connectQueue = new ConcurrentLinkedQueue(); private final SocketIoProcessor[] ioProcessors; private final int processorCount; private final Executor executor; private volatile Selector selector; private Worker worker; private int processorDistributor = 0; private int workerTimeout = 60; // 1 min. /** * Create a connector with a single processing thread using a NewThreadExecutor */ public SocketConnector() { this(1, new NewThreadExecutor()); } /** * Create a connector with the desired number of processing threads * * @param processorCount Number of processing threads * @param executor Executor to use for launching threads */ public SocketConnector(int processorCount, Executor executor) { if (processorCount < 1) { throw new IllegalArgumentException( "Must have at least one processor"); } this.executor = executor; this.processorCount = processorCount; ioProcessors = new SocketIoProcessor[processorCount]; for (int i = 0; i < processorCount; i++) { ioProcessors[i] = new SocketIoProcessor( "SocketConnectorIoProcessor-" + id + "." + i, executor); } } /** * How many seconds to keep the connection thread alive between connection requests * * @return the number of seconds to keep connection thread alive. * 0 means that the connection thread will terminate immediately * when there's no connection to make. */ public int getWorkerTimeout() { return workerTimeout; } /** * Set how many seconds the connection worker thread should remain alive once idle before terminating itself. * * @param workerTimeout the number of seconds to keep thread alive. * Must be >=0. If 0 is specified, the connection * worker thread will terminate immediately when * there's no connection to make. */ public void setWorkerTimeout(int workerTimeout) { if (workerTimeout < 0) { throw new IllegalArgumentException("Must be >= 0"); } this.workerTimeout = workerTimeout; } public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config) { return connect(address, null, handler, config); } public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config) { if (address == null) { throw new NullPointerException("address"); } if (handler == null) { throw new NullPointerException("handler"); } if (!(address instanceof InetSocketAddress)) { throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); } if (localAddress != null && !(localAddress instanceof InetSocketAddress)) { throw new IllegalArgumentException( "Unexpected local address type: " + localAddress.getClass()); } if (config == null) { config = getDefaultConfig(); } SocketChannel ch = null; boolean success = false; try { ch = SocketChannel.open(); ch.socket().setReuseAddress(true); // Receive buffer size must be set BEFORE the socket is connected // in order for the TCP window to be sized accordingly if (config instanceof SocketConnectorConfig) { int receiveBufferSize = ((SocketSessionConfig) config.getSessionConfig()).getReceiveBufferSize(); if (receiveBufferSize > 65535) { ch.socket().setReceiveBufferSize(receiveBufferSize); } } if (localAddress != null) { ch.socket().bind(localAddress); } ch.configureBlocking(false); if (ch.connect(address)) { DefaultConnectFuture future = new DefaultConnectFuture(); newSession(ch, handler, config, future); success = true; return future; } success = true; } catch (IOException e) { return DefaultConnectFuture.newFailedFuture(e); } finally { if (!success && ch != null) { try { ch.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } ConnectionRequest request = new ConnectionRequest(ch, handler, config); synchronized (lock) { try { startupWorker(); } catch (IOException e) { try { ch.close(); } catch (IOException e2) { ExceptionMonitor.getInstance().exceptionCaught(e2); } return DefaultConnectFuture.newFailedFuture(e); } connectQueue.add(request); selector.wakeup(); } return request; } public SocketConnectorConfig getDefaultConfig() { return defaultConfig; } /** * Sets the config this connector will use by default. * * @param defaultConfig the default config. * @throws NullPointerException if the specified value is null. */ public void setDefaultConfig(SocketConnectorConfig defaultConfig) { if (defaultConfig == null) { throw new NullPointerException("defaultConfig"); } this.defaultConfig = defaultConfig; } private void startupWorker() throws IOException { synchronized (lock) { if (worker == null) { selector = Selector.open(); worker = new Worker(); executor.execute(new NamePreservingRunnable(worker, threadName)); } } } private void registerNew() { if (connectQueue.isEmpty()) { return; } Selector selector = this.selector; for (;;) { ConnectionRequest req = connectQueue.poll(); if (req == null) { break; } SocketChannel ch = req.channel; try { ch.register(selector, SelectionKey.OP_CONNECT, req); } catch (IOException e) { req.setException(e); try { ch.close(); } catch (IOException e2) { ExceptionMonitor.getInstance().exceptionCaught(e2); } } } } private void processSessions(Set keys) { for (SelectionKey key : keys) { if (!key.isConnectable()) { continue; } SocketChannel ch = (SocketChannel) key.channel(); ConnectionRequest entry = (ConnectionRequest) key.attachment(); boolean success = false; try { if (ch.finishConnect()) { key.cancel(); newSession(ch, entry.handler, entry.config, entry); } success = true; } catch (Throwable e) { entry.setException(e); } finally { if (!success) { key.cancel(); try { ch.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } } keys.clear(); } private void processTimedOutSessions(Set keys) { long currentTime = System.currentTimeMillis(); for (SelectionKey key : keys) { if (!key.isValid()) { continue; } ConnectionRequest entry = (ConnectionRequest) key.attachment(); if (currentTime >= entry.deadline) { entry.setException(new ConnectException()); try { key.channel().close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } finally { key.cancel(); } } } } private void newSession(SocketChannel ch, IoHandler handler, IoServiceConfig config, ConnectFuture connectFuture) throws IOException { SocketSessionImpl session = new SocketSessionImpl(this, nextProcessor(), getListeners(), config, ch, handler, ch .socket().getRemoteSocketAddress()); try { getFilterChainBuilder().buildFilterChain(session.getFilterChain()); config.getFilterChainBuilder().buildFilterChain( session.getFilterChain()); config.getThreadModel().buildFilterChain(session.getFilterChain()); } catch (Throwable e) { throw (IOException) new IOException("Failed to create a session.") .initCause(e); } // Set the ConnectFuture of the specified session, which will be // removed and notified by AbstractIoFilterChain eventually. session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE, connectFuture); // Forward the remaining process to the SocketIoProcessor. session.getIoProcessor().addNew(session); } private SocketIoProcessor nextProcessor() { if (this.processorDistributor == Integer.MAX_VALUE) { this.processorDistributor = Integer.MAX_VALUE % this.processorCount; } return ioProcessors[processorDistributor++ % processorCount]; } private class Worker implements Runnable { private long lastActive = System.currentTimeMillis(); public void run() { Selector selector = SocketConnector.this.selector; for (;;) { try { int nKeys = selector.select(1000); registerNew(); if (nKeys > 0) { processSessions(selector.selectedKeys()); } processTimedOutSessions(selector.keys()); if (selector.keys().isEmpty()) { if (System.currentTimeMillis() - lastActive > workerTimeout * 1000L) { synchronized (lock) { if (selector.keys().isEmpty() && connectQueue.isEmpty()) { worker = null; try { selector.close(); } catch (IOException e) { ExceptionMonitor.getInstance() .exceptionCaught(e); } finally { SocketConnector.this.selector = null; } break; } } } } else { lastActive = System.currentTimeMillis(); } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } } } private class ConnectionRequest extends DefaultConnectFuture { private final SocketChannel channel; private final long deadline; private final IoHandler handler; private final IoServiceConfig config; private ConnectionRequest(SocketChannel channel, IoHandler handler, IoServiceConfig config) { this.channel = channel; long timeout; if (config instanceof IoConnectorConfig) { timeout = ((IoConnectorConfig) config) .getConnectTimeoutMillis(); } else { timeout = ((IoConnectorConfig) getDefaultConfig()) .getConnectTimeoutMillis(); } this.deadline = System.currentTimeMillis() + timeout; this.handler = handler; this.config = config; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/0000755000175000017500000000000011044712500023064 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ByteBufferProxy.java0000644000175000017500000003055411002320023027022 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.io.FilterOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; /** * A {@link ByteBuffer} that wraps a buffer and proxies any operations to it. *

* You can think this class like a {@link FilterOutputStream}. All operations * are proxied by default so that you can extend this class and override existing * operations selectively. You can introduce new operations, too. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ByteBufferProxy extends ByteBuffer { /** * The buffer proxied by this proxy. */ protected ByteBuffer buf; /** * Create a new instance. * @param buf the buffer to be proxied */ protected ByteBufferProxy(ByteBuffer buf) { if (buf == null) { throw new NullPointerException("buf"); } this.buf = buf; } public void acquire() { buf.acquire(); } public void release() { buf.release(); } public boolean isDirect() { return buf.isDirect(); } public java.nio.ByteBuffer buf() { return buf.buf(); } public int capacity() { return buf.capacity(); } public int position() { return buf.position(); } public ByteBuffer position(int newPosition) { buf.position(newPosition); return this; } public int limit() { return buf.limit(); } public ByteBuffer limit(int newLimit) { buf.limit(newLimit); return this; } public ByteBuffer mark() { buf.mark(); return this; } public ByteBuffer reset() { buf.reset(); return this; } public ByteBuffer clear() { buf.clear(); return this; } public ByteBuffer sweep() { buf.sweep(); return this; } public ByteBuffer sweep(byte value) { buf.sweep(value); return this; } public ByteBuffer flip() { buf.flip(); return this; } public ByteBuffer rewind() { buf.rewind(); return this; } public int remaining() { return buf.remaining(); } public boolean hasRemaining() { return buf.hasRemaining(); } public byte get() { return buf.get(); } public short getUnsigned() { return buf.getUnsigned(); } public ByteBuffer put(byte b) { buf.put(b); return this; } public byte get(int index) { return buf.get(index); } public short getUnsigned(int index) { return buf.getUnsigned(index); } public ByteBuffer put(int index, byte b) { buf.put(index, b); return this; } public ByteBuffer get(byte[] dst, int offset, int length) { buf.get(dst, offset, length); return this; } public ByteBuffer get(byte[] dst) { buf.get(dst); return this; } public ByteBuffer put(ByteBuffer src) { buf.put(src); return this; } public ByteBuffer put(java.nio.ByteBuffer src) { buf.put(src); return this; } public ByteBuffer put(byte[] src, int offset, int length) { buf.put(src, offset, length); return this; } public ByteBuffer put(byte[] src) { buf.put(src); return this; } public ByteBuffer compact() { buf.compact(); return this; } public String toString() { return buf.toString(); } public int hashCode() { return buf.hashCode(); } public boolean equals(Object ob) { return buf.equals(ob); } public int compareTo(ByteBuffer that) { return buf.compareTo(that); } public ByteOrder order() { return buf.order(); } public ByteBuffer order(ByteOrder bo) { buf.order(bo); return this; } public char getChar() { return buf.getChar(); } public ByteBuffer putChar(char value) { buf.putChar(value); return this; } public char getChar(int index) { return buf.getChar(index); } public ByteBuffer putChar(int index, char value) { buf.putChar(index, value); return this; } public CharBuffer asCharBuffer() { return buf.asCharBuffer(); } public short getShort() { return buf.getShort(); } public int getUnsignedShort() { return buf.getUnsignedShort(); } public ByteBuffer putShort(short value) { buf.putShort(value); return this; } public short getShort(int index) { return buf.getShort(index); } public int getUnsignedShort(int index) { return buf.getUnsignedShort(index); } public ByteBuffer putShort(int index, short value) { buf.putShort(index, value); return this; } public ShortBuffer asShortBuffer() { return buf.asShortBuffer(); } public int getInt() { return buf.getInt(); } public long getUnsignedInt() { return buf.getUnsignedInt(); } public ByteBuffer putInt(int value) { buf.putInt(value); return this; } public int getInt(int index) { return buf.getInt(index); } public long getUnsignedInt(int index) { return buf.getUnsignedInt(index); } public ByteBuffer putInt(int index, int value) { buf.putInt(index, value); return this; } public IntBuffer asIntBuffer() { return buf.asIntBuffer(); } public long getLong() { return buf.getLong(); } public ByteBuffer putLong(long value) { buf.putLong(value); return this; } public long getLong(int index) { return buf.getLong(index); } public ByteBuffer putLong(int index, long value) { buf.putLong(index, value); return this; } public LongBuffer asLongBuffer() { return buf.asLongBuffer(); } public float getFloat() { return buf.getFloat(); } public ByteBuffer putFloat(float value) { buf.putFloat(value); return this; } public float getFloat(int index) { return buf.getFloat(index); } public ByteBuffer putFloat(int index, float value) { buf.putFloat(index, value); return this; } public FloatBuffer asFloatBuffer() { return buf.asFloatBuffer(); } public double getDouble() { return buf.getDouble(); } public ByteBuffer putDouble(double value) { buf.putDouble(value); return this; } public double getDouble(int index) { return buf.getDouble(index); } public ByteBuffer putDouble(int index, double value) { buf.putDouble(index, value); return this; } public DoubleBuffer asDoubleBuffer() { return buf.asDoubleBuffer(); } public String getHexDump() { return buf.getHexDump(); } public String getString(int fieldSize, CharsetDecoder decoder) throws CharacterCodingException { return buf.getString(fieldSize, decoder); } public String getString(CharsetDecoder decoder) throws CharacterCodingException { return buf.getString(decoder); } public String getPrefixedString(CharsetDecoder decoder) throws CharacterCodingException { return buf.getPrefixedString(decoder); } public String getPrefixedString(int prefixLength, CharsetDecoder decoder) throws CharacterCodingException { return buf.getPrefixedString(prefixLength, decoder); } public ByteBuffer putString(CharSequence in, int fieldSize, CharsetEncoder encoder) throws CharacterCodingException { buf.putString(in, fieldSize, encoder); return this; } public ByteBuffer putString(CharSequence in, CharsetEncoder encoder) throws CharacterCodingException { buf.putString(in, encoder); return this; } public ByteBuffer putPrefixedString(CharSequence in, CharsetEncoder encoder) throws CharacterCodingException { buf.putPrefixedString(in, encoder); return this; } public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, CharsetEncoder encoder) throws CharacterCodingException { buf.putPrefixedString(in, prefixLength, encoder); return this; } public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, int padding, CharsetEncoder encoder) throws CharacterCodingException { buf.putPrefixedString(in, prefixLength, padding, encoder); return this; } public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, int padding, byte padValue, CharsetEncoder encoder) throws CharacterCodingException { buf.putPrefixedString(in, prefixLength, padding, padValue, encoder); return this; } public ByteBuffer skip(int size) { buf.skip(size); return this; } public ByteBuffer fill(byte value, int size) { buf.fill(value, size); return this; } public ByteBuffer fillAndReset(byte value, int size) { buf.fillAndReset(value, size); return this; } public ByteBuffer fill(int size) { buf.fill(size); return this; } public ByteBuffer fillAndReset(int size) { buf.fillAndReset(size); return this; } public boolean isAutoExpand() { return buf.isAutoExpand(); } public ByteBuffer setAutoExpand(boolean autoExpand) { buf.setAutoExpand(autoExpand); return this; } public ByteBuffer expand(int pos, int expectedRemaining) { buf.expand(pos, expectedRemaining); return this; } public ByteBuffer expand(int expectedRemaining) { buf.expand(expectedRemaining); return this; } public boolean isPooled() { return buf.isPooled(); } public void setPooled(boolean pooled) { buf.setPooled(pooled); } public Object getObject() throws ClassNotFoundException { return buf.getObject(); } public Object getObject(ClassLoader classLoader) throws ClassNotFoundException { return buf.getObject(classLoader); } public ByteBuffer putObject(Object o) { buf.putObject(o); return this; } public InputStream asInputStream() { return buf.asInputStream(); } public OutputStream asOutputStream() { return buf.asOutputStream(); } public ByteBuffer duplicate() { return buf.duplicate(); } public ByteBuffer slice() { return buf.slice(); } public ByteBuffer asReadOnlyBuffer() { return buf.asReadOnlyBuffer(); } public byte[] array() { return buf.array(); } public int arrayOffset() { return buf.arrayOffset(); } public ByteBuffer capacity(int newCapacity) { buf.capacity(newCapacity); return this; } public boolean isReadOnly() { return buf.isReadOnly(); } public int markValue() { return buf.markValue(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/CloseFuture.java0000644000175000017500000000330111002320023026151 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * An {@link IoFuture} for asynchronous close requests. * *

Example

*
 * IoSession session = ...;
 * CloseFuture future = session.close();
 * // Wait until the connection is closed
 * future.join();
 * // Now connection should be closed.
 * assert future.isClosed();
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface CloseFuture extends IoFuture { /** * Returns true if the close request is finished and the session is closed. */ boolean isClosed(); /** * Marks this future as closed and notifies all threads waiting for this * future. This method is invoked by MINA internally. Please do not call * this method directly. */ void setClosed(); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoSession.java0000644000175000017500000002421211002320023025630 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; import java.util.Set; /** * A handle which represents connection between two endpoints regardless of * transport types. *

* {@link IoSession} provides user-defined attributes. User-defined attributes * are application-specific data which is associated with a session. * It often contains objects that represents the state of a higher-level protocol * and becomes a way to exchange data between filters and handlers. * *

Adjusting Transport Type Specific Properties

*

* You can simply downcast the session to an appropriate subclass. *

* *

Thread Safety

*

* {@link IoSession} is thread-safe. But please note that performing * more than one {@link #write(Object)} calls at the same time will * cause the {@link IoFilter#filterWrite(IoFilter.NextFilter, IoSession, IoFilter.WriteRequest)} * is executed simnutaneously, and therefore you have to make sure the * {@link IoFilter} implementations you're using are thread-safe, too. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoSession { /** * Returns the {@link IoService} which provides I/O service to this session. */ IoService getService(); /** * Returns the {@link IoServiceConfig} of this session. */ IoServiceConfig getServiceConfig(); /** * Returns the {@link IoHandler} which handles this session. */ IoHandler getHandler(); /** * Returns the configuration of this session. */ IoSessionConfig getConfig(); /** * Returns the filter chain that only affects this session. */ IoFilterChain getFilterChain(); /** * Writes the specified message to remote peer. This * operation is asynchronous; {@link IoHandler#messageSent(IoSession, Object)} * will be invoked when the message is actually sent to remote peer. * You can also wait for the returned {@link WriteFuture} if you want * to wait for the message actually written. */ WriteFuture write(Object message); /** * Closes this session immediately. This operation is asynthronous. * Wait for the returned {@link CloseFuture} if you want to wait for * the session actually closed. */ CloseFuture close(); /** * Returns an attachment of this session. * This method is identical with getAttribute( "" ). */ Object getAttachment(); /** * Sets an attachment of this session. * This method is identical with setAttribute( "", attachment ). * * @return Old attachment. null if it is new. */ Object setAttachment(Object attachment); /** * Returns the value of user-defined attribute of this session. * * @param key the key of the attribute * @return null if there is no attribute with the specified key */ Object getAttribute(String key); /** * Sets a user-defined attribute. * * @param key the key of the attribute * @param value the value of the attribute * @return The old value of the attribute. null if it is new. */ Object setAttribute(String key, Object value); /** * Sets a user defined attribute without a value. This is useful when * you just want to put a 'mark' attribute. Its value is set to * {@link Boolean#TRUE}. * * @param key the key of the attribute * @return The old value of the attribute. null if it is new. */ Object setAttribute(String key); /** * Removes a user-defined attribute with the specified key. * * @return The old value of the attribute. null if not found. */ Object removeAttribute(String key); /** * Returns true if this session contains the attribute with * the specified key. */ boolean containsAttribute(String key); /** * Returns the set of keys of all user-defined attributes. */ Set getAttributeKeys(); /** * Returns transport type of this session. */ TransportType getTransportType(); /** * Returns true if this session is connected with remote peer. */ boolean isConnected(); /** * Returns true if and only if this session is being closed * (but not disconnected yet) or is closed. */ boolean isClosing(); /** * Returns the {@link CloseFuture} of this session. This method returns * the same instance whenever user calls it. */ CloseFuture getCloseFuture(); /** * Returns the socket address of remote peer. */ SocketAddress getRemoteAddress(); /** * Returns the socket address of local machine which is associated with this * session. */ SocketAddress getLocalAddress(); /** * Returns the socket address of the {@link IoService} listens to to manage * this session. If this session is managed by {@link IoAcceptor}, it * returns the {@link SocketAddress} which is specified as a parameter of * {@link IoAcceptor#bind(SocketAddress, IoHandler)}. If this session is * managed by {@link IoConnector}, this method returns the same address with * that of {@link #getRemoteAddress()}. */ SocketAddress getServiceAddress(); /** * Returns idle time for the specified type of idleness in seconds. */ int getIdleTime(IdleStatus status); /** * Returns idle time for the specified type of idleness in milliseconds. */ long getIdleTimeInMillis(IdleStatus status); /** * Sets idle time for the specified type of idleness in seconds. */ void setIdleTime(IdleStatus status, int idleTime); /** * Returns write timeout in seconds. */ int getWriteTimeout(); /** * Returns write timeout in milliseconds. */ long getWriteTimeoutInMillis(); /** * Sets write timeout in seconds. */ void setWriteTimeout(int writeTimeout); /** * Returns the current {@link TrafficMask} of this session. */ TrafficMask getTrafficMask(); /** * Sets the {@link TrafficMask} of this session which will result * the parent {@link IoService} to start to control the traffic * of this session immediately. */ void setTrafficMask(TrafficMask trafficMask); /** * A shortcut method for {@link #setTrafficMask(TrafficMask)} that * suspends read operations for this session. */ void suspendRead(); /** * A shortcut method for {@link #setTrafficMask(TrafficMask)} that * suspends write operations for this session. */ void suspendWrite(); /** * A shortcut method for {@link #setTrafficMask(TrafficMask)} that * resumes read operations for this session. */ void resumeRead(); /** * A shortcut method for {@link #setTrafficMask(TrafficMask)} that * resumes write operations for this session. */ void resumeWrite(); /** * Returns the total number of bytes which were read from this session. */ long getReadBytes(); /** * Returns the total number of bytes which were written to this session. */ long getWrittenBytes(); /** * Returns the total number of messages which were read and decoded from this session. */ long getReadMessages(); /** * Returns the total number of messages which were written and encoded by this session. */ long getWrittenMessages(); /** * Returns the total number of write requests which were written to this session. */ long getWrittenWriteRequests(); /** * Returns the number of write requests which are scheduled to be written * to this session. */ int getScheduledWriteRequests(); /** * Returns the number of bytes which are scheduled to be written to this * session. */ int getScheduledWriteBytes(); /** * Returns the time in millis when this session is created. */ long getCreationTime(); /** * Returns the time in millis when I/O occurred lastly. */ long getLastIoTime(); /** * Returns the time in millis when read operation occurred lastly. */ long getLastReadTime(); /** * Returns the time in millis when write operation occurred lastly. */ long getLastWriteTime(); /** * Returns true if this session is idle for the specified * {@link IdleStatus}. */ boolean isIdle(IdleStatus status); /** * Returns the number of the fired continuous sessionIdle events * for the specified {@link IdleStatus}. *

* If sessionIdle event is fired first after some time after I/O, * idleCount becomes 1. idleCount resets to * 0 if any I/O occurs again, otherwise it increases to * 2 and so on if sessionIdle event is fired again without * any I/O between two (or more) sessionIdle events. */ int getIdleCount(IdleStatus status); /** * Returns the time in millis when the last sessionIdle event * is fired for the specified {@link IdleStatus}. */ long getLastIdleTime(IdleStatus status); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoAcceptorConfig.java0000644000175000017500000000304111002320023027070 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * A configuration which is used to configure {@link IoAcceptor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoAcceptorConfig extends IoServiceConfig { /** * Returns true if and only if all clients are disconnected * when this acceptor unbinds the related local address. */ boolean isDisconnectOnUnbind(); /** * Sets whether all clients are disconnected when this acceptor unbinds the * related local address. The default value is true. */ void setDisconnectOnUnbind(boolean disconnectOnUnbind); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ThreadModel.java0000644000175000017500000000323011002320023026102 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * Represents a thread model of an {@link IoService}. There's no essential * difference from {@link IoFilterChainBuilder}. The only difference is that * {@link ThreadModel} is executed later than the {@link IoFilterChainBuilder} * you specified. However, please don't abuse this internal behavior; it can * change. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ThreadModel extends IoFilterChainBuilder { /** * A {@link ThreadModel} which make MINA not manage a thread model at all. */ static final ThreadModel MANUAL = new ThreadModel() { public void buildFilterChain(IoFilterChain chain) throws Exception { // Do nothing. } }; } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ByteBuffer.java0000644000175000017500000014705611002320023025766 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.StreamCorruptedException; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.util.HashSet; import java.util.Set; import org.apache.mina.common.support.ByteBufferHexDumper; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /** * A byte buffer used by MINA applications. *

* This is a replacement for {@link java.nio.ByteBuffer}. Please refer to * {@link java.nio.ByteBuffer} and {@link java.nio.Buffer} documentation for * usage. MINA does not use NIO {@link java.nio.ByteBuffer} directly for two * reasons: *

    *
  • It doesn't provide useful getters and putters such as * fill, get/putString, and * get/putAsciiInt() enough.
  • *
  • It is hard to distinguish if the buffer is created from MINA buffer * pool or not. MINA have to return used buffers back to pool.
  • *
  • It is difficult to write variable-length data due to its fixed * capacity
  • *
*

* *

Allocation

*

* You can get a heap buffer from buffer pool: *

 * ByteBuffer buf = ByteBuffer.allocate(1024, false);
 * 
* you can also get a direct buffer from buffer pool: *
 * ByteBuffer buf = ByteBuffer.allocate(1024, true);
 * 
* or you can let MINA choose: *
 * ByteBuffer buf = ByteBuffer.allocate(1024);
 * 
*

* *

Acquire/Release

*

* Please note that you never need to release the allocated buffer * because MINA will release it automatically when: *

    *
  • You pass the buffer by calling {@link IoSession#write(Object)}.
  • *
  • You pass the buffer by calling {@link IoFilter.NextFilter#filterWrite(IoSession,IoFilter.WriteRequest)}.
  • *
  • You pass the buffer by calling {@link ProtocolEncoderOutput#write(ByteBuffer)}.
  • *
* And, you don't need to release any {@link ByteBuffer} which is passed as a parameter * of {@link IoHandler#messageReceived(IoSession, Object)} method. They are released * automatically when the method returns. *

* You have to release buffers manually by calling {@link #release()} when: *

    *
  • You allocated a buffer, but didn't pass the buffer to any of two methods above.
  • *
  • You called {@link #acquire()} to prevent the buffer from being released.
  • *
*

* *

Wrapping existing NIO buffers and arrays

*

* This class provides a few wrap(...) methods that wraps * any NIO buffers and byte arrays. Wrapped MINA buffers are not returned * to the buffer pool by default to prevent unexpected memory leakage by default. * In case you want to make it pooled, you can call {@link #setPooled(boolean)} * with true flag to enable pooling. * *

AutoExpand

*

* Writing variable-length data using NIO ByteBuffers is not really * easy, and it is because its size is fixed. MINA ByteBuffer * introduces autoExpand property. If autoExpand property * is true, you never get {@link BufferOverflowException} or * {@link IndexOutOfBoundsException} (except when index is negative). * It automatically expands its capacity and limit value. For example: *

 * String greeting = messageBundle.getMessage( "hello" );
 * ByteBuffer buf = ByteBuffer.allocate( 16 );
 * // Turn on autoExpand (it is off by default)
 * buf.setAutoExpand( true );
 * buf.putString( greeting, utf8encoder );
 * 
* NIO ByteBuffer is reallocated by MINA ByteBuffer behind * the scene if the encoded data is larger than 16 bytes. Its capacity and * its limit will increase to the last position the string is written. *

* *

Derived Buffers

*

* Derived buffers are the buffers which were created by * {@link #duplicate()}, {@link #slice()}, or {@link #asReadOnlyBuffer()}. * They are useful especially when you broadcast the same messages to * multiple {@link IoSession}s. Please note that the derived buffers are * neither pooled nor auto-expandable. Trying to expand a derived buffer will * raise {@link IllegalStateException}. *

* *

Changing Buffer Allocation and Management Policy

*

* MINA provides a {@link ByteBufferAllocator} interface to let you override * the default buffer management behavior. There are two allocators provided * out-of-the-box: *

    *
  • {@link PooledByteBufferAllocator} (Default)
  • *
  • {@link SimpleByteBufferAllocator}
  • *
* You can change the allocator by calling {@link #setAllocator(ByteBufferAllocator)}. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 637706 $, $Date: 2008-03-17 12:18:43 +0900 (Mon, 17 Mar 2008) $ * @noinspection StaticNonFinalField * @see ByteBufferAllocator */ public abstract class ByteBuffer implements Comparable { private static ByteBufferAllocator allocator = new PooledByteBufferAllocator(); private static boolean useDirectBuffers = true; /** * Returns the current allocator which manages the allocated buffers. */ public static ByteBufferAllocator getAllocator() { return allocator; } /** * Changes the current allocator with the specified one to manage * the allocated buffers from now. */ public static void setAllocator(ByteBufferAllocator newAllocator) { if (newAllocator == null) { throw new NullPointerException("allocator"); } ByteBufferAllocator oldAllocator = allocator; allocator = newAllocator; if (null != oldAllocator) { oldAllocator.dispose(); } } public static boolean isUseDirectBuffers() { return useDirectBuffers; } public static void setUseDirectBuffers(boolean useDirectBuffers) { ByteBuffer.useDirectBuffers = useDirectBuffers; } /** * Returns the direct or heap buffer which is capable of the specified * size. This method tries to allocate direct buffer first, and then * tries heap buffer if direct buffer memory is exhausted. Please use * {@link #allocate(int, boolean)} to allocate buffers of specific type. * * @param capacity the capacity of the buffer */ public static ByteBuffer allocate(int capacity) { if (useDirectBuffers) { try { // first try to allocate direct buffer return allocate(capacity, true); } catch (OutOfMemoryError e) { // fall through to heap buffer } } return allocate(capacity, false); } /** * Returns the buffer which is capable of the specified size. * * @param capacity the capacity of the buffer * @param direct true to get a direct buffer, * false to get a heap buffer. */ public static ByteBuffer allocate(int capacity, boolean direct) { return allocator.allocate(capacity, direct); } /** * Wraps the specified NIO {@link java.nio.ByteBuffer} into MINA buffer. */ public static ByteBuffer wrap(java.nio.ByteBuffer nioBuffer) { return allocator.wrap(nioBuffer); } /** * Wraps the specified byte array into MINA heap buffer. */ public static ByteBuffer wrap(byte[] byteArray) { return wrap(java.nio.ByteBuffer.wrap(byteArray)); } /** * Wraps the specified byte array into MINA heap buffer. * Please note that MINA buffers are going to be pooled, and * therefore there can be waste of memory if you wrap * your byte array specifying offset and length. */ public static ByteBuffer wrap(byte[] byteArray, int offset, int length) { return wrap(java.nio.ByteBuffer.wrap(byteArray, offset, length)); } private static final Set primitiveTypeNames = new HashSet(); static { primitiveTypeNames.add("void"); primitiveTypeNames.add("boolean"); primitiveTypeNames.add("byte"); primitiveTypeNames.add("char"); primitiveTypeNames.add("short"); primitiveTypeNames.add("int"); primitiveTypeNames.add("long"); primitiveTypeNames.add("float"); primitiveTypeNames.add("double"); } protected ByteBuffer() { } /** * Increases the internal reference count of this buffer to defer * automatic release. You have to invoke {@link #release()} as many * as you invoked this method to release this buffer. * * @throws IllegalStateException if you attempt to acquire already * released buffer. */ public abstract void acquire(); /** * Releases the specified buffer to buffer pool. * * @throws IllegalStateException if you attempt to release already * released buffer. */ public abstract void release(); /** * Returns the underlying NIO buffer instance. */ public abstract java.nio.ByteBuffer buf(); /** * @see java.nio.ByteBuffer#isDirect() */ public abstract boolean isDirect(); /** * @see java.nio.ByteBuffer#isReadOnly() */ public abstract boolean isReadOnly(); /** * @see java.nio.ByteBuffer#capacity() */ public abstract int capacity(); /** * Changes the capacity of this buffer. */ public abstract ByteBuffer capacity(int newCapacity); /** * Returns true if and only if autoExpand is turned on. */ public abstract boolean isAutoExpand(); /** * Turns on or off autoExpand. */ public abstract ByteBuffer setAutoExpand(boolean autoExpand); /** * Changes the capacity and limit of this buffer so this buffer get * the specified expectedRemaining room from the current position. * This method works even if you didn't set autoExpand to * true. */ public ByteBuffer expand(int expectedRemaining) { return expand(position(), expectedRemaining); } /** * Changes the capacity and limit of this buffer so this buffer get * the specified expectedRemaining room from the specified * pos. * This method works even if you didn't set autoExpand to * true. */ public abstract ByteBuffer expand(int pos, int expectedRemaining); /** * Returns true if and only if this buffer is returned back * to the buffer pool when released. *

* The default value of this property is true if and only if you * allocated this buffer using {@link #allocate(int)} or {@link #allocate(int, boolean)}, * or false otherwise. (i.e. {@link #wrap(byte[])}, {@link #wrap(byte[], int, int)}, * and {@link #wrap(java.nio.ByteBuffer)}) */ public abstract boolean isPooled(); /** * Sets whether this buffer is returned back to the buffer pool when released. *

* The default value of this property is true if and only if you * allocated this buffer using {@link #allocate(int)} or {@link #allocate(int, boolean)}, * or false otherwise. (i.e. {@link #wrap(byte[])}, {@link #wrap(byte[], int, int)}, * and {@link #wrap(java.nio.ByteBuffer)}) */ public abstract void setPooled(boolean pooled); /** * @see java.nio.Buffer#position() */ public abstract int position(); /** * @see java.nio.Buffer#position(int) */ public abstract ByteBuffer position(int newPosition); /** * @see java.nio.Buffer#limit() */ public abstract int limit(); /** * @see java.nio.Buffer#limit(int) */ public abstract ByteBuffer limit(int newLimit); /** * @see java.nio.Buffer#mark() */ public abstract ByteBuffer mark(); /** * Returns the position of the current mark. This method returns -1 if no * mark is set. */ public abstract int markValue(); /** * @see java.nio.Buffer#reset() */ public abstract ByteBuffer reset(); /** * @see java.nio.Buffer#clear() */ public abstract ByteBuffer clear(); /** * Clears this buffer and fills its content with NUL. * The position is set to zero, the limit is set to the capacity, * and the mark is discarded. */ public ByteBuffer sweep() { clear(); return fillAndReset(remaining()); } /** * Clears this buffer and fills its content with value. * The position is set to zero, the limit is set to the capacity, * and the mark is discarded. */ public ByteBuffer sweep(byte value) { clear(); return fillAndReset(value, remaining()); } /** * @see java.nio.Buffer#flip() */ public abstract ByteBuffer flip(); /** * @see java.nio.Buffer#rewind() */ public abstract ByteBuffer rewind(); /** * @see java.nio.Buffer#remaining() */ public int remaining() { return limit() - position(); } /** * @see java.nio.Buffer#hasRemaining() */ public boolean hasRemaining() { return remaining() > 0; } /** * @see java.nio.ByteBuffer#duplicate() */ public abstract ByteBuffer duplicate(); /** * @see java.nio.ByteBuffer#slice() */ public abstract ByteBuffer slice(); /** * @see java.nio.ByteBuffer#asReadOnlyBuffer() */ public abstract ByteBuffer asReadOnlyBuffer(); /** * @see java.nio.ByteBuffer#array() */ public abstract byte[] array(); /** * @see java.nio.ByteBuffer#arrayOffset() */ public abstract int arrayOffset(); /** * @see java.nio.ByteBuffer#get() */ public abstract byte get(); /** * Reads one unsigned byte as a short integer. */ public short getUnsigned() { return (short) (get() & 0xff); } /** * @see java.nio.ByteBuffer#put(byte) */ public abstract ByteBuffer put(byte b); /** * @see java.nio.ByteBuffer#get(int) */ public abstract byte get(int index); /** * Reads one byte as an unsigned short integer. */ public short getUnsigned(int index) { return (short) (get(index) & 0xff); } /** * @see java.nio.ByteBuffer#put(int, byte) */ public abstract ByteBuffer put(int index, byte b); /** * @see java.nio.ByteBuffer#get(byte[], int, int) */ public abstract ByteBuffer get(byte[] dst, int offset, int length); /** * @see java.nio.ByteBuffer#get(byte[]) */ public ByteBuffer get(byte[] dst) { return get(dst, 0, dst.length); } /** * Writes the content of the specified src into this buffer. */ public abstract ByteBuffer put(java.nio.ByteBuffer src); /** * Writes the content of the specified src into this buffer. */ public ByteBuffer put(ByteBuffer src) { return put(src.buf()); } /** * @see java.nio.ByteBuffer#put(byte[], int, int) */ public abstract ByteBuffer put(byte[] src, int offset, int length); /** * @see java.nio.ByteBuffer#put(byte[]) */ public ByteBuffer put(byte[] src) { return put(src, 0, src.length); } /** * @see java.nio.ByteBuffer#compact() */ public abstract ByteBuffer compact(); @Override public String toString() { StringBuffer buf = new StringBuffer(); if (isDirect()) { buf.append("DirectBuffer"); } else { buf.append("HeapBuffer"); } buf.append("[pos="); buf.append(position()); buf.append(" lim="); buf.append(limit()); buf.append(" cap="); buf.append(capacity()); buf.append(": "); buf.append(getHexDump()); buf.append(']'); return buf.toString(); } @Override public int hashCode() { int h = 1; int p = position(); for (int i = limit() - 1; i >= p; i--) { h = 31 * h + get(i); } return h; } @Override public boolean equals(Object o) { if (!(o instanceof ByteBuffer)) { return false; } ByteBuffer that = (ByteBuffer) o; if (this.remaining() != that.remaining()) { return false; } int p = this.position(); for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--) { byte v1 = this.get(i); byte v2 = that.get(j); if (v1 != v2) { return false; } } return true; } public int compareTo(ByteBuffer that) { int n = this.position() + Math.min(this.remaining(), that.remaining()); for (int i = this.position(), j = that.position(); i < n; i++, j++) { byte v1 = this.get(i); byte v2 = that.get(j); if (v1 == v2) { continue; } if (v1 < v2) { return -1; } return +1; } return this.remaining() - that.remaining(); } /** * @see java.nio.ByteBuffer#order() */ public abstract ByteOrder order(); /** * @see java.nio.ByteBuffer#order(ByteOrder) */ public abstract ByteBuffer order(ByteOrder bo); /** * @see java.nio.ByteBuffer#getChar() */ public abstract char getChar(); /** * @see java.nio.ByteBuffer#putChar(char) */ public abstract ByteBuffer putChar(char value); /** * @see java.nio.ByteBuffer#getChar(int) */ public abstract char getChar(int index); /** * @see java.nio.ByteBuffer#putChar(int, char) */ public abstract ByteBuffer putChar(int index, char value); /** * @see java.nio.ByteBuffer#asCharBuffer() */ public abstract CharBuffer asCharBuffer(); /** * @see java.nio.ByteBuffer#getShort() */ public abstract short getShort(); /** * Reads two bytes unsigned integer. */ public int getUnsignedShort() { return getShort() & 0xffff; } /** * @see java.nio.ByteBuffer#putShort(short) */ public abstract ByteBuffer putShort(short value); /** * @see java.nio.ByteBuffer#getShort() */ public abstract short getShort(int index); /** * Reads two bytes unsigned integer. */ public int getUnsignedShort(int index) { return getShort(index) & 0xffff; } /** * @see java.nio.ByteBuffer#putShort(int, short) */ public abstract ByteBuffer putShort(int index, short value); /** * @see java.nio.ByteBuffer#asShortBuffer() */ public abstract ShortBuffer asShortBuffer(); /** * @see java.nio.ByteBuffer#getInt() */ public abstract int getInt(); /** * Reads four bytes unsigned integer. */ public long getUnsignedInt() { return getInt() & 0xffffffffL; } /** * @see java.nio.ByteBuffer#putInt(int) */ public abstract ByteBuffer putInt(int value); /** * @see java.nio.ByteBuffer#getInt(int) */ public abstract int getInt(int index); /** * Reads four bytes unsigned integer. */ public long getUnsignedInt(int index) { return getInt(index) & 0xffffffffL; } /** * @see java.nio.ByteBuffer#putInt(int, int) */ public abstract ByteBuffer putInt(int index, int value); /** * @see java.nio.ByteBuffer#asIntBuffer() */ public abstract IntBuffer asIntBuffer(); /** * @see java.nio.ByteBuffer#getLong() */ public abstract long getLong(); /** * @see java.nio.ByteBuffer#putLong(int, long) */ public abstract ByteBuffer putLong(long value); /** * @see java.nio.ByteBuffer#getLong(int) */ public abstract long getLong(int index); /** * @see java.nio.ByteBuffer#putLong(int, long) */ public abstract ByteBuffer putLong(int index, long value); /** * @see java.nio.ByteBuffer#asLongBuffer() */ public abstract LongBuffer asLongBuffer(); /** * @see java.nio.ByteBuffer#getFloat() */ public abstract float getFloat(); /** * @see java.nio.ByteBuffer#putFloat(float) */ public abstract ByteBuffer putFloat(float value); /** * @see java.nio.ByteBuffer#getFloat(int) */ public abstract float getFloat(int index); /** * @see java.nio.ByteBuffer#putFloat(int, float) */ public abstract ByteBuffer putFloat(int index, float value); /** * @see java.nio.ByteBuffer#asFloatBuffer() */ public abstract FloatBuffer asFloatBuffer(); /** * @see java.nio.ByteBuffer#getDouble() */ public abstract double getDouble(); /** * @see java.nio.ByteBuffer#putDouble(double) */ public abstract ByteBuffer putDouble(double value); /** * @see java.nio.ByteBuffer#getDouble(int) */ public abstract double getDouble(int index); /** * @see java.nio.ByteBuffer#putDouble(int, double) */ public abstract ByteBuffer putDouble(int index, double value); /** * @see java.nio.ByteBuffer#asDoubleBuffer() */ public abstract DoubleBuffer asDoubleBuffer(); /** * Returns an {@link InputStream} that reads the data from this buffer. * {@link InputStream#read()} returns -1 if the buffer position * reaches to the limit. */ public InputStream asInputStream() { return new InputStream() { @Override public int available() { return ByteBuffer.this.remaining(); } @Override public synchronized void mark(int readlimit) { ByteBuffer.this.mark(); } @Override public boolean markSupported() { return true; } @Override public int read() { if (ByteBuffer.this.hasRemaining()) { return ByteBuffer.this.get() & 0xff; } else { return -1; } } @Override public int read(byte[] b, int off, int len) { int remaining = ByteBuffer.this.remaining(); if (remaining > 0) { int readBytes = Math.min(remaining, len); ByteBuffer.this.get(b, off, readBytes); return readBytes; } else { return -1; } } @Override public synchronized void reset() { ByteBuffer.this.reset(); } @Override public long skip(long n) { int bytes; if (n > Integer.MAX_VALUE) { bytes = ByteBuffer.this.remaining(); } else { bytes = Math.min(ByteBuffer.this.remaining(), (int) n); } ByteBuffer.this.skip(bytes); return bytes; } }; } /** * Returns an {@link OutputStream} that appends the data into this buffer. * Please note that the {@link OutputStream#write(int)} will throw a * {@link BufferOverflowException} instead of an {@link IOException} * in case of buffer overflow. Please set autoExpand property by * calling {@link #setAutoExpand(boolean)} to prevent the unexpected runtime * exception. */ public OutputStream asOutputStream() { return new OutputStream() { @Override public void write(byte[] b, int off, int len) { ByteBuffer.this.put(b, off, len); } @Override public void write(int b) { ByteBuffer.this.put((byte) b); } }; } /** * Returns hexdump of this buffer. */ public String getHexDump() { return ByteBufferHexDumper.getHexdump(this); } //////////////////////////////// // String getters and putters // //////////////////////////////// /** * Reads a NUL-terminated string from this buffer using the * specified decoder and returns it. This method reads * until the limit of this buffer if no NUL is found. */ public String getString(CharsetDecoder decoder) throws CharacterCodingException { if (!hasRemaining()) { return ""; } boolean utf16 = decoder.charset().name().startsWith("UTF-16"); int oldPos = position(); int oldLimit = limit(); int end; if (!utf16) { while (hasRemaining()) { if (get() == 0) { break; } } end = position(); if (end == oldLimit && get(end - 1) != 0) { limit(end); } else { limit(end - 1); } } else { while (remaining() >= 2) { boolean highZero = (get() == 0); boolean lowZero = (get() == 0); if (highZero && lowZero) { break; } } end = position(); if (end == oldLimit || end == oldLimit - 1) { limit(end); } else { limit(end - 2); } } position(oldPos); if (!hasRemaining()) { limit(oldLimit); position(end); return ""; } decoder.reset(); int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1; CharBuffer out = CharBuffer.allocate(expectedLength); for (;;) { CoderResult cr; if (hasRemaining()) { cr = decoder.decode(buf(), out, true); } else { cr = decoder.flush(out); } if (cr.isUnderflow()) { break; } if (cr.isOverflow()) { CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength); out.flip(); o.put(out); out = o; continue; } if (cr.isError()) { // Revert the buffer back to the previous state. limit(oldLimit); position(oldPos); cr.throwException(); } } limit(oldLimit); position(end); return out.flip().toString(); } /** * Reads a NUL-terminated string from this buffer using the * specified decoder and returns it. * * @param fieldSize the maximum number of bytes to read */ public String getString(int fieldSize, CharsetDecoder decoder) throws CharacterCodingException { checkFieldSize(fieldSize); if (fieldSize == 0) { return ""; } if (!hasRemaining()) { return ""; } boolean utf16 = decoder.charset().name().startsWith("UTF-16"); if (utf16 && ((fieldSize & 1) != 0)) { throw new IllegalArgumentException("fieldSize is not even."); } int oldPos = position(); int oldLimit = limit(); int end = position() + fieldSize; if (oldLimit < end) { throw new BufferUnderflowException(); } int i; if (!utf16) { for (i = 0; i < fieldSize; i++) { if (get() == 0) { break; } } if (i == fieldSize) { limit(end); } else { limit(position() - 1); } } else { for (i = 0; i < fieldSize; i += 2) { boolean highZero = (get() == 0); boolean lowZero = (get() == 0); if (highZero && lowZero) { break; } } if (i == fieldSize) { limit(end); } else { limit(position() - 2); } } position(oldPos); if (!hasRemaining()) { limit(oldLimit); position(end); return ""; } decoder.reset(); int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1; CharBuffer out = CharBuffer.allocate(expectedLength); for (;;) { CoderResult cr; if (hasRemaining()) { cr = decoder.decode(buf(), out, true); } else { cr = decoder.flush(out); } if (cr.isUnderflow()) { break; } if (cr.isOverflow()) { CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength); out.flip(); o.put(out); out = o; continue; } if (cr.isError()) { // Revert the buffer back to the previous state. limit(oldLimit); position(oldPos); cr.throwException(); } } limit(oldLimit); position(end); return out.flip().toString(); } /** * Writes the content of in into this buffer using the * specified encoder. This method doesn't terminate * string with NUL. You have to do it by yourself. * * @throws BufferOverflowException if the specified string doesn't fit */ public ByteBuffer putString(CharSequence val, CharsetEncoder encoder) throws CharacterCodingException { if (val.length() == 0) { return this; } CharBuffer in = CharBuffer.wrap(val); encoder.reset(); int expandedState = 0; for (;;) { CoderResult cr; if (in.hasRemaining()) { cr = encoder.encode(in, buf(), true); } else { cr = encoder.flush(buf()); } if (cr.isUnderflow()) { break; } if (cr.isOverflow()) { if (isAutoExpand()) { switch (expandedState) { case 0: autoExpand((int) Math.ceil(in.remaining() * encoder.averageBytesPerChar())); expandedState++; break; case 1: autoExpand((int) Math.ceil(in.remaining() * encoder.maxBytesPerChar())); expandedState++; break; default: throw new RuntimeException("Expanded by " + (int) Math.ceil(in.remaining() * encoder.maxBytesPerChar()) + " but that wasn't enough for '" + val + "'"); } continue; } } else { expandedState = 0; } cr.throwException(); } return this; } /** * Writes the content of in into this buffer as a * NUL-terminated string using the specified * encoder. *

* If the charset name of the encoder is UTF-16, you cannot specify * odd fieldSize, and this method will append two * NULs as a terminator. *

* Please note that this method doesn't terminate with NUL * if the input string is longer than fieldSize. * * @param fieldSize the maximum number of bytes to write */ public ByteBuffer putString(CharSequence val, int fieldSize, CharsetEncoder encoder) throws CharacterCodingException { checkFieldSize(fieldSize); if (fieldSize == 0) return this; autoExpand(fieldSize); boolean utf16 = encoder.charset().name().startsWith("UTF-16"); if (utf16 && ((fieldSize & 1) != 0)) { throw new IllegalArgumentException("fieldSize is not even."); } int oldLimit = limit(); int end = position() + fieldSize; if (oldLimit < end) { throw new BufferOverflowException(); } if (val.length() == 0) { if (!utf16) { put((byte) 0x00); } else { put((byte) 0x00); put((byte) 0x00); } position(end); return this; } CharBuffer in = CharBuffer.wrap(val); limit(end); encoder.reset(); for (;;) { CoderResult cr; if (in.hasRemaining()) { cr = encoder.encode(in, buf(), true); } else { cr = encoder.flush(buf()); } if (cr.isUnderflow() || cr.isOverflow()) { break; } cr.throwException(); } limit(oldLimit); if (position() < end) { if (!utf16) { put((byte) 0x00); } else { put((byte) 0x00); put((byte) 0x00); } } position(end); return this; } /** * Reads a string which has a 16-bit length field before the actual * encoded string, using the specified decoder and returns it. * This method is a shortcut for getPrefixedString(2, decoder). */ public String getPrefixedString(CharsetDecoder decoder) throws CharacterCodingException { return getPrefixedString(2, decoder); } /** * Reads a string which has a length field before the actual * encoded string, using the specified decoder and returns it. * * @param prefixLength the length of the length field (1, 2, or 4) */ public String getPrefixedString(int prefixLength, CharsetDecoder decoder) throws CharacterCodingException { if (!prefixedDataAvailable(prefixLength)) { throw new BufferUnderflowException(); } int fieldSize = 0; switch (prefixLength) { case 1: fieldSize = getUnsigned(); break; case 2: fieldSize = getUnsignedShort(); break; case 4: fieldSize = getInt(); break; } if (fieldSize == 0) { return ""; } boolean utf16 = decoder.charset().name().startsWith("UTF-16"); if (utf16 && ((fieldSize & 1) != 0)) { throw new BufferDataException( "fieldSize is not even for a UTF-16 string."); } int oldLimit = limit(); int end = position() + fieldSize; if (oldLimit < end) { throw new BufferUnderflowException(); } limit(end); decoder.reset(); int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1; CharBuffer out = CharBuffer.allocate(expectedLength); for (;;) { CoderResult cr; if (hasRemaining()) { cr = decoder.decode(buf(), out, true); } else { cr = decoder.flush(out); } if (cr.isUnderflow()) { break; } if (cr.isOverflow()) { CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength); out.flip(); o.put(out); out = o; continue; } cr.throwException(); } limit(oldLimit); position(end); return out.flip().toString(); } /** * Writes the content of in into this buffer as a * string which has a 16-bit length field before the actual * encoded string, using the specified encoder. * This method is a shortcut for putPrefixedString(in, 2, 0, encoder). * * @throws BufferOverflowException if the specified string doesn't fit */ public ByteBuffer putPrefixedString(CharSequence in, CharsetEncoder encoder) throws CharacterCodingException { return putPrefixedString(in, 2, 0, encoder); } /** * Writes the content of in into this buffer as a * string which has a 16-bit length field before the actual * encoded string, using the specified encoder. * This method is a shortcut for putPrefixedString(in, prefixLength, 0, encoder). * * @param prefixLength the length of the length field (1, 2, or 4) * * @throws BufferOverflowException if the specified string doesn't fit */ public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, CharsetEncoder encoder) throws CharacterCodingException { return putPrefixedString(in, prefixLength, 0, encoder); } /** * Writes the content of in into this buffer as a * string which has a 16-bit length field before the actual * encoded string, using the specified encoder. * This method is a shortcut for putPrefixedString(in, prefixLength, padding, ( byte ) 0, encoder). * * @param prefixLength the length of the length field (1, 2, or 4) * @param padding the number of padded NULs (1 (or 0), 2, or 4) * * @throws BufferOverflowException if the specified string doesn't fit */ public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, int padding, CharsetEncoder encoder) throws CharacterCodingException { return putPrefixedString(in, prefixLength, padding, (byte) 0, encoder); } /** * Writes the content of in into this buffer as a * string which has a 16-bit length field before the actual * encoded string, using the specified encoder. * * @param prefixLength the length of the length field (1, 2, or 4) * @param padding the number of padded bytes (1 (or 0), 2, or 4) * @param padValue the value of padded bytes * * @throws BufferOverflowException if the specified string doesn't fit */ public ByteBuffer putPrefixedString(CharSequence val, int prefixLength, int padding, byte padValue, CharsetEncoder encoder) throws CharacterCodingException { int maxLength; switch (prefixLength) { case 1: maxLength = 255; break; case 2: maxLength = 65535; break; case 4: maxLength = Integer.MAX_VALUE; break; default: throw new IllegalArgumentException("prefixLength: " + prefixLength); } if (val.length() > maxLength) { throw new IllegalArgumentException( "The specified string is too long."); } if (val.length() == 0) { switch (prefixLength) { case 1: put((byte) 0); break; case 2: putShort((short) 0); break; case 4: putInt(0); break; } return this; } int padMask; switch (padding) { case 0: case 1: padMask = 0; break; case 2: padMask = 1; break; case 4: padMask = 3; break; default: throw new IllegalArgumentException("padding: " + padding); } CharBuffer in = CharBuffer.wrap(val); int expectedLength = (int) (in.remaining() * encoder .averageBytesPerChar()) + 1; skip(prefixLength); // make a room for the length field int oldPos = position(); encoder.reset(); for (;;) { CoderResult cr; if (in.hasRemaining()) { cr = encoder.encode(in, buf(), true); } else { cr = encoder.flush(buf()); } if (position() - oldPos > maxLength) { throw new IllegalArgumentException( "The specified string is too long."); } if (cr.isUnderflow()) { break; } if (cr.isOverflow() && isAutoExpand()) { autoExpand(expectedLength); continue; } cr.throwException(); } // Write the length field fill(padValue, padding - ((position() - oldPos) & padMask)); int length = position() - oldPos; switch (prefixLength) { case 1: put(oldPos - 1, (byte) length); break; case 2: putShort(oldPos - 2, (short) length); break; case 4: putInt(oldPos - 4, length); break; } return this; } /** * Reads a Java object from the buffer using the context {@link ClassLoader} * of the current thread. */ public Object getObject() throws ClassNotFoundException { return getObject(Thread.currentThread().getContextClassLoader()); } /** * Reads a Java object from the buffer using the specified classLoader. */ public Object getObject(final ClassLoader classLoader) throws ClassNotFoundException { if (!prefixedDataAvailable(4)) { throw new BufferUnderflowException(); } int length = getInt(); if (length <= 4) { throw new BufferDataException( "Object length should be greater than 4: " + length); } int oldLimit = limit(); limit(position() + length); try { ObjectInputStream in = new ObjectInputStream(asInputStream()) { @Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { int type = read(); if (type < 0) { throw new EOFException(); } switch (type) { case 0: // Primitive types return super.readClassDescriptor(); case 1: // Non-primitive types String className = readUTF(); Class clazz = Class.forName(className, true, classLoader); return ObjectStreamClass.lookup(clazz); default: throw new StreamCorruptedException( "Unexpected class descriptor type: " + type); } } @Override protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName(); try { return Class.forName(name, false, classLoader); } catch (ClassNotFoundException ex) { return super.resolveClass(desc); } } }; return in.readObject(); } catch (IOException e) { throw new BufferDataException(e); } finally { limit(oldLimit); } } /** * Writes the specified Java object to the buffer. */ public ByteBuffer putObject(Object o) { int oldPos = position(); skip(4); // Make a room for the length field. try { ObjectOutputStream out = new ObjectOutputStream(asOutputStream()) { @Override protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException { String className = desc.getName(); if (primitiveTypeNames.contains(className)) { write(0); super.writeClassDescriptor(desc); } else { write(1); writeUTF(desc.getName()); } } }; out.writeObject(o); out.flush(); } catch (IOException e) { throw new BufferDataException(e); } // Fill the length field int newPos = position(); position(oldPos); putInt(newPos - oldPos - 4); position(newPos); return this; } /** * Returns true if this buffer contains a data which has a data * length as a prefix and the buffer has remaining data as enough as * specified in the data length field. This method is identical with * prefixedDataAvailable( prefixLength, Integer.MAX_VALUE ). * Please not that using this method can allow DoS (Denial of Service) * attack in case the remote peer sends too big data length value. * It is recommended to use {@link #prefixedDataAvailable(int, int)} * instead. * * @param prefixLength the length of the prefix field (1, 2, or 4) * * @throws IllegalArgumentException if prefixLength is wrong * @throws BufferDataException if data length is negative */ public boolean prefixedDataAvailable(int prefixLength) { return prefixedDataAvailable(prefixLength, Integer.MAX_VALUE); } /** * Returns true if this buffer contains a data which has a data * length as a prefix and the buffer has remaining data as enough as * specified in the data length field. * * @param prefixLength the length of the prefix field (1, 2, or 4) * @param maxDataLength the allowed maximum of the read data length * * @throws IllegalArgumentException if prefixLength is wrong * @throws BufferDataException if data length is negative or greater then maxDataLength */ public boolean prefixedDataAvailable(int prefixLength, int maxDataLength) { if (remaining() < prefixLength) { return false; } int dataLength; switch (prefixLength) { case 1: dataLength = getUnsigned(position()); break; case 2: dataLength = getUnsignedShort(position()); break; case 4: dataLength = getInt(position()); break; default: throw new IllegalArgumentException("prefixLength: " + prefixLength); } if (dataLength < 0 || dataLength > maxDataLength) { throw new BufferDataException("dataLength: " + dataLength); } return remaining() - prefixLength >= dataLength; } ////////////////////////// // Skip or fill methods // ////////////////////////// /** * Forwards the position of this buffer as the specified size * bytes. */ public ByteBuffer skip(int size) { autoExpand(size); return position(position() + size); } /** * Fills this buffer with the specified value. * This method moves buffer position forward. */ public ByteBuffer fill(byte value, int size) { autoExpand(size); int q = size >>> 3; int r = size & 7; if (q > 0) { int intValue = value | (value << 8) | (value << 16) | (value << 24); long longValue = intValue; longValue <<= 32; longValue |= intValue; for (int i = q; i > 0; i--) { putLong(longValue); } } q = r >>> 2; r = r & 3; if (q > 0) { int intValue = value | (value << 8) | (value << 16) | (value << 24); putInt(intValue); } q = r >> 1; r = r & 1; if (q > 0) { short shortValue = (short) (value | (value << 8)); putShort(shortValue); } if (r > 0) { put(value); } return this; } /** * Fills this buffer with the specified value. * This method does not change buffer position. */ public ByteBuffer fillAndReset(byte value, int size) { autoExpand(size); int pos = position(); try { fill(value, size); } finally { position(pos); } return this; } /** * Fills this buffer with NUL (0x00). * This method moves buffer position forward. */ public ByteBuffer fill(int size) { autoExpand(size); int q = size >>> 3; int r = size & 7; for (int i = q; i > 0; i--) { putLong(0L); } q = r >>> 2; r = r & 3; if (q > 0) { putInt(0); } q = r >> 1; r = r & 1; if (q > 0) { putShort((short) 0); } if (r > 0) { put((byte) 0); } return this; } /** * Fills this buffer with NUL (0x00). * This method does not change buffer position. */ public ByteBuffer fillAndReset(int size) { autoExpand(size); int pos = position(); try { fill(size); } finally { position(pos); } return this; } /** * This method forwards the call to {@link #expand(int)} only when * autoExpand property is true. */ protected ByteBuffer autoExpand(int expectedRemaining) { if (isAutoExpand()) { expand(expectedRemaining); } return this; } /** * This method forwards the call to {@link #expand(int)} only when * autoExpand property is true. */ protected ByteBuffer autoExpand(int pos, int expectedRemaining) { if (isAutoExpand()) { expand(pos, expectedRemaining); } return this; } private static void checkFieldSize(int fieldSize) { if (fieldSize < 0) { throw new IllegalArgumentException("fieldSize cannot be negative: " + fieldSize); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ExpiringSessionRecycler.java0000644000175000017500000000706711002320023030550 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import org.apache.mina.util.ExpirationListener; import org.apache.mina.util.ExpiringMap; /** * An {@link IoSessionRecycler} with sessions that time out on inactivity. * * TODO Document me. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ExpiringSessionRecycler implements IoSessionRecycler { private ExpiringMap sessionMap; private ExpiringMap.Expirer mapExpirer; public ExpiringSessionRecycler() { this(ExpiringMap.DEFAULT_TIME_TO_LIVE); } public ExpiringSessionRecycler(int timeToLive) { this(timeToLive, ExpiringMap.DEFAULT_EXPIRATION_INTERVAL); } public ExpiringSessionRecycler(int timeToLive, int expirationInterval) { sessionMap = new ExpiringMap(timeToLive, expirationInterval); mapExpirer = sessionMap.getExpirer(); sessionMap.addExpirationListener(new DefaultExpirationListener()); } public void put(IoSession session) { mapExpirer.startExpiringIfNotStarted(); Object key = generateKey(session); if (!sessionMap.containsKey(key)) { sessionMap.put(key, session); } } public IoSession recycle(SocketAddress localAddress, SocketAddress remoteAddress) { return sessionMap.get(generateKey(localAddress, remoteAddress)); } public void remove(IoSession session) { sessionMap.remove(generateKey(session)); } public void stopExpiring() { mapExpirer.stopExpiring(); } public int getExpirationInterval() { return sessionMap.getExpirationInterval(); } public int getTimeToLive() { return sessionMap.getTimeToLive(); } public void setExpirationInterval(int expirationInterval) { sessionMap.setExpirationInterval(expirationInterval); } public void setTimeToLive(int timeToLive) { sessionMap.setTimeToLive(timeToLive); } private Object generateKey(IoSession session) { return generateKey(session.getLocalAddress(), session .getRemoteAddress()); } private Object generateKey(SocketAddress localAddress, SocketAddress remoteAddress) { List key = new ArrayList(2); key.add(remoteAddress); key.add(localAddress); return key; } private class DefaultExpirationListener implements ExpirationListener { public void expired(IoSession expiredSession) { expiredSession.close(); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/PooledByteBufferAllocator.java0000644000175000017500000003611111002320023030757 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.nio.ByteOrder; import org.apache.mina.common.support.BaseByteBuffer; import org.apache.mina.util.ExpiringStack; /** * A {@link ByteBufferAllocator} which pools allocated buffers.

All buffers are allocated with the size of power of * 2 (e.g. 16, 32, 64, ...) This means that you cannot simply assume that the actual capacity of the buffer and the * capacity you requested are same.

This allocator releases the buffers which have not been in use for a * certain period. You can adjust the period by calling {@link #setTimeout(int)}. The default timeout is 1 minute (60 * seconds). To release these buffers periodically, a daemon thread is started when a new instance of the allocator is * created. You can stop the thread by calling {@link #dispose()}.

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class PooledByteBufferAllocator implements ByteBufferAllocator { private static final int MINIMUM_CAPACITY = 1; private static int threadId = 0; private final Expirer expirer; private final ExpiringStack[] heapBufferStacks = new ExpiringStack[] { new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), }; private final ExpiringStack[] directBufferStacks = new ExpiringStack[] { new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), }; private int timeout; private boolean disposed; /** * Creates a new instance with the default timeout. */ public PooledByteBufferAllocator() { this(60); } /** * Creates a new instance with the specified timeout. */ public PooledByteBufferAllocator(int timeout) { setTimeout(timeout); expirer = new Expirer(); expirer.start(); } /** * Stops the thread which releases unused buffers and make this allocator unusable from now on. */ public void dispose() { if (this == ByteBuffer.getAllocator()) { throw new IllegalStateException("This allocator is in use."); } expirer.shutdown(); for (int i = directBufferStacks.length - 1; i >= 0; i--) { ExpiringStack stack = directBufferStacks[i]; synchronized (stack) { stack.clear(); } } for (int i = heapBufferStacks.length - 1; i >= 0; i--) { ExpiringStack stack = heapBufferStacks[i]; synchronized (stack) { stack.clear(); } } disposed = true; } /** * Returns the timeout value of this allocator in seconds. */ public int getTimeout() { return timeout; } /** * Returns the timeout value of this allocator in milliseconds. */ public long getTimeoutMillis() { return timeout * 1000L; } /** * Sets the timeout value of this allocator in seconds. * * @param timeout 0 or negative value to disable timeout. */ public void setTimeout(int timeout) { if (timeout < 0) { timeout = 0; } this.timeout = timeout; if (timeout > 0) { } } public ByteBuffer allocate(int capacity, boolean direct) { ensureNotDisposed(); UnexpandableByteBuffer ubb = allocate0(capacity, direct); PooledByteBuffer buf = allocateContainer(); buf.init(ubb, true); return buf; } private PooledByteBuffer allocateContainer() { return new PooledByteBuffer(); } private UnexpandableByteBuffer allocate0(int capacity, boolean direct) { ExpiringStack[] bufferStacks = direct ? directBufferStacks : heapBufferStacks; int idx = getBufferStackIndex(bufferStacks, capacity); ExpiringStack stack = bufferStacks[idx]; UnexpandableByteBuffer buf; synchronized (stack) { buf = (UnexpandableByteBuffer) stack.pop(); } if (buf == null) { java.nio.ByteBuffer nioBuf = direct ? java.nio.ByteBuffer .allocateDirect(MINIMUM_CAPACITY << idx) : java.nio.ByteBuffer.allocate(MINIMUM_CAPACITY << idx); buf = new UnexpandableByteBuffer(nioBuf); } buf.init(); return buf; } private void release0(UnexpandableByteBuffer buf) { ExpiringStack[] bufferStacks = buf.buf().isDirect() ? directBufferStacks : heapBufferStacks; ExpiringStack stack = bufferStacks[getBufferStackIndex(bufferStacks, buf.buf().capacity())]; synchronized (stack) { // push back stack.push(buf); } } public ByteBuffer wrap(java.nio.ByteBuffer nioBuffer) { ensureNotDisposed(); PooledByteBuffer buf = allocateContainer(); buf.init(new UnexpandableByteBuffer(nioBuffer), false); buf.buf.init(); buf.setPooled(false); return buf; } private int getBufferStackIndex(ExpiringStack[] bufferStacks, int size) { int targetSize = MINIMUM_CAPACITY; int stackIdx = 0; while (size > targetSize) { targetSize <<= 1; stackIdx++; if (stackIdx >= bufferStacks.length) { throw new IllegalArgumentException("Buffer size is too big: " + size); } } return stackIdx; } private void ensureNotDisposed() { if (disposed) { throw new IllegalStateException( "This allocator is disposed already."); } } private class Expirer extends Thread { private boolean timeToStop; Expirer() { super("PooledByteBufferExpirer-" + threadId++); setDaemon(true); } public void shutdown() { timeToStop = true; interrupt(); while (isAlive()) { try { join(); } catch (InterruptedException e) { //ignore since this is shutdown time } } } public void run() { // Expire unused buffers every seconds while (!timeToStop) { try { Thread.sleep(1000); } catch (InterruptedException e) { //ignore } // Check if expiration is disabled. long timeout = getTimeoutMillis(); if (timeout <= 0L) { continue; } // Expire old buffers long expirationTime = System.currentTimeMillis() - timeout; for (int i = directBufferStacks.length - 1; i >= 0; i--) { ExpiringStack stack = directBufferStacks[i]; synchronized (stack) { stack.expireBefore(expirationTime); } } for (int i = heapBufferStacks.length - 1; i >= 0; i--) { ExpiringStack stack = heapBufferStacks[i]; synchronized (stack) { stack.expireBefore(expirationTime); } } } } } private class PooledByteBuffer extends BaseByteBuffer { private UnexpandableByteBuffer buf; private int refCount = 1; protected PooledByteBuffer() { } public synchronized void init(UnexpandableByteBuffer buf, boolean clear) { this.buf = buf; if (clear) { buf.buf().clear(); } buf.buf().order(ByteOrder.BIG_ENDIAN); setAutoExpand(false); refCount = 1; } public synchronized void acquire() { if (refCount <= 0) { throw new IllegalStateException("Already released buffer."); } refCount++; } public void release() { synchronized (this) { if (refCount <= 0) { refCount = 0; throw new IllegalStateException( "Already released buffer. You released the buffer too many times."); } refCount--; if (refCount > 0) { return; } } // No need to return buffers to the pool if it is disposed already. if (disposed) { return; } buf.release(); } public java.nio.ByteBuffer buf() { return buf.buf(); } public boolean isPooled() { return buf.isPooled(); } public void setPooled(boolean pooled) { buf.setPooled(pooled); } public ByteBuffer duplicate() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init(new UnexpandableByteBuffer(buf().duplicate(), buf), false); return newBuf; } public ByteBuffer slice() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init(new UnexpandableByteBuffer(buf().slice(), buf), false); return newBuf; } public ByteBuffer asReadOnlyBuffer() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init(new UnexpandableByteBuffer(buf().asReadOnlyBuffer(), buf), false); return newBuf; } public byte[] array() { return buf().array(); } public int arrayOffset() { return buf().arrayOffset(); } protected void capacity0(int requestedCapacity) { if (buf.isDerived()) { throw new IllegalStateException( "Derived buffers cannot be expanded."); } int newCapacity = MINIMUM_CAPACITY; while (newCapacity < requestedCapacity) { newCapacity <<= 1; } UnexpandableByteBuffer oldBuf = this.buf; boolean direct = isDirect(); UnexpandableByteBuffer newBuf; try { newBuf = allocate0(newCapacity, direct); } catch (OutOfMemoryError e) { if (direct) { newBuf = allocate0(newCapacity, false); } else { throw e; } } newBuf.buf().clear(); oldBuf.buf().clear(); newBuf.buf().put(oldBuf.buf()); this.buf = newBuf; oldBuf.release(); } } private class UnexpandableByteBuffer { private final java.nio.ByteBuffer buf; private final UnexpandableByteBuffer parentBuf; private int refCount; private boolean pooled; protected UnexpandableByteBuffer(java.nio.ByteBuffer buf) { this.buf = buf; this.parentBuf = null; } protected UnexpandableByteBuffer(java.nio.ByteBuffer buf, UnexpandableByteBuffer parentBuf) { parentBuf.acquire(); this.buf = buf; this.parentBuf = parentBuf; } public void init() { refCount = 1; pooled = true; } public synchronized void acquire() { if (isDerived()) { parentBuf.acquire(); return; } if (refCount <= 0) { throw new IllegalStateException("Already released buffer."); } refCount++; } public void release() { if (isDerived()) { parentBuf.release(); return; } synchronized (this) { if (refCount <= 0) { refCount = 0; throw new IllegalStateException( "Already released buffer. You released the buffer too many times."); } refCount--; if (refCount > 0) { return; } } // No need to return buffers to the pool if it is disposed already. if (disposed) { return; } if (pooled) { if (parentBuf != null) { release0(parentBuf); } else { release0(this); } } } public java.nio.ByteBuffer buf() { return buf; } public boolean isPooled() { return pooled; } public void setPooled(boolean pooled) { this.pooled = pooled; } public boolean isDerived() { return parentBuf != null; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoServiceConfig.java0000644000175000017500000000707211002320023026740 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * A configuration which is used to configure {@link IoService}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoServiceConfig extends Cloneable { /** * Resturns the default configuration of the new {@link IoSession}s. */ IoSessionConfig getSessionConfig(); /** * Returns the {@link IoFilterChainBuilder} which will modify the * {@link IoFilterChain} of all {@link IoSession}s which is created * with this configuration. * The default value is an empty {@link DefaultIoFilterChainBuilder}. */ IoFilterChainBuilder getFilterChainBuilder(); /** * Sets the {@link IoFilterChainBuilder} which will modify the * {@link IoFilterChain} of all {@link IoSession}s which is created * with this configuration. * If you specify null this property will be set to * an empty {@link DefaultIoFilterChainBuilder}. */ void setFilterChainBuilder(IoFilterChainBuilder builder); /** * A shortcut for ( ( DefaultIoFilterChainBuilder ) {@link #getFilterChainBuilder()} ). * Please note that the returned object is not a real {@link IoFilterChain} * but a {@link DefaultIoFilterChainBuilder}. Modifying the returned builder * won't affect the existing {@link IoSession}s at all, because * {@link IoFilterChainBuilder}s affect only newly created {@link IoSession}s. * * @throws IllegalStateException if the current {@link IoFilterChainBuilder} is * not a {@link DefaultIoFilterChainBuilder} */ DefaultIoFilterChainBuilder getFilterChain(); /** * Returns the default {@link ThreadModel} of the {@link IoService}. * The default value is a {@link ExecutorThreadModel}() whose service name is * 'AnonymousIoService' and which has 16 maximum active threads. * It is strongly recommended to set a new {@link ExecutorThreadModel} by calling * {@link ExecutorThreadModel#getInstance(String)}. */ ThreadModel getThreadModel(); /** * Sets the default {@link ThreadModel} of the {@link IoService}. * If you specify null, this property will be set to the * default value. * The default value is an {@link ExecutorThreadModel} whose service name is * 'AnonymousIoService' with 16 threads. * It is strongly recommended to set a new {@link ExecutorThreadModel} by calling * {@link ExecutorThreadModel#getInstance(String)}. */ void setThreadModel(ThreadModel threadModel); /** * Returns a deep clone of this configuration. */ Object clone(); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/package.html0000644000175000017500000000023211002320023025327 0ustar drazzibdrazzib Common types required for users to use MINA. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ExceptionMonitor.java0000644000175000017500000000445511002320023027232 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import org.apache.mina.common.support.DefaultExceptionMonitor; /** * Monitors uncaught exceptions. {@link #exceptionCaught(Throwable)} is * invoked when there are any uncaught exceptions. *

* You can monitor any uncaught exceptions by setting {@link ExceptionMonitor} * by calling {@link #setInstance(ExceptionMonitor)}. The default * monitor logs all caught exceptions in WARN level using * SLF4J. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see DefaultExceptionMonitor */ public abstract class ExceptionMonitor { private static ExceptionMonitor instance = new DefaultExceptionMonitor(); /** * Returns the current exception monitor. */ public static ExceptionMonitor getInstance() { return instance; } /** * Sets the uncaught exception monitor. If null is specified, * the default monitor will be set. * * @param monitor A new instance of {@link DefaultExceptionMonitor} is set * if null is specified. */ public static void setInstance(ExceptionMonitor monitor) { if (monitor == null) { monitor = new DefaultExceptionMonitor(); } instance = monitor; } /** * Invoked when there are any uncaught exceptions. */ public abstract void exceptionCaught(Throwable cause); }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFilter.java0000644000175000017500000003215011002320023025432 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; import org.apache.mina.filter.ReferenceCountingIoFilter; /** * A filter which intercepts {@link IoHandler} events like Servlet * filters. Filters can be used for these purposes: *

    *
  • Event logging,
  • *
  • Performance measurement,
  • *
  • Authorization,
  • *
  • Overload control,
  • *
  • Message transformation (e.g. encryption and decryption, ...),
  • *
  • and many more.
  • *
*

* Please NEVER implement your filters to wrap * {@link IoSession}s. Users can cache the reference to the * session, which might malfunction if any filters are added or removed later. * *

The Life Cycle

* {@link IoFilter}s are activated only when they are inside {@link IoFilterChain}. *

* When you add an {@link IoFilter} to an {@link IoFilterChain}: *

    *
  1. {@link #init()} is invoked by {@link ReferenceCountingIoFilter} if * the filter is added at the first time.
  2. *
  3. {@link #onPreAdd(IoFilterChain, String, NextFilter)} is invoked to notify * that the filter will be added to the chain.
  4. *
  5. The filter is added to the chain, and all events and I/O requests * pass through the filter from now.
  6. *
  7. {@link #onPostAdd(IoFilterChain, String, NextFilter)} is invoked to notify * that the filter is added to the chain.
  8. *
  9. The filter is removed from the chain if {@link #onPostAdd(IoFilterChain, String, org.apache.mina.common.IoFilter.NextFilter)} * threw an exception. {@link #destroy()} is also invoked by * {@link ReferenceCountingIoFilter} if the filter is the last filter which * was added to {@link IoFilterChain}s.
  10. *
*

* When you remove an {@link IoFilter} from an {@link IoFilterChain}: *

    *
  1. {@link #onPreRemove(IoFilterChain, String, NextFilter)} is invoked to * notify that the filter will be removed from the chain.
  2. *
  3. The filter is removed from the chain, and any events and I/O requests * don't pass through the filter from now.
  4. *
  5. {@link #onPostRemove(IoFilterChain, String, NextFilter)} is invoked to * notify that the filter is removed from the chain.
  6. *
  7. {@link #destroy()} is invoked by {@link ReferenceCountingIoFilter} if * the removed filter was the last one.
  8. *
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 599822 $, $Date: 2007-11-30 22:54:07 +0900 (Fri, 30 Nov 2007) $ * * @see IoFilterAdapter */ public interface IoFilter { /** * Invoked by {@link ReferenceCountingIoFilter} when this filter * is added to a {@link IoFilterChain} at the first time, so you can * initialize shared resources. Please note that this method is never * called if you don't wrap a filter with {@link ReferenceCountingIoFilter}. */ void init() throws Exception; /** * Invoked by {@link ReferenceCountingIoFilter} when this filter * is not used by any {@link IoFilterChain} anymore, so you can destroy * shared resources. Please note that this method is never called if * you don't wrap a filter with {@link ReferenceCountingIoFilter}. */ void destroy() throws Exception; /** * Invoked before this filter is added to the specified parent. * Please note that this method can be invoked more than once if * this filter is added to more than one parents. This method is not * invoked before {@link #init()} is invoked. * * @param parent the parent who called this method * @param name the name assigned to this filter * @param nextFilter the {@link NextFilter} for this filter. You can reuse * this object until this filter is removed from the chain. */ void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception; /** * Invoked after this filter is added to the specified parent. * Please note that this method can be invoked more than once if * this filter is added to more than one parents. This method is not * invoked before {@link #init()} is invoked. * * @param parent the parent who called this method * @param name the name assigned to this filter * @param nextFilter the {@link NextFilter} for this filter. You can reuse * this object until this filter is removed from the chain. */ void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception; /** * Invoked before this filter is removed from the specified parent. * Please note that this method can be invoked more than once if * this filter is removed from more than one parents. * This method is always invoked before {@link #destroy()} is invoked. * * @param parent the parent who called this method * @param name the name assigned to this filter * @param nextFilter the {@link NextFilter} for this filter. You can reuse * this object until this filter is removed from the chain. */ void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception; /** * Invoked after this filter is removed from the specified parent. * Please note that this method can be invoked more than once if * this filter is removed from more than one parents. * This method is always invoked before {@link #destroy()} is invoked. * * @param parent the parent who called this method * @param name the name assigned to this filter * @param nextFilter the {@link NextFilter} for this filter. You can reuse * this object until this filter is removed from the chain. */ void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception; /** * Filters {@link IoHandler#sessionCreated(IoSession)} event. */ void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception; /** * Filters {@link IoHandler#sessionOpened(IoSession)} event. */ void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception; /** * Filters {@link IoHandler#sessionClosed(IoSession)} event. */ void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception; /** * Filters {@link IoHandler#sessionIdle(IoSession,IdleStatus)} * event. */ void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception; /** * Filters {@link IoHandler#exceptionCaught(IoSession,Throwable)} * event. */ void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception; /** * Filters {@link IoHandler#messageReceived(IoSession,Object)} * event. */ void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception; /** * Filters {@link IoHandler#messageSent(IoSession,Object)} * event. */ void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception; /** * Filters {@link IoSession#close()} method invocation. */ void filterClose(NextFilter nextFilter, IoSession session) throws Exception; /** * Filters {@link IoSession#write(Object)} method invocation. */ void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception; /** * Represents the next {@link IoFilter} in {@link IoFilterChain}. */ public interface NextFilter { /** * Forwards sessionCreated event to next filter. */ void sessionCreated(IoSession session); /** * Forwards sessionOpened event to next filter. */ void sessionOpened(IoSession session); /** * Forwards sessionClosed event to next filter. */ void sessionClosed(IoSession session); /** * Forwards sessionIdle event to next filter. */ void sessionIdle(IoSession session, IdleStatus status); /** * Forwards exceptionCaught event to next filter. */ void exceptionCaught(IoSession session, Throwable cause); /** * Forwards messageReceived event to next filter. */ void messageReceived(IoSession session, Object message); /** * Forwards messageSent event to next filter. */ void messageSent(IoSession session, Object message); /** * Forwards filterWrite event to next filter. */ void filterWrite(IoSession session, WriteRequest writeRequest); /** * Forwards filterClose event to next filter. */ void filterClose(IoSession session); } /** * Represents write request fired by {@link IoSession#write(Object)}. */ public static class WriteRequest { private static final WriteFuture UNUSED_FUTURE = new WriteFuture() { public boolean isWritten() { return false; } public void setWritten(boolean written) { } public IoSession getSession() { return null; } public void join() { } public boolean join(long timeoutInMillis) { return true; } public boolean isReady() { return true; } public void addListener(IoFutureListener listener) { throw new IllegalStateException( "You can't add a listener to a dummy future."); } public void removeListener(IoFutureListener listener) { throw new IllegalStateException( "You can't add a listener to a dummy future."); } public Object getLock() { return this; } }; private final Object message; private final WriteFuture future; private final SocketAddress destination; /** * Creates a new instance without {@link WriteFuture}. You'll get * an instance of {@link WriteFuture} even if you called this constructor * because {@link #getFuture()} will return a bogus future. */ public WriteRequest(Object message) { this(message, null, null); } /** * Creates a new instance with {@link WriteFuture}. */ public WriteRequest(Object message, WriteFuture future) { this(message, future, null); } /** * Creates a new instance. * * @param message a message to write * @param future a future that needs to be notified when an operation is finished * @param destination the destination of the message. This property will be * ignored unless the transport supports it. */ public WriteRequest(Object message, WriteFuture future, SocketAddress destination) { if (message == null) { throw new NullPointerException("message"); } if (future == null) { future = UNUSED_FUTURE; } this.message = message; this.future = future; this.destination = destination; } /** * Returns {@link WriteFuture} that is associated with this write request. */ public WriteFuture getFuture() { return future; } /** * Returns a message object to be written. */ public Object getMessage() { return message; } /** * Returne the destination of this write request. * * @return null for the default destination */ public SocketAddress getDestination() { return destination; } @Override public String toString() { return message.toString(); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/RuntimeIOException.java0000644000175000017500000000277711002320023027463 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * A unchecked version of {@link java.io.IOException}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class RuntimeIOException extends RuntimeException { private static final long serialVersionUID = 9029092241311939548L; public RuntimeIOException() { super(); } public RuntimeIOException(String message) { super(message); } public RuntimeIOException(String message, Throwable cause) { super(message, cause); } public RuntimeIOException(Throwable cause) { super(cause); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoSessionConfig.java0000644000175000017500000000225611002320023026762 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * The configuration of {@link IoSession}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoSessionConfig { /** * Returns a deep clone of this configuration. */ Object clone(); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoConnectorConfig.java0000644000175000017500000000267311002320023027274 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * A configuration which is used to configure {@link IoConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoConnectorConfig extends IoServiceConfig { /** * Returns the connect timeout in seconds. */ int getConnectTimeout(); /** * Returns the connect timeout in milliseconds. */ long getConnectTimeoutMillis(); /** * Sets the connect timeout in seconds. */ void setConnectTimeout(int connectTimeout); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFutureListener.java0000644000175000017500000000343311002320023027167 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.util.EventListener; /** * Something interested in being notified when the result * of an {@link IoFuture} becomes available. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoFutureListener extends EventListener { /** * An {@link IoFutureListener} that closes the {@link IoSession} which is * associated with the specified {@link IoFuture}. */ static IoFutureListener CLOSE = new IoFutureListener() { public void operationComplete(IoFuture future) { future.getSession().close(); } }; /** * Invoked when the operation associated with the {@link IoFuture} * has been completed. * * @param future The source {@link IoFuture} which called this * callback. */ void operationComplete(IoFuture future); }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFuture.java0000644000175000017500000000401511002320023025456 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * Represents the result of an ashynchronous I/O operation. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 599822 $, $Date: 2007-11-30 22:54:07 +0900 (Fri, 30 Nov 2007) $ */ public interface IoFuture { /** * Returns the {@link IoSession} which is associated with this future. */ IoSession getSession(); /** * Returns the lock object this future acquires. */ Object getLock(); /** * Wait for the asynchronous operation to end. */ void join(); /** * Wait for the asynchronous operation to end with the specified timeout. * * @return true if the operation is finished. */ boolean join(long timeoutInMillis); /** * Returns if the asynchronous operation is finished. */ boolean isReady(); /** * Adds an event listener which is notified when * the state of this future changes. */ void addListener(IoFutureListener listener); /** * Removes an existing event listener which is notified when * the state of this future changes. */ void removeListener(IoFutureListener listener); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoService.java0000644000175000017500000001073011002320023025605 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; import java.util.Set; /** * Base interface for all {@link IoAcceptor}s and {@link IoConnector}s * that provide I/O service and manage {@link IoSession}s. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoService { /** * Adds an {@link IoServiceListener} that listens any events related with * this service. */ void addListener(IoServiceListener listener); /** * Removed an existing {@link IoServiceListener} that listens any events * related with this service. */ void removeListener(IoServiceListener listener); /** * Returns all {@link SocketAddress}es this service is managing. * If this service is an {@link IoAcceptor}, a set of bind addresses will * be returned. If this service is an {@link IoConnector}, a set of remote * addresses will be returned. */ Set getManagedServiceAddresses(); /** * Returns true if this service is managing the specified serviceAddress. * If this service is an {@link IoAcceptor}, serviceAddress is a bind address. * If this service is an {@link IoConnector}, serviceAddress is a remote address. */ boolean isManaged(SocketAddress serviceAddress); /** * Returns all sessions with the specified remote or local address, * which are currently managed by this service. * {@link IoAcceptor} will assume the specified address is a local * address, and {@link IoConnector} will assume it's a remote address. * * @param serviceAddress the address to return all sessions for. * @return the sessions. An empty collection if there's no session. * @throws IllegalArgumentException if the specified address has * not been bound. * @throws UnsupportedOperationException if this operation isn't supported * for the particular transport type implemented by this {@link IoService}. */ Set getManagedSessions(SocketAddress serviceAddress); /** * Returns the default configuration which is used when you didn't specify * any configuration. */ IoServiceConfig getDefaultConfig(); /** * Returns the global {@link IoFilterChainBuilder} which will modify the * {@link IoFilterChain} of all {@link IoSession}s which is managed * by this service. * The default value is an empty {@link DefaultIoFilterChainBuilder}. */ IoFilterChainBuilder getFilterChainBuilder(); /** * Sets the global {@link IoFilterChainBuilder} which will modify the * {@link IoFilterChain} of all {@link IoSession}s which is managed * by this service. * If you specify null this property will be set to * an empty {@link DefaultIoFilterChainBuilder}. */ void setFilterChainBuilder(IoFilterChainBuilder builder); /** * A shortcut for ( ( DefaultIoFilterChainBuilder ) {@link #getFilterChainBuilder()} ). * Please note that the returned object is not a real {@link IoFilterChain} * but a {@link DefaultIoFilterChainBuilder}. Modifying the returned builder * won't affect the existing {@link IoSession}s at all, because * {@link IoFilterChainBuilder}s affect only newly created {@link IoSession}s. * * @throws IllegalStateException if the current {@link IoFilterChainBuilder} is * not a {@link DefaultIoFilterChainBuilder} */ DefaultIoFilterChainBuilder getFilterChain(); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFilterChain.java0000644000175000017500000002030511002320023026374 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.util.List; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; /** * A container of {@link IoFilter}s that forwards {@link IoHandler} events * to the consisting filters and terminal {@link IoHandler} sequentially. * Every {@link IoSession} has its own {@link IoFilterChain} (1-to-1 relationship). * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoFilterChain { /** * Returns the parent {@link IoSession} of this chain. * @return {@link IoSession} */ IoSession getSession(); /** * Returns the {@link Entry} with the specified name in this chain. * @return null if there's no such name in this chain */ Entry getEntry(String name); /** * Returns the {@link IoFilter} with the specified name in this chain. * @return null if there's no such name in this chain */ IoFilter get(String name); /** * Returns the {@link NextFilter} of the {@link IoFilter} with the * specified name in this chain. * @return null if there's no such name in this chain */ NextFilter getNextFilter(String name); /** * Returns the list of all {@link Entry}s this chain contains. */ List getAll(); /** * Returns the reversed list of all {@link Entry}s this chain contains. */ List getAllReversed(); /** * Returns true if this chain contains an {@link IoFilter} with the * specified name. */ boolean contains(String name); /** * Returns true if this chain contains the specified filter. */ boolean contains(IoFilter filter); /** * Returns true if this chain contains an {@link IoFilter} of the * specified filterType. */ boolean contains(Class filterType); /** * Adds the specified filter with the specified name at the beginning of this chain. * @throws IoFilterLifeCycleException * if {@link IoFilter#onPostAdd(IoFilterChain, String, NextFilter)} or * {@link IoFilter#init()} throws an exception. */ void addFirst(String name, IoFilter filter); /** * Adds the specified filter with the specified name at the end of this chain. * @throws IoFilterLifeCycleException * if {@link IoFilter#onPostAdd(IoFilterChain, String, NextFilter)} or * {@link IoFilter#init()} throws an exception. */ void addLast(String name, IoFilter filter); /** * Adds the specified filter with the specified name just before the filter whose name is * baseName in this chain. * @throws IoFilterLifeCycleException * if {@link IoFilter#onPostAdd(IoFilterChain, String, NextFilter)} or * {@link IoFilter#init()} throws an exception. */ void addBefore(String baseName, String name, IoFilter filter); /** * Adds the specified filter with the specified name just after the filter whose name is * baseName in this chain. * @throws IoFilterLifeCycleException * if {@link IoFilter#onPostAdd(IoFilterChain, String, NextFilter)} or * {@link IoFilter#init()} throws an exception. */ void addAfter(String baseName, String name, IoFilter filter); /** * Removes the filter with the specified name from this chain. * @throws IoFilterLifeCycleException * if {@link IoFilter#onPostRemove(IoFilterChain, String, NextFilter)} or * {@link IoFilter#destroy()} throws an exception. */ IoFilter remove(String name); /** * Removes all filters added to this chain. * @throws Exception if {@link IoFilter#onPostRemove(IoFilterChain, String, NextFilter)} thrown an exception. */ void clear() throws Exception; /** * Fires a {@link IoHandler#sessionCreated(IoSession)} event. Most users don't need to * call this method at all. Please use this method only when you implement a new transport * or fire a virtual event. */ public void fireSessionCreated(IoSession session); /** * Fires a {@link IoHandler#sessionOpened(IoSession)} event. Most users don't need to call * this method at all. Please use this method only when you implement a new transport or * fire a virtual event. */ public void fireSessionOpened(IoSession session); /** * Fires a {@link IoHandler#sessionClosed(IoSession)} event. Most users don't need to call * this method at all. Please use this method only when you implement a new transport or * fire a virtual event. */ public void fireSessionClosed(IoSession session); /** * Fires a {@link IoHandler#sessionIdle(IoSession, IdleStatus)} event. Most users don't * need to call this method at all. Please use this method only when you implement a new * transport or fire a virtual event. */ public void fireSessionIdle(IoSession session, IdleStatus status); /** * Fires a {@link #fireMessageReceived(IoSession, Object)} event. Most users don't need to * call this method at all. Please use this method only when you implement a new transport * or fire a virtual event. */ public void fireMessageReceived(IoSession session, Object message); /** * Fires a {@link IoHandler#sessionOpened(IoSession)} event. Most users don't need to call * this method at all. Please use this method only when you implement a new transport or * fire a virtual event. */ public void fireMessageSent(IoSession session, WriteRequest request); /** * Fires a {@link IoHandler#exceptionCaught(IoSession, Throwable)} event. Most users don't * need to call this method at all. Please use this method only when you implement a new * transport or fire a virtual event. */ public void fireExceptionCaught(IoSession session, Throwable cause); /** * Fires a {@link IoSession#write(Object)} event. Most users don't need to call this * method at all. Please use this method only when you implement a new transport or fire a * virtual event. */ public void fireFilterWrite(IoSession session, WriteRequest writeRequest); /** * Fires a {@link IoSession#close()} event. Most users don't need to call this method at * all. Please use this method only when you implement a new transport or fire a virtual * event. */ public void fireFilterClose(IoSession session); /** * Represents a name-filter pair that an {@link IoFilterChain} contains. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface Entry { /** * Returns the name of the filter. */ String getName(); /** * Returns the filter. */ IoFilter getFilter(); /** * Returns the {@link NextFilter} of the filter. * * @throws IllegalStateException if the {@link NextFilter} is not available */ NextFilter getNextFilter(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/WriteFuture.java0000644000175000017500000000362311002320023026205 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * An {@link IoFuture} for asynchronous write requests. * *

Example

*
 * IoSession session = ...;
 * WriteFuture future = session.write(...);
 * // Wait until the message is completely written out to the O/S buffer.
 * future.join();
 * if( future.isWritten() )
 * {
 *     // The message has been written successfully.
 * }
 * else
 * {
 *     // The messsage couldn't be written out completely for some reason.
 *     // (e.g. Connection is closed)
 * }
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface WriteFuture extends IoFuture { /** * Returns true if the write operation is finished successfully. */ boolean isWritten(); /** * Sets whether the message is written or not, and notifies all threads * waiting for this future. This method is invoked by MINA internally. * Please do not call this method directly. */ void setWritten(boolean written); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/TransportType.java0000644000175000017500000001517411002320023026562 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * Represents network transport types. * MINA provides three transport types by default: *
    *
  • {@link #SOCKET} - TCP/IP
  • *
  • {@link #DATAGRAM} - UDP/IP
  • *
  • {@link #VM_PIPE} - in-VM pipe support (only available in protocol * layer
  • *
*

* You can also create your own transport type. Please refer to * {@link #TransportType(String[], boolean)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public final class TransportType implements Serializable { private static final long serialVersionUID = 3258132470497883447L; private static final Map name2type = new HashMap(); private static void register(String[] names, TransportType type) { synchronized (name2type) { for (int i = names.length - 1; i >= 0; i--) { if (name2type.containsKey(names[i])) { throw new IllegalArgumentException("Transport type name '" + names[i] + "' is already taken."); } } for (int i = names.length - 1; i >= 0; i--) { name2type.put(names[i].toUpperCase(), type); } } } /** * Transport type: TCP/IP (Registry name: "SOCKET" or "TCP") */ public static final TransportType SOCKET = new TransportType(new String[] { "SOCKET", "TCP" }, false); /** * Transport type: UDP/IP (Registry name: "DATAGRAM" or "UDP") */ public static final TransportType DATAGRAM = new TransportType( new String[] { "DATAGRAM", "UDP" }, true); /** * Transport type: in-VM pipe (Registry name: "VM_PIPE") * Please refer to * org.apache.mina.protocol.vmpipe * package. */ public static final TransportType VM_PIPE = new TransportType( new String[] { "VM_PIPE" }, Object.class, false); /** * Returns the transport type of the specified name. * All names are case-insensitive. * * @param name the name of the transport type * @return the transport type * @throws IllegalArgumentException if the specified name is not available. */ public static TransportType getInstance(String name) { TransportType type = name2type.get(name.toUpperCase()); if (type != null) { return type; } throw new IllegalArgumentException("Unknown transport type name: " + name); } private final String[] names; private final transient boolean connectionless; private final transient Class envelopeType; /** * Creates a new instance. New transport type is automatically registered * to internal registry so that you can look it up using {@link #getInstance(String)}. * * @param names the name or aliases of this transport type * @param connectionless true if and only if this transport type is connectionless * * @throws IllegalArgumentException if names are already registered or empty */ public TransportType(String[] names, boolean connectionless) { this(names, ByteBuffer.class, connectionless); } /** * Creates a new instance. New transport type is automatically registered * to internal registry so that you can look it up using {@link #getInstance(String)}. * * @param names the name or aliases of this transport type * @param connectionless true if and only if this transport type is connectionless * * @throws IllegalArgumentException if names are already registered or empty */ public TransportType(String[] names, Class envelopeType, boolean connectionless) { if (names == null) { throw new NullPointerException("names"); } if (names.length == 0) { throw new IllegalArgumentException("names is empty"); } if (envelopeType == null) { throw new NullPointerException("envelopeType"); } for (int i = 0; i < names.length; i++) { if (names[i] == null) { throw new NullPointerException("strVals[" + i + "]"); } names[i] = names[i].toUpperCase(); } register(names, this); this.names = names; this.connectionless = connectionless; this.envelopeType = envelopeType; } /** * Returns true if the session of this transport type is * connectionless. */ public boolean isConnectionless() { return connectionless; } public Class getEnvelopeType() { return envelopeType; } /** * Returns the known names of this transport type. */ public Set getNames() { Set result = new TreeSet(); for (int i = names.length - 1; i >= 0; i--) { result.add(names[i]); } return result; } @Override public String toString() { return names[0]; } private Object readResolve() throws ObjectStreamException { for (int i = names.length - 1; i >= 0; i--) { try { return getInstance(names[i]); } catch (IllegalArgumentException e) { // ignore } } throw new InvalidObjectException("Unknown transport type."); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoConnector.java0000644000175000017500000000646611002320023026152 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; /** * Connects to endpoint, communicates with the server, and fires events to * {@link IoHandler}s. *

* Please refer to * NetCat * example. *

* You should connect to the desired socket address to start communication, * and then events for incoming connections will be sent to the specified * default {@link IoHandler}. *

* Threads connect to endpoint start automatically when * {@link #connect(SocketAddress, IoHandler)} is invoked, and stop when all * connection attempts are finished. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoConnector extends IoService { /** * Connects to the specified address. If communication starts * successfully, events are fired to the specified * handler. * * @return {@link ConnectFuture} that will tell the result of the connection attempt */ ConnectFuture connect(SocketAddress address, IoHandler handler); /** * Connects to the specified address. If communication starts * successfully, events are fired to the specified * handler. * * @param config the configuration * @return {@link ConnectFuture} that will tell the result of the connection attempt */ ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config); /** * Connects to the specified address. If communication starts * successfully, events are fired to the specified * handler. * * @param localAddress the local address the channel is bound to * @return {@link ConnectFuture} that will tell the result of the connection attempt */ ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler); /** * Connects to the specified address. If communication starts * successfully, events are fired to the specified * handler. * * @param config the configuration * @return {@link ConnectFuture} that will tell the result of the connection attempt */ ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config); }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoHandler.java0000644000175000017500000000573111002320023025567 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.io.IOException; /** * Handles all I/O events fired by MINA. * * @author The Apache MINA Project (dev@mina.apache.org) * @version $Rev: 562343 $, $Date: 2007-08-03 14:53:44 +0900 (Fri, 03 Aug 2007) $ * * @see IoHandlerAdapter */ public interface IoHandler { /** * Invoked from an I/O processor thread when a new connection has been created. * Because this method is supposed to be called from the same thread that * handles I/O of multiple sessions, please implement this method to perform * tasks that consumes minimal amount of time such as socket parameter * and user-defined session attribute initialization. */ void sessionCreated(IoSession session) throws Exception; /** * Invoked when a connection has been opened. This method is invoked after * {@link #sessionCreated(IoSession)}. The biggest difference from * {@link #sessionCreated(IoSession)} is that it's invoked from other thread * than an I/O processor thread once thread modesl is configured properly. */ void sessionOpened(IoSession session) throws Exception; /** * Invoked when a connection is closed. */ void sessionClosed(IoSession session) throws Exception; /** * Invoked with the related {@link IdleStatus} when a connection becomes idle. * This method is not invoked if the transport type is UDP; it's a known bug, * and will be fixed in 2.0. */ void sessionIdle(IoSession session, IdleStatus status) throws Exception; /** * Invoked when any exception is thrown by user {@link IoHandler} * implementation or by MINA. If cause is instanceof * {@link IOException}, MINA will close the connection automatically. */ void exceptionCaught(IoSession session, Throwable cause) throws Exception; /** * Invoked when a message is received. */ void messageReceived(IoSession session, Object message) throws Exception; /** * Invoked when a message written by {@link IoSession#write(Object)} is * sent out. */ void messageSent(IoSession session, Object message) throws Exception; }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/SimpleByteBufferAllocator.java0000644000175000017500000001040211002320023030761 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.nio.ByteOrder; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.common.support.BaseByteBuffer; /** * A simplistic {@link ByteBufferAllocator} which simply allocates a new * buffer every time. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SimpleByteBufferAllocator implements ByteBufferAllocator { private static final int MINIMUM_CAPACITY = 1; public SimpleByteBufferAllocator() { } public ByteBuffer allocate(int capacity, boolean direct) { java.nio.ByteBuffer nioBuffer; if (direct) { nioBuffer = java.nio.ByteBuffer.allocateDirect(capacity); } else { nioBuffer = java.nio.ByteBuffer.allocate(capacity); } return new SimpleByteBuffer(nioBuffer); } public ByteBuffer wrap(java.nio.ByteBuffer nioBuffer) { return new SimpleByteBuffer(nioBuffer); } public void dispose() { } private static class SimpleByteBuffer extends BaseByteBuffer { private java.nio.ByteBuffer buf; private final AtomicInteger refCount = new AtomicInteger(); protected SimpleByteBuffer(java.nio.ByteBuffer buf) { this.buf = buf; buf.order(ByteOrder.BIG_ENDIAN); refCount.set(1); } @Override public void acquire() { if (refCount.get() <= 0) { throw new IllegalStateException("Already released buffer."); } refCount.incrementAndGet(); } @Override public void release() { if (refCount.get() <= 0) { refCount.set(0); throw new IllegalStateException( "Already released buffer. You released the buffer too many times."); } refCount.decrementAndGet(); } @Override public java.nio.ByteBuffer buf() { return buf; } @Override public boolean isPooled() { return false; } @Override public void setPooled(boolean pooled) { } @Override protected void capacity0(int requestedCapacity) { int newCapacity = MINIMUM_CAPACITY; while (newCapacity < requestedCapacity) { newCapacity <<= 1; } java.nio.ByteBuffer oldBuf = this.buf; java.nio.ByteBuffer newBuf; if (isDirect()) { newBuf = java.nio.ByteBuffer.allocateDirect(newCapacity); } else { newBuf = java.nio.ByteBuffer.allocate(newCapacity); } newBuf.clear(); oldBuf.clear(); newBuf.put(oldBuf); this.buf = newBuf; } @Override public ByteBuffer duplicate() { return new SimpleByteBuffer(this.buf.duplicate()); } @Override public ByteBuffer slice() { return new SimpleByteBuffer(this.buf.slice()); } @Override public ByteBuffer asReadOnlyBuffer() { return new SimpleByteBuffer(this.buf.asReadOnlyBuffer()); } @Override public byte[] array() { return buf.array(); } @Override public int arrayOffset() { return buf.arrayOffset(); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/0000755000175000017500000000000011044712500024600 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoService.java0000644000175000017500000000617411002320023030123 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.net.SocketAddress; import java.util.Set; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoFilterChainBuilder; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceListener; import org.apache.mina.common.IoSession; /** * Base implementation of {@link IoService}s. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class BaseIoService implements IoService { /** * Current filter chain builder. */ private IoFilterChainBuilder filterChainBuilder = new DefaultIoFilterChainBuilder(); /** * Maintains the {@link IoServiceListener}s of this service. */ private final IoServiceListenerSupport listeners; protected BaseIoService() { this.listeners = new IoServiceListenerSupport(); } public IoFilterChainBuilder getFilterChainBuilder() { return filterChainBuilder; } public void setFilterChainBuilder(IoFilterChainBuilder builder) { if (builder == null) { builder = new DefaultIoFilterChainBuilder(); } filterChainBuilder = builder; } public DefaultIoFilterChainBuilder getFilterChain() { if (filterChainBuilder instanceof DefaultIoFilterChainBuilder) { return (DefaultIoFilterChainBuilder) filterChainBuilder; } else { throw new IllegalStateException( "Current filter chain builder is not a DefaultIoFilterChainBuilder."); } } public void addListener(IoServiceListener listener) { getListeners().add(listener); } public void removeListener(IoServiceListener listener) { getListeners().remove(listener); } public Set getManagedServiceAddresses() { return getListeners().getManagedServiceAddresses(); } public Set getManagedSessions(SocketAddress serviceAddress) { return getListeners().getManagedSessions(serviceAddress); } public boolean isManaged(SocketAddress serviceAddress) { return getListeners().isManaged(serviceAddress); } protected IoServiceListenerSupport getListeners() { return listeners; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoServiceConfig.java0000644000175000017500000000763611002320023031255 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.lang.reflect.Method; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.ExecutorThreadModel; import org.apache.mina.common.IoFilterChainBuilder; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.ThreadModel; /** * A base implementation of {@link IoServiceConfig}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 629332 $, $Date: 2008-02-20 12:33:32 +0900 (Wed, 20 Feb 2008) $ */ public abstract class BaseIoServiceConfig implements IoServiceConfig, Cloneable { /** * Current filter chain builder. */ private IoFilterChainBuilder filterChainBuilder = new DefaultIoFilterChainBuilder(); /** * The default thread model (initialized lazily). */ private ThreadModel defaultThreadModel; /** * Current thread model. */ private ThreadModel threadModel; public BaseIoServiceConfig() { super(); } public IoFilterChainBuilder getFilterChainBuilder() { return filterChainBuilder; } public void setFilterChainBuilder(IoFilterChainBuilder builder) { if (builder == null) { builder = new DefaultIoFilterChainBuilder(); } filterChainBuilder = builder; } public DefaultIoFilterChainBuilder getFilterChain() { if (filterChainBuilder instanceof DefaultIoFilterChainBuilder) { return (DefaultIoFilterChainBuilder) filterChainBuilder; } else { throw new IllegalStateException( "Current filter chain builder is not a DefaultIoFilterChainBuilder."); } } public ThreadModel getThreadModel() { if (threadModel == null) { threadModel = getDefaultThreadModel(); } return threadModel; } public void setThreadModel(ThreadModel threadModel) { if (threadModel == null) { // We reuse the previous default model to prevent too much // daemon threads are created. threadModel = getDefaultThreadModel(); } this.threadModel = threadModel; } private synchronized ThreadModel getDefaultThreadModel() { if (defaultThreadModel == null) { defaultThreadModel = ExecutorThreadModel.getInstance("AnonymousIoService"); } return defaultThreadModel; } @Override public Object clone() { BaseIoServiceConfig ret; try { ret = (BaseIoServiceConfig) super.clone(); } catch (CloneNotSupportedException e) { throw (InternalError) new InternalError().initCause(e); } // Try to clone the chain builder. try { Method cloneMethod = this.filterChainBuilder.getClass().getMethod( "clone"); if (cloneMethod.isAccessible()) { ret.filterChainBuilder = (IoFilterChainBuilder) cloneMethod .invoke(this.filterChainBuilder); } } catch (Exception e) { // uncloneable } return ret; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java0000644000175000017500000000327511002320023030262 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.io.IOException; import java.net.SocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; /** * A base implementation of {@link IoAcceptor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class BaseIoAcceptor extends BaseIoService implements IoAcceptor { protected BaseIoAcceptor() { } public void bind(SocketAddress address, IoHandler handler) throws IOException { this.bind(address, handler, getDefaultConfig()); } public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) { throw new UnsupportedOperationException(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoConnectorConfig.java0000644000175000017500000000340211002320023031572 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.IoConnectorConfig; /** * A base implementation of {@link IoConnectorConfig}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class BaseIoConnectorConfig extends BaseIoServiceConfig implements IoConnectorConfig { private int connectTimeout = 60; // 1 minute protected BaseIoConnectorConfig() { super(); } public int getConnectTimeout() { return connectTimeout; } public long getConnectTimeoutMillis() { return connectTimeout * 1000L; } public void setConnectTimeout(int connectTimeout) { if (connectTimeout <= 0) { throw new IllegalArgumentException("connectTimeout: " + connectTimeout); } this.connectTimeout = connectTimeout; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java0000644000175000017500000000330311002320023030444 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.net.SocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandler; /** * A base implementation of {@link IoConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class BaseIoConnector extends BaseIoService implements IoConnector { protected BaseIoConnector() { } public ConnectFuture connect(SocketAddress address, IoHandler handler) { return connect(address, handler, getDefaultConfig()); } public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler) { return connect(address, localAddress, handler, getDefaultConfig()); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/package.html0000644000175000017500000000025711002320023027052 0ustar drazzibdrazzib Internal classes used by org.apache.mina.common package. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/IoServiceListenerSupport.java0000644000175000017500000002240411002320023032425 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.net.SocketAddress; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoFuture; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoServiceListener; import org.apache.mina.common.IoSession; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.util.IdentityHashSet; /** * A helper which provides addition and removal of {@link IoServiceListener}s and firing * events. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 636193 $, $Date: 2008-03-12 13:17:43 +0900 (Wed, 12 Mar 2008) $ */ public class IoServiceListenerSupport { /** * A list of {@link IoServiceListener}s. */ private final List listeners = new CopyOnWriteArrayList(); /** * Tracks managed serviceAddresses. */ private final Set managedServiceAddresses = new CopyOnWriteArraySet(); /** * Tracks managed sesssions with serviceAddress as a key. */ private final ConcurrentMap> managedSessions = new ConcurrentHashMap>(); /** * Creates a new instance. */ public IoServiceListenerSupport() { } /** * Adds a new listener. */ public void add(IoServiceListener listener) { listeners.add(listener); } /** * Removes an existing listener. */ public void remove(IoServiceListener listener) { listeners.remove(listener); } public Set getManagedServiceAddresses() { return Collections.unmodifiableSet(managedServiceAddresses); } public boolean isManaged(SocketAddress serviceAddress) { return managedServiceAddresses.contains(serviceAddress); } public Set getManagedSessions(SocketAddress serviceAddress) { Set sessions = managedSessions.get(serviceAddress); if (null == sessions) { return Collections.emptySet(); } synchronized (sessions) { return new IdentityHashSet(sessions); } } /** * Calls {@link IoServiceListener#serviceActivated(IoService, SocketAddress, IoHandler, IoServiceConfig)} * for all registered listeners. */ public void fireServiceActivated(IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config) { if (!managedServiceAddresses.add(serviceAddress)) { return; } for (IoServiceListener listener : listeners) { try { listener.serviceActivated(service, serviceAddress, handler, config); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } /** * Calls {@link IoServiceListener#serviceDeactivated(IoService, SocketAddress, IoHandler, IoServiceConfig)} * for all registered listeners. */ public synchronized void fireServiceDeactivated(IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config) { if (!managedServiceAddresses.remove(serviceAddress)) { return; } try { for (IoServiceListener listener : listeners) { try { listener.serviceDeactivated(service, serviceAddress, handler, config); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } finally { disconnectSessions(serviceAddress, config); } } /** * Calls {@link IoServiceListener#sessionCreated(IoSession)} for all registered listeners. */ public void fireSessionCreated(IoSession session) { SocketAddress serviceAddress = session.getServiceAddress(); boolean firstSession; Set s = new IdentityHashSet(); synchronized (managedSessions) { // Get the session set. Set sessions = managedSessions.putIfAbsent(serviceAddress, Collections.synchronizedSet(s)); if (null == sessions) { sessions = s; firstSession = true; } else { firstSession = false; } // If already registered, ignore. if (!sessions.add(session)) { return; } } // If the first connector session, fire a virtual service activation event. if (session.getService() instanceof IoConnector && firstSession) { fireServiceActivated(session.getService(), session .getServiceAddress(), session.getHandler(), session .getServiceConfig()); } // Fire session events. session.getFilterChain().fireSessionCreated(session); session.getFilterChain().fireSessionOpened(session); // Fire listener events. for (IoServiceListener listener : listeners) { try { listener.sessionCreated(session); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } /** * Calls {@link IoServiceListener#sessionDestroyed(IoSession)} for all registered listeners. */ public void fireSessionDestroyed(IoSession session) { SocketAddress serviceAddress = session.getServiceAddress(); boolean lastSession = false; synchronized (managedSessions) { // Get the session set. Set sessions = managedSessions.get(serviceAddress); // Ignore if unknown. if (sessions == null) { return; } sessions.remove(session); // Try to remove the remaining empty session set after removal. if (sessions.isEmpty()) { lastSession = managedSessions.remove(serviceAddress, sessions); } } // Fire session events. session.getFilterChain().fireSessionClosed(session); // Fire listener events. try { for (IoServiceListener listener : listeners) { try { listener.sessionDestroyed(session); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } finally { // Fire a virtual service deactivation event for the last session of the connector. //TODO double-check that this is *STILL* the last session. May not be the case if (session.getService() instanceof IoConnector && lastSession) { fireServiceDeactivated(session.getService(), session .getServiceAddress(), session.getHandler(), session .getServiceConfig()); } } } private void disconnectSessions(SocketAddress serviceAddress, IoServiceConfig config) { if (!(config instanceof IoAcceptorConfig)) { return; } if (!((IoAcceptorConfig) config).isDisconnectOnUnbind()) { return; } Set sessions = getManagedSessions(serviceAddress); if (sessions.isEmpty()) { return; } final CountDownLatch latch = new CountDownLatch(sessions.size()); for (IoSession session : sessions) { session.close().addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException e) { throw new RuntimeIOException(e); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DefaultIoFuture.java0000644000175000017500000001572011002320023030504 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.util.ArrayList; import java.util.List; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoFuture; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoSession; /** * A default implementation of {@link IoFuture}. * * @author The Apache MINA Project (dev@mina.apache.org) * @version $Rev: 599822 $, $Date: 2007-11-30 22:54:07 +0900 (Fri, 30 Nov 2007) $ */ public class DefaultIoFuture implements IoFuture { private final IoSession session; private final Object lock; private IoFutureListener firstListener; private List otherListeners; private Object result; private boolean ready; private int waiters; /** * Creates a new instance. * * @param session an {@link IoSession} which is associated with this future */ public DefaultIoFuture(IoSession session) { this.session = session; this.lock = this; } /** * Creates a new instance. * * @param session an {@link IoSession} which is associated with this future */ public DefaultIoFuture(IoSession session, Object lock) { this.session = session; this.lock = lock; } public IoSession getSession() { return session; } public Object getLock() { return lock; } public void join() { awaitUninterruptibly(); } public boolean join(long timeoutMillis) { return awaitUninterruptibly(timeoutMillis); } private IoFuture awaitUninterruptibly() { synchronized (lock) { while (!ready) { waiters++; try { lock.wait(); } catch (InterruptedException e) { } finally { waiters--; } } } return this; } private boolean awaitUninterruptibly(long timeoutMillis) { try { return await0(timeoutMillis, false); } catch (InterruptedException e) { throw new InternalError(); } } private boolean await0(long timeoutMillis, boolean interruptable) throws InterruptedException { long startTime = timeoutMillis <= 0 ? 0 : System.currentTimeMillis(); long waitTime = timeoutMillis; synchronized (lock) { if (ready) { return ready; } else if (waitTime <= 0) { return ready; } waiters++; try { for (;;) { try { lock.wait(waitTime); } catch (InterruptedException e) { if (interruptable) { throw e; } } if (ready) { return true; } else { waitTime = timeoutMillis - (System.currentTimeMillis() - startTime); if (waitTime <= 0) { return ready; } } } } finally { waiters--; } } } public boolean isReady() { synchronized (lock) { return ready; } } /** * Sets the result of the asynchronous operation, and mark it as finished. */ protected void setValue(Object newValue) { synchronized (lock) { // Allow only once. if (ready) { return; } result = newValue; ready = true; if (waiters > 0) { lock.notifyAll(); } } notifyListeners(); } /** * Returns the result of the asynchronous operation. */ protected Object getValue() { synchronized (lock) { return result; } } public void addListener(IoFutureListener listener) { if (listener == null) { throw new NullPointerException("listener"); } boolean notifyNow = false; synchronized (lock) { if (ready) { notifyNow = true; } else { if (firstListener == null) { firstListener = listener; } else { if (otherListeners == null) { otherListeners = new ArrayList(1); } otherListeners.add(listener); } } } if (notifyNow) { notifyListener(listener); } } public void removeListener(IoFutureListener listener) { if (listener == null) { throw new NullPointerException("listener"); } synchronized (lock) { if (!ready) { if (listener == firstListener) { if (otherListeners != null && !otherListeners.isEmpty()) { firstListener = otherListeners.remove(0); } else { firstListener = null; } } else if (otherListeners != null) { otherListeners.remove(listener); } } } } private void notifyListeners() { // There won't be any visibility problem or concurrent modification // because 'ready' flag will be checked against both addListener and // removeListener calls. if (firstListener != null) { notifyListener(firstListener); firstListener = null; if (otherListeners != null) { for (IoFutureListener l : otherListeners) { notifyListener(l); } otherListeners = null; } } } @SuppressWarnings("unchecked") private void notifyListener(IoFutureListener l) { try { l.operationComplete(this); } catch (Throwable t) { ExceptionMonitor.getInstance().exceptionCaught(t); } } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java0000644000175000017500000000720511002320023031455 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.net.SocketAddress; import java.util.Set; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoFilterChainBuilder; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoServiceListener; import org.apache.mina.common.IoSession; /** * A delegated {@link IoConnector} that wraps the other {@link IoConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DelegatedIoConnector implements IoConnector { protected IoConnector delegate; /** * Creates a new instance. */ protected DelegatedIoConnector() { } /** * Sets the delegate. This method should be invoked before any operation * is requested. */ protected void init(IoConnector delegate) { this.delegate = delegate; } public ConnectFuture connect(SocketAddress address, IoHandler handler) { return delegate.connect(address, handler); } public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config) { return delegate.connect(address, handler, config); } public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler) { return delegate.connect(address, localAddress, handler); } public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config) { return delegate.connect(address, localAddress, handler, config); } public boolean isManaged(SocketAddress serviceAddress) { return delegate.isManaged(serviceAddress); } public Set getManagedServiceAddresses() { return delegate.getManagedServiceAddresses(); } public Set getManagedSessions(SocketAddress serviceAddress) { return delegate.getManagedSessions(serviceAddress); } public IoServiceConfig getDefaultConfig() { return delegate.getDefaultConfig(); } public IoFilterChainBuilder getFilterChainBuilder() { return delegate.getFilterChainBuilder(); } public void setFilterChainBuilder(IoFilterChainBuilder builder) { delegate.setFilterChainBuilder(builder); } public DefaultIoFilterChainBuilder getFilterChain() { return delegate.getFilterChain(); } public void addListener(IoServiceListener listener) { delegate.addListener(listener); } public void removeListener(IoServiceListener listener) { delegate.removeListener(listener); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DefaultWriteFuture.java0000644000175000017500000000471111002320023031225 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; /** * A default implementation of {@link WriteFuture}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 599822 $, $Date: 2007-11-30 22:54:07 +0900 (Fri, 30 Nov 2007) $ */ public class DefaultWriteFuture extends DefaultIoFuture implements WriteFuture { /** * Returns a new {@link DefaultWriteFuture} which is already marked as 'written'. */ public static WriteFuture newWrittenFuture(IoSession session) { DefaultWriteFuture unwrittenFuture = new DefaultWriteFuture(session); unwrittenFuture.setWritten(true); return unwrittenFuture; } /** * Returns a new {@link DefaultWriteFuture} which is already marked as 'not written'. */ public static WriteFuture newNotWrittenFuture(IoSession session) { DefaultWriteFuture unwrittenFuture = new DefaultWriteFuture(session); unwrittenFuture.setWritten(false); return unwrittenFuture; } /** * Creates a new instance. */ public DefaultWriteFuture(IoSession session) { super(session); } /** * Creates a new instance which uses the specified object as a lock. */ public DefaultWriteFuture(IoSession session, Object lock) { super(session, lock); } public boolean isWritten() { if (isReady()) { return (Boolean) getValue(); } else { return false; } } public void setWritten(boolean written) { setValue(written ? Boolean.TRUE : Boolean.FALSE); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptorConfig.java0000644000175000017500000000307011002320023031401 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.IoAcceptorConfig; /** * A base implementation of {@link IoAcceptorConfig}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class BaseIoAcceptorConfig extends BaseIoServiceConfig implements IoAcceptorConfig { private boolean disconnectOnUnbind = true; protected BaseIoAcceptorConfig() { super(); } public boolean isDisconnectOnUnbind() { return disconnectOnUnbind; } public void setDisconnectOnUnbind(boolean disconnectClientsOnUnbind) { this.disconnectOnUnbind = disconnectClientsOnUnbind; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoSessionConfig.java0000644000175000017500000000302111002320023031260 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.IoSessionConfig; /** * A base implementation of {@link IoSessionConfig}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class BaseIoSessionConfig implements IoSessionConfig, Cloneable { protected BaseIoSessionConfig() { } public Object clone() { BaseIoSessionConfig ret; try { ret = (BaseIoSessionConfig) super.clone(); } catch (CloneNotSupportedException e) { throw (InternalError) new InternalError().initCause(e); } return ret; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseIoSession.java0000644000175000017500000003133511002320023030143 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.net.SocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.common.CloseFuture; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFuture; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoService; import org.apache.mina.common.IoSession; import org.apache.mina.common.TrafficMask; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.IoFilter.WriteRequest; /** * Base implementation of {@link IoSession}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 592279 $, $Date: 2007-11-06 13:59:46 +0900 (Tue, 06 Nov 2007) $ */ public abstract class BaseIoSession implements IoSession { private static final IoFutureListener SCHEDULED_COUNTER_RESETTER = new IoFutureListener() { public void operationComplete(IoFuture future) { BaseIoSession s = (BaseIoSession) future.getSession(); s.scheduledWriteBytes.set(0); s.scheduledWriteRequests.set(0); } }; private final Object lock = new Object(); private final Map attributes = Collections .synchronizedMap(new HashMap(8)); private final long creationTime; /** * A future that will be set 'closed' when the connection is closed. */ private final CloseFuture closeFuture = new DefaultCloseFuture(this); private final AtomicBoolean scheduledForFlush = new AtomicBoolean(); private final AtomicInteger scheduledWriteBytes = new AtomicInteger(); private final AtomicInteger scheduledWriteRequests = new AtomicInteger(); private volatile boolean closing; // Configuration variables private int idleTimeForRead; private int idleTimeForWrite; private int idleTimeForBoth; private int writeTimeout; private TrafficMask trafficMask = TrafficMask.ALL; // Status variables private long readBytes; private long writtenBytes; private long readMessages; private long writtenMessages; private long lastReadTime; private long lastWriteTime; private int idleCountForBoth; private int idleCountForRead; private int idleCountForWrite; private long lastIdleTimeForBoth; private long lastIdleTimeForRead; private long lastIdleTimeForWrite; protected BaseIoSession() { creationTime = lastReadTime = lastWriteTime = lastIdleTimeForBoth = lastIdleTimeForRead = lastIdleTimeForWrite = System .currentTimeMillis(); closeFuture.addListener(SCHEDULED_COUNTER_RESETTER); } public boolean isConnected() { return !closeFuture.isClosed(); } public boolean isClosing() { return closing || closeFuture.isClosed(); } public CloseFuture getCloseFuture() { return closeFuture; } public boolean isScheduledForFlush() { return scheduledForFlush.get(); } public boolean setScheduledForFlush(boolean flag) { if (flag) { return scheduledForFlush.compareAndSet(false, true); } else { scheduledForFlush.set(false); return true; } } public CloseFuture close() { synchronized (lock) { if (isClosing()) { return closeFuture; } else { closing = true; } } close0(); return closeFuture; } /** * Implement this method to perform real close operation. * By default, this method is implemented to set the future to * 'closed' immediately. */ protected void close0() { closeFuture.setClosed(); } public WriteFuture write(Object message) { return write(message, null); } public WriteFuture write(Object message, SocketAddress remoteAddress) { if (isClosing() ) { return DefaultWriteFuture.newNotWrittenFuture(this); } WriteFuture future = new DefaultWriteFuture(this); write0(new WriteRequest(message, future, remoteAddress)); return future; } /** * Implement this method to perform real write operation with * the specified writeRequest. * * By default, this method is implemented to set the future to * 'not written' immediately. * * @param writeRequest Write request to make */ protected void write0(WriteRequest writeRequest) { writeRequest.getFuture().setWritten(false); } public Object getAttachment() { return getAttribute(""); } public Object setAttachment(Object attachment) { return setAttribute("", attachment); } public Object getAttribute(String key) { return attributes.get(key); } public Object setAttribute(String key, Object value) { if (value == null) { return removeAttribute(key); } else { return attributes.put(key, value); } } public Object setAttribute(String key) { return setAttribute(key, Boolean.TRUE); } public Object removeAttribute(String key) { return attributes.remove(key); } public boolean containsAttribute(String key) { return getAttribute(key) != null; } public Set getAttributeKeys() { synchronized (attributes) { return new HashSet(attributes.keySet()); } } public int getIdleTime(IdleStatus status) { if (status == IdleStatus.BOTH_IDLE) return idleTimeForBoth; if (status == IdleStatus.READER_IDLE) return idleTimeForRead; if (status == IdleStatus.WRITER_IDLE) return idleTimeForWrite; throw new IllegalArgumentException("Unknown idle status: " + status); } public long getIdleTimeInMillis(IdleStatus status) { return getIdleTime(status) * 1000L; } public void setIdleTime(IdleStatus status, int idleTime) { if (idleTime < 0) throw new IllegalArgumentException("Illegal idle time: " + idleTime); if (status == IdleStatus.BOTH_IDLE) idleTimeForBoth = idleTime; else if (status == IdleStatus.READER_IDLE) idleTimeForRead = idleTime; else if (status == IdleStatus.WRITER_IDLE) idleTimeForWrite = idleTime; else throw new IllegalArgumentException("Unknown idle status: " + status); } public int getWriteTimeout() { return writeTimeout; } public long getWriteTimeoutInMillis() { return writeTimeout * 1000L; } public void setWriteTimeout(int writeTimeout) { if (writeTimeout < 0) throw new IllegalArgumentException("Illegal write timeout: " + writeTimeout); this.writeTimeout = writeTimeout; } public TrafficMask getTrafficMask() { return trafficMask; } public void setTrafficMask(TrafficMask trafficMask) { if (trafficMask == null) { throw new NullPointerException("trafficMask"); } if (this.trafficMask == trafficMask) { return; } this.trafficMask = trafficMask; updateTrafficMask(); } public void suspendRead() { setTrafficMask(getTrafficMask().and(TrafficMask.READ.not())); } public void suspendWrite() { setTrafficMask(getTrafficMask().and(TrafficMask.WRITE.not())); } public void resumeRead() { setTrafficMask(getTrafficMask().or(TrafficMask.READ)); } public void resumeWrite() { setTrafficMask(getTrafficMask().or(TrafficMask.WRITE)); } /** * Signals the {@link IoService} that the {@link TrafficMask} of this * session has been changed. */ protected abstract void updateTrafficMask(); public long getReadBytes() { return readBytes; } public long getWrittenBytes() { return writtenBytes; } public long getWrittenWriteRequests() { return writtenMessages; } public long getReadMessages() { return readMessages; } public long getWrittenMessages() { return writtenMessages; } public int getScheduledWriteBytes() { return scheduledWriteBytes.get(); } public int getScheduledWriteRequests() { return scheduledWriteRequests.get(); } public void increaseReadBytes(int increment) { if (increment > 0) { readBytes += increment; lastReadTime = System.currentTimeMillis(); idleCountForBoth = 0; idleCountForRead = 0; } } public void increaseWrittenBytes(int increment) { if (increment > 0) { writtenBytes += increment; lastWriteTime = System.currentTimeMillis(); idleCountForBoth = 0; idleCountForWrite = 0; scheduledWriteBytes.addAndGet(-increment); } } public void increaseReadMessages() { readMessages++; lastReadTime = System.currentTimeMillis(); } public void increaseWrittenMessages() { writtenMessages++; lastWriteTime = System.currentTimeMillis(); scheduledWriteRequests.decrementAndGet(); } public void increaseScheduledWriteBytes(int increment) { scheduledWriteBytes.addAndGet(increment); } public void increaseScheduledWriteRequests() { scheduledWriteRequests.incrementAndGet(); } public long getCreationTime() { return creationTime; } public long getLastIoTime() { return Math.max(lastReadTime, lastWriteTime); } public long getLastReadTime() { return lastReadTime; } public long getLastWriteTime() { return lastWriteTime; } public boolean isIdle(IdleStatus status) { if (status == IdleStatus.BOTH_IDLE) return idleCountForBoth > 0; if (status == IdleStatus.READER_IDLE) return idleCountForRead > 0; if (status == IdleStatus.WRITER_IDLE) return idleCountForWrite > 0; throw new IllegalArgumentException("Unknown idle status: " + status); } public int getIdleCount(IdleStatus status) { if (status == IdleStatus.BOTH_IDLE) return idleCountForBoth; if (status == IdleStatus.READER_IDLE) return idleCountForRead; if (status == IdleStatus.WRITER_IDLE) return idleCountForWrite; throw new IllegalArgumentException("Unknown idle status: " + status); } public long getLastIdleTime(IdleStatus status) { if (status == IdleStatus.BOTH_IDLE) return lastIdleTimeForBoth; if (status == IdleStatus.READER_IDLE) return lastIdleTimeForRead; if (status == IdleStatus.WRITER_IDLE) return lastIdleTimeForWrite; throw new IllegalArgumentException("Unknown idle status: " + status); } public void increaseIdleCount(IdleStatus status) { if (status == IdleStatus.BOTH_IDLE) { idleCountForBoth++; lastIdleTimeForBoth = System.currentTimeMillis(); } else if (status == IdleStatus.READER_IDLE) { idleCountForRead++; lastIdleTimeForRead = System.currentTimeMillis(); } else if (status == IdleStatus.WRITER_IDLE) { idleCountForWrite++; lastIdleTimeForWrite = System.currentTimeMillis(); } else throw new IllegalArgumentException("Unknown idle status: " + status); } @Override public String toString() { return "(" + getTransportType() + ", R: " + getRemoteAddress() + ", L: " + getLocalAddress() + ", S: " + getServiceAddress() + ')'; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java0000644000175000017500000000701211002320023031257 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.io.IOException; import java.net.SocketAddress; import java.util.Set; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoFilterChainBuilder; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoServiceListener; import org.apache.mina.common.IoSession; /** * A delegated {@link IoAcceptor} that wraps the other {@link IoAcceptor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DelegatedIoAcceptor implements IoAcceptor { protected IoAcceptor delegate; /** * Creates a new instance. */ protected DelegatedIoAcceptor() { } /** * Sets the delegate. This method should be invoked before any operations * is requested. */ protected void init(IoAcceptor delegate) { this.delegate = delegate; } public void bind(SocketAddress address, IoHandler handler) throws IOException { delegate.bind(address, handler); } public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException { delegate.bind(address, handler, config); } public void unbind(SocketAddress address) { delegate.unbind(address); } public void unbindAll() { delegate.unbindAll(); } public boolean isManaged(SocketAddress address) { return delegate.isManaged(address); } public Set getManagedServiceAddresses() { return delegate.getManagedServiceAddresses(); } public Set getManagedSessions(SocketAddress serviceAddress) { return delegate.getManagedSessions(serviceAddress); } public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) { return delegate.newSession(remoteAddress, localAddress); } public IoServiceConfig getDefaultConfig() { return delegate.getDefaultConfig(); } public IoFilterChainBuilder getFilterChainBuilder() { return delegate.getFilterChainBuilder(); } public void setFilterChainBuilder(IoFilterChainBuilder builder) { delegate.setFilterChainBuilder(builder); } public DefaultIoFilterChainBuilder getFilterChain() { return delegate.getFilterChain(); } public void addListener(IoServiceListener listener) { delegate.addListener(listener); } public void removeListener(IoServiceListener listener) { delegate.removeListener(listener); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/AbstractIoFilterChain.java0000644000175000017500000005365611002320023031613 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoFilterLifeCycleException; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.util.ByteBufferUtil; import org.apache.mina.util.SessionLog; /** * An abstract implementation of {@link IoFilterChain} that provides * common operations for developers to implement their own transport layer. *

* The only method a developer should implement is * {@link #doWrite(IoSession, IoFilter.WriteRequest)}. This method is invoked * when filter chain is evaluated for * {@link IoFilter#filterWrite(NextFilter, IoSession, IoFilter.WriteRequest)} and * finally to be written out. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 561238 $, $Date: 2007-07-31 15:12:43 +0900 (Tue, 31 Jul 2007) $ */ public abstract class AbstractIoFilterChain implements IoFilterChain { /** * A session attribute that stores a {@link ConnectFuture} related with * the {@link IoSession}. {@link AbstractIoFilterChain} clears this * attribute and notifies the future when {@link #fireSessionOpened(IoSession)} * or {@link #fireExceptionCaught(IoSession, Throwable)} is invoked */ public static final String CONNECT_FUTURE = AbstractIoFilterChain.class .getName() + ".connectFuture"; private final IoSession session; private final Map name2entry = new HashMap(); private final EntryImpl head; private final EntryImpl tail; protected AbstractIoFilterChain(IoSession session) { if (session == null) { throw new NullPointerException("session"); } this.session = session; head = new EntryImpl(null, null, "head", new HeadFilter()); tail = new EntryImpl(head, null, "tail", new TailFilter()); head.nextEntry = tail; } public IoSession getSession() { return session; } public Entry getEntry(String name) { Entry e = name2entry.get(name); if (e == null) { return null; } return e; } public IoFilter get(String name) { Entry e = getEntry(name); if (e == null) { return null; } return e.getFilter(); } public NextFilter getNextFilter(String name) { Entry e = getEntry(name); if (e == null) { return null; } return e.getNextFilter(); } public synchronized void addFirst(String name, IoFilter filter) { checkAddable(name); register(head, name, filter); } public synchronized void addLast(String name, IoFilter filter) { checkAddable(name); register(tail.prevEntry, name, filter); } public synchronized void addBefore(String baseName, String name, IoFilter filter) { EntryImpl baseEntry = checkOldName(baseName); checkAddable(name); register(baseEntry.prevEntry, name, filter); } public synchronized void addAfter(String baseName, String name, IoFilter filter) { EntryImpl baseEntry = checkOldName(baseName); checkAddable(name); register(baseEntry, name, filter); } public synchronized IoFilter remove(String name) { EntryImpl entry = checkOldName(name); deregister(entry); return entry.getFilter(); } public synchronized void clear() throws Exception { Iterator it = new ArrayList(name2entry.keySet()) .iterator(); while (it.hasNext()) { this.remove(it.next()); } } private void register(EntryImpl prevEntry, String name, IoFilter filter) { EntryImpl newEntry = new EntryImpl(prevEntry, prevEntry.nextEntry, name, filter); try { filter.onPreAdd(this, name, newEntry.getNextFilter()); } catch (Exception e) { throw new IoFilterLifeCycleException("onPreAdd(): " + name + ':' + filter + " in " + getSession(), e); } prevEntry.nextEntry.prevEntry = newEntry; prevEntry.nextEntry = newEntry; name2entry.put(name, newEntry); try { filter.onPostAdd(this, name, newEntry.getNextFilter()); } catch (Exception e) { deregister0(newEntry); throw new IoFilterLifeCycleException("onPostAdd(): " + name + ':' + filter + " in " + getSession(), e); } } private void deregister(EntryImpl entry) { IoFilter filter = entry.getFilter(); try { filter.onPreRemove(this, entry.getName(), entry.getNextFilter()); } catch (Exception e) { throw new IoFilterLifeCycleException("onPreRemove(): " + entry.getName() + ':' + filter + " in " + getSession(), e); } deregister0(entry); try { filter.onPostRemove(this, entry.getName(), entry.getNextFilter()); } catch (Exception e) { throw new IoFilterLifeCycleException("onPostRemove(): " + entry.getName() + ':' + filter + " in " + getSession(), e); } } private void deregister0(EntryImpl entry) { EntryImpl prevEntry = entry.prevEntry; EntryImpl nextEntry = entry.nextEntry; prevEntry.nextEntry = nextEntry; nextEntry.prevEntry = prevEntry; name2entry.remove(entry.name); } /** * Throws an exception when the specified filter name is not registered in this chain. * * @return An filter entry with the specified name. */ private EntryImpl checkOldName(String baseName) { EntryImpl e = (EntryImpl) name2entry.get(baseName); if (e == null) { throw new IllegalArgumentException("Unknown filter name:" + baseName); } return e; } /** * Checks the specified filter name is already taken and throws an exception if already taken. */ private void checkAddable(String name) { if (name2entry.containsKey(name)) { throw new IllegalArgumentException( "Other filter is using the same name '" + name + "'"); } } public void fireSessionCreated(IoSession session) { Entry head = this.head; callNextSessionCreated(head, session); } private void callNextSessionCreated(Entry entry, IoSession session) { try { entry.getFilter().sessionCreated(entry.getNextFilter(), session); } catch (Throwable e) { fireExceptionCaught(session, e); } } public void fireSessionOpened(IoSession session) { Entry head = this.head; callNextSessionOpened(head, session); } private void callNextSessionOpened(Entry entry, IoSession session) { try { entry.getFilter().sessionOpened(entry.getNextFilter(), session); } catch (Throwable e) { fireExceptionCaught(session, e); } } public void fireSessionClosed(IoSession session) { // Update future. try { session.getCloseFuture().setClosed(); } catch (Throwable t) { fireExceptionCaught(session, t); } // And start the chain. Entry head = this.head; callNextSessionClosed(head, session); } private void callNextSessionClosed(Entry entry, IoSession session) { try { entry.getFilter().sessionClosed(entry.getNextFilter(), session); } catch (Throwable e) { fireExceptionCaught(session, e); } } public void fireSessionIdle(IoSession session, IdleStatus status) { Entry head = this.head; callNextSessionIdle(head, session, status); } private void callNextSessionIdle(Entry entry, IoSession session, IdleStatus status) { try { entry.getFilter().sessionIdle(entry.getNextFilter(), session, status); } catch (Throwable e) { fireExceptionCaught(session, e); } } public void fireMessageReceived(IoSession session, Object message) { Entry head = this.head; callNextMessageReceived(head, session, message); } private void callNextMessageReceived(Entry entry, IoSession session, Object message) { try { entry.getFilter().messageReceived(entry.getNextFilter(), session, message); } catch (Throwable e) { fireExceptionCaught(session, e); } } public void fireMessageSent(IoSession session, WriteRequest request) { try { request.getFuture().setWritten(true); } catch (Throwable t) { fireExceptionCaught(session, t); } Entry head = this.head; callNextMessageSent(head, session, request.getMessage()); } private void callNextMessageSent(Entry entry, IoSession session, Object message) { try { entry.getFilter().messageSent(entry.getNextFilter(), session, message); } catch (Throwable e) { fireExceptionCaught(session, e); } } public void fireExceptionCaught(IoSession session, Throwable cause) { // Notify the related ConnectFuture // if the session is created from SocketConnector. ConnectFuture future = (ConnectFuture) session .removeAttribute(CONNECT_FUTURE); if (future == null) { Entry head = this.head; callNextExceptionCaught(head, session, cause); } else { // Please note that this place is not the only place that // calls ConnectFuture.setException(). future.setException(cause); } } private void callNextExceptionCaught(Entry entry, IoSession session, Throwable cause) { try { entry.getFilter().exceptionCaught(entry.getNextFilter(), session, cause); } catch (Throwable e) { SessionLog.warn(session, "Unexpected exception from exceptionCaught handler.", e); } } public void fireFilterWrite(IoSession session, WriteRequest writeRequest) { Entry tail = this.tail; callPreviousFilterWrite(tail, session, writeRequest); } private void callPreviousFilterWrite(Entry entry, IoSession session, WriteRequest writeRequest) { try { entry.getFilter().filterWrite(entry.getNextFilter(), session, writeRequest); } catch (Throwable e) { writeRequest.getFuture().setWritten(false); fireExceptionCaught(session, e); } } public void fireFilterClose(IoSession session) { Entry tail = this.tail; callPreviousFilterClose(tail, session); } private void callPreviousFilterClose(Entry entry, IoSession session) { try { entry.getFilter().filterClose(entry.getNextFilter(), session); } catch (Throwable e) { fireExceptionCaught(session, e); } } public List getAll() { List list = new ArrayList(); EntryImpl e = head.nextEntry; while (e != tail) { list.add(e); e = e.nextEntry; } return list; } public List getAllReversed() { List list = new ArrayList(); EntryImpl e = tail.prevEntry; while (e != head) { list.add(e); e = e.prevEntry; } return list; } public boolean contains(String name) { return getEntry(name) != null; } public boolean contains(IoFilter filter) { EntryImpl e = head.nextEntry; while (e != tail) { if (e.getFilter() == filter) { return true; } e = e.nextEntry; } return false; } public boolean contains(Class filterType) { EntryImpl e = head.nextEntry; while (e != tail) { if (filterType.isAssignableFrom(e.getFilter().getClass())) { return true; } e = e.nextEntry; } return false; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{ "); boolean empty = true; EntryImpl e = head.nextEntry; while (e != tail) { if (!empty) { buf.append(", "); } else { empty = false; } buf.append('('); buf.append(e.getName()); buf.append(':'); buf.append(e.getFilter()); buf.append(')'); e = e.nextEntry; } if (empty) { buf.append("empty"); } buf.append(" }"); return buf.toString(); } protected void finalize() throws Throwable { try { this.clear(); } finally { super.finalize(); } } protected abstract void doWrite(IoSession session, WriteRequest writeRequest) throws Exception; protected abstract void doClose(IoSession session) throws Exception; private class HeadFilter extends IoFilterAdapter { public void sessionCreated(NextFilter nextFilter, IoSession session) { nextFilter.sessionCreated(session); } public void sessionOpened(NextFilter nextFilter, IoSession session) { nextFilter.sessionOpened(session); } public void sessionClosed(NextFilter nextFilter, IoSession session) { nextFilter.sessionClosed(session); } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) { nextFilter.sessionIdle(session, status); } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) { nextFilter.exceptionCaught(session, cause); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) { nextFilter.messageReceived(session, message); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) { nextFilter.messageSent(session, message); } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { if (session.getTransportType().getEnvelopeType().isAssignableFrom( writeRequest.getMessage().getClass())) { doWrite(session, writeRequest); } else { throw new IllegalStateException( "Write requests must be transformed to " + session.getTransportType().getEnvelopeType() + ": " + writeRequest); } } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { doClose(session); } } private static class TailFilter extends IoFilterAdapter { public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { session.getHandler().sessionCreated(session); } public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception { try { session.getHandler().sessionOpened(session); } finally { // Notify the related ConnectFuture // if the session is created from SocketConnector. ConnectFuture future = (ConnectFuture) session .removeAttribute(CONNECT_FUTURE); if (future != null) { future.setSession(session); } } } public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { try { session.getHandler().sessionClosed(session); } finally { // Remove all filters. session.getFilterChain().clear(); } } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { session.getHandler().sessionIdle(session, status); } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception { session.getHandler().exceptionCaught(session, cause); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { try { session.getHandler().messageReceived(session, message); } finally { ByteBufferUtil.releaseIfPossible(message); } } public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception { try { session.getHandler().messageSent(session, message); } finally { ByteBufferUtil.releaseIfPossible(message); } } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { nextFilter.filterWrite(session, writeRequest); } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.filterClose(session); } } private class EntryImpl implements Entry { private EntryImpl prevEntry; private EntryImpl nextEntry; private final String name; private final IoFilter filter; private final NextFilter nextFilter; private EntryImpl(EntryImpl prevEntry, EntryImpl nextEntry, String name, IoFilter filter) { if (filter == null) { throw new NullPointerException("filter"); } if (name == null) { throw new NullPointerException("name"); } this.prevEntry = prevEntry; this.nextEntry = nextEntry; this.name = name; this.filter = filter; this.nextFilter = new NextFilter() { public void sessionCreated(IoSession session) { Entry nextEntry = EntryImpl.this.nextEntry; callNextSessionCreated(nextEntry, session); } public void sessionOpened(IoSession session) { Entry nextEntry = EntryImpl.this.nextEntry; callNextSessionOpened(nextEntry, session); } public void sessionClosed(IoSession session) { Entry nextEntry = EntryImpl.this.nextEntry; callNextSessionClosed(nextEntry, session); } public void sessionIdle(IoSession session, IdleStatus status) { Entry nextEntry = EntryImpl.this.nextEntry; callNextSessionIdle(nextEntry, session, status); } public void exceptionCaught(IoSession session, Throwable cause) { Entry nextEntry = EntryImpl.this.nextEntry; callNextExceptionCaught(nextEntry, session, cause); } public void messageReceived(IoSession session, Object message) { Entry nextEntry = EntryImpl.this.nextEntry; callNextMessageReceived(nextEntry, session, message); } public void messageSent(IoSession session, Object message) { Entry nextEntry = EntryImpl.this.nextEntry; callNextMessageSent(nextEntry, session, message); } public void filterWrite(IoSession session, WriteRequest writeRequest) { Entry nextEntry = EntryImpl.this.prevEntry; callPreviousFilterWrite(nextEntry, session, writeRequest); } public void filterClose(IoSession session) { Entry nextEntry = EntryImpl.this.prevEntry; callPreviousFilterClose(nextEntry, session); } }; } public String getName() { return name; } public IoFilter getFilter() { return filter; } public NextFilter getNextFilter() { return nextFilter; } public String toString() { return "(" + getName() + ':' + filter + ')'; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/BaseByteBuffer.java0000644000175000017500000002114311002320023030261 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ByteBufferAllocator; /** * A base implementation of {@link ByteBuffer}. This implementation * assumes that {@link ByteBuffer#buf()} always returns a correct NIO * {@link java.nio.ByteBuffer} instance. Most implementations could * extend this class and implement their own buffer management mechanism. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * @noinspection StaticNonFinalField * @see ByteBufferAllocator */ public abstract class BaseByteBuffer extends ByteBuffer { private boolean autoExpand; /** * We don't have any access to Buffer.markValue(), so we need to track it down, * which will cause small extra overhead. */ private int mark = -1; protected BaseByteBuffer() { } public boolean isDirect() { return buf().isDirect(); } public boolean isReadOnly() { return buf().isReadOnly(); } public int capacity() { return buf().capacity(); } public ByteBuffer capacity(int newCapacity) { if (newCapacity > capacity()) { // Allocate a new buffer and transfer all settings to it. int pos = position(); int limit = limit(); ByteOrder bo = order(); capacity0(newCapacity); buf().limit(limit); if (mark >= 0) { buf().position(mark); buf().mark(); } buf().position(pos); buf().order(bo); } return this; } /** * Implement this method to increase the capacity of this buffer. * newCapacity is always greater than the current capacity. */ protected abstract void capacity0(int newCapacity); public boolean isAutoExpand() { return autoExpand; } public ByteBuffer setAutoExpand(boolean autoExpand) { this.autoExpand = autoExpand; return this; } public ByteBuffer expand(int pos, int expectedRemaining) { int end = pos + expectedRemaining; if (end > capacity()) { // The buffer needs expansion. capacity(end); } if (end > limit()) { // We call limit() directly to prevent StackOverflowError buf().limit(end); } return this; } public int position() { return buf().position(); } public ByteBuffer position(int newPosition) { autoExpand(newPosition, 0); buf().position(newPosition); if (mark > newPosition) { mark = -1; } return this; } public int limit() { return buf().limit(); } public ByteBuffer limit(int newLimit) { autoExpand(newLimit, 0); buf().limit(newLimit); if (mark > newLimit) { mark = -1; } return this; } public ByteBuffer mark() { buf().mark(); mark = position(); return this; } public int markValue() { return mark; } public ByteBuffer reset() { buf().reset(); return this; } public ByteBuffer clear() { buf().clear(); mark = -1; return this; } public ByteBuffer flip() { buf().flip(); mark = -1; return this; } public ByteBuffer rewind() { buf().rewind(); mark = -1; return this; } public byte get() { return buf().get(); } public ByteBuffer put(byte b) { autoExpand(1); buf().put(b); return this; } public byte get(int index) { return buf().get(index); } public ByteBuffer put(int index, byte b) { autoExpand(index, 1); buf().put(index, b); return this; } public ByteBuffer get(byte[] dst, int offset, int length) { buf().get(dst, offset, length); return this; } public ByteBuffer put(java.nio.ByteBuffer src) { autoExpand(src.remaining()); buf().put(src); return this; } public ByteBuffer put(byte[] src, int offset, int length) { autoExpand(length); buf().put(src, offset, length); return this; } public ByteBuffer compact() { buf().compact(); mark = -1; return this; } public ByteOrder order() { return buf().order(); } public ByteBuffer order(ByteOrder bo) { buf().order(bo); return this; } public char getChar() { return buf().getChar(); } public ByteBuffer putChar(char value) { autoExpand(2); buf().putChar(value); return this; } public char getChar(int index) { return buf().getChar(index); } public ByteBuffer putChar(int index, char value) { autoExpand(index, 2); buf().putChar(index, value); return this; } public CharBuffer asCharBuffer() { return buf().asCharBuffer(); } public short getShort() { return buf().getShort(); } public ByteBuffer putShort(short value) { autoExpand(2); buf().putShort(value); return this; } public short getShort(int index) { return buf().getShort(index); } public ByteBuffer putShort(int index, short value) { autoExpand(index, 2); buf().putShort(index, value); return this; } public ShortBuffer asShortBuffer() { return buf().asShortBuffer(); } public int getInt() { return buf().getInt(); } public ByteBuffer putInt(int value) { autoExpand(4); buf().putInt(value); return this; } public int getInt(int index) { return buf().getInt(index); } public ByteBuffer putInt(int index, int value) { autoExpand(index, 4); buf().putInt(index, value); return this; } public IntBuffer asIntBuffer() { return buf().asIntBuffer(); } public long getLong() { return buf().getLong(); } public ByteBuffer putLong(long value) { autoExpand(8); buf().putLong(value); return this; } public long getLong(int index) { return buf().getLong(index); } public ByteBuffer putLong(int index, long value) { autoExpand(index, 8); buf().putLong(index, value); return this; } public LongBuffer asLongBuffer() { return buf().asLongBuffer(); } public float getFloat() { return buf().getFloat(); } public ByteBuffer putFloat(float value) { autoExpand(4); buf().putFloat(value); return this; } public float getFloat(int index) { return buf().getFloat(index); } public ByteBuffer putFloat(int index, float value) { autoExpand(index, 4); buf().putFloat(index, value); return this; } public FloatBuffer asFloatBuffer() { return buf().asFloatBuffer(); } public double getDouble() { return buf().getDouble(); } public ByteBuffer putDouble(double value) { autoExpand(8); buf().putDouble(value); return this; } public double getDouble(int index) { return buf().getDouble(index); } public ByteBuffer putDouble(int index, double value) { autoExpand(index, 8); buf().putDouble(index, value); return this; } public DoubleBuffer asDoubleBuffer() { return buf().asDoubleBuffer(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DefaultCloseFuture.java0000644000175000017500000000340411002320023031176 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.CloseFuture; import org.apache.mina.common.IoSession; /** * A default implementation of {@link CloseFuture}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 599822 $, $Date: 2007-11-30 22:54:07 +0900 (Fri, 30 Nov 2007) $ */ public class DefaultCloseFuture extends DefaultIoFuture implements CloseFuture { /** * Creates a new instance. */ public DefaultCloseFuture(IoSession session) { super(session); } /** * Creates a new instance which uses the specified object as a lock. */ public DefaultCloseFuture(IoSession session, Object lock) { super(session, lock); } public boolean isClosed() { if (isReady()) { return (Boolean) getValue(); } else { return false; } } public void setClosed() { setValue(Boolean.TRUE); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DefaultExceptionMonitor.java0000644000175000017500000000325511002320023032250 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A default {@link ExceptionMonitor} implementation that logs uncaught * exceptions using {@link Logger}. *

* All {@link IoService}s have this implementation as a default exception * monitor. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DefaultExceptionMonitor extends ExceptionMonitor { private final Logger log = LoggerFactory .getLogger(DefaultExceptionMonitor.class); public void exceptionCaught(Throwable cause) { if (log.isWarnEnabled()) { log.warn("Unexpected exception.", cause); } } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/ByteBufferHexDumper.java0000644000175000017500000000463711002320023031321 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.ByteBuffer; /** * Provides utility methods for ByteBuffers. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ByteBufferHexDumper { private static final byte[] highDigits; private static final byte[] lowDigits; // initialize lookup tables static { final byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int i; byte[] high = new byte[256]; byte[] low = new byte[256]; for (i = 0; i < 256; i++) { high[i] = digits[i >>> 4]; low[i] = digits[i & 0x0F]; } highDigits = high; lowDigits = low; } public static String getHexdump(ByteBuffer in) { int size = in.remaining(); if (size == 0) { return "empty"; } StringBuffer out = new StringBuffer((in.remaining() * 3) - 1); int mark = in.position(); // fill the first int byteValue = in.get() & 0xFF; out.append((char) highDigits[byteValue]); out.append((char) lowDigits[byteValue]); size--; // and the others, too for (; size > 0; size--) { out.append(' '); byteValue = in.get() & 0xFF; out.append((char) highDigits[byteValue]); out.append((char) lowDigits[byteValue]); } in.position(mark); return out.toString(); } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/support/DefaultConnectFuture.java0000644000175000017500000000511511002320023031523 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoSession; import org.apache.mina.common.RuntimeIOException; /** * A default implementation of {@link ConnectFuture}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 599822 $, $Date: 2007-11-30 22:54:07 +0900 (Fri, 30 Nov 2007) $ */ public class DefaultConnectFuture extends DefaultIoFuture implements ConnectFuture { /** * Returns a new {@link ConnectFuture} which is already marked as 'failed to connect'. */ public static ConnectFuture newFailedFuture(Throwable exception) { DefaultConnectFuture failedFuture = new DefaultConnectFuture(); failedFuture.setException(exception); return failedFuture; } /** * Creates a new instance. */ public DefaultConnectFuture() { super(null); } /** * Creates a new instance which uses the specified object as a lock. */ public DefaultConnectFuture(Object lock) { super(null, lock); } @Override public IoSession getSession() throws RuntimeIOException { Object v = getValue(); if (v instanceof RuntimeIOException) { throw (RuntimeIOException) v; } else if (v instanceof Throwable) { throw (RuntimeIOException) new RuntimeIOException( "Failed to get the session.").initCause((Throwable) v); } else { return (IoSession) v; } } public boolean isConnected() { return getValue() instanceof IoSession; } public void setSession(IoSession session) { setValue(session); } public void setException(Throwable exception) { setValue(exception); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoHandlerAdapter.java0000644000175000017500000000433011002320023027062 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import org.apache.mina.util.SessionLog; import org.apache.mina.util.SessionUtil; /** * An abstract adapter class for {@link IoHandler}. You can extend this * class and selectively override required event handler methods only. All * methods do nothing by default. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoHandlerAdapter implements IoHandler { public void sessionCreated(IoSession session) throws Exception { SessionUtil.initialize(session); } public void sessionOpened(IoSession session) throws Exception { } public void sessionClosed(IoSession session) throws Exception { } public void sessionIdle(IoSession session, IdleStatus status) throws Exception { } public void exceptionCaught(IoSession session, Throwable cause) throws Exception { if (SessionLog.isWarnEnabled(session)) { SessionLog.warn(session, "EXCEPTION, please implement " + getClass().getName() + ".exceptionCaught() for proper handling:", cause); } } public void messageReceived(IoSession session, Object message) throws Exception { } public void messageSent(IoSession session, Object message) throws Exception { } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFilterChainBuilder.java0000644000175000017500000000364611002320023027714 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * An interface that builds {@link IoFilterChain} in predefined way * when {@link IoSession} is created. You can extract common filter chain * modification logic to this interface. For example, to add a filter * to the chain, *

 * public class MyFilterChainBuilder implements IoFilterChainBuilder {
 *     public void buildFilterChain( IoFilterChain chain ) throws Exception {
 *         chain.addLast( "myFilter", new MyFilter() );
 *     }
 * }
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoFilterChainBuilder { /** * An implementation which does nothing. */ IoFilterChainBuilder NOOP = new IoFilterChainBuilder() { public void buildFilterChain(IoFilterChain chain) throws Exception { } public String toString() { return "NOOP"; } }; /** * Modifies the specified chain. */ void buildFilterChain(IoFilterChain chain) throws Exception; } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IdleStatus.java0000644000175000017500000000505011002320023025775 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * Represents the type of idleness of {@link IoSession} or * {@link IoSession}. There are three types of idleness: *
    *
  • {@link #READER_IDLE} - No data is coming from the remote peer.
  • *
  • {@link #WRITER_IDLE} - Session is not writing any data.
  • *
  • {@link #BOTH_IDLE} - Both {@link #READER_IDLE} and {@link #WRITER_IDLE}.
  • *
*

* Idle time settings are all disabled by default. You can enable them * using {@link IoSession#setIdleTime(IdleStatus,int)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IdleStatus { /** * Represents the session status that no data is coming from the remote * peer. */ public static final IdleStatus READER_IDLE = new IdleStatus("reader idle"); /** * Represents the session status that the session is not writing any data. */ public static final IdleStatus WRITER_IDLE = new IdleStatus("writer idle"); /** * Represents both {@link #READER_IDLE} and {@link #WRITER_IDLE}. */ public static final IdleStatus BOTH_IDLE = new IdleStatus("both idle"); private final String strValue; /** * Creates a new instance. */ private IdleStatus(String strValue) { this.strValue = strValue; } /** * Returns the string representation of this status. *

    *
  • {@link #READER_IDLE} - "reader idle"
  • *
  • {@link #WRITER_IDLE} - "writer idle"
  • *
  • {@link #BOTH_IDLE} - "both idle"
  • *
*/ public String toString() { return strValue; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/DefaultIoFilterChainBuilder.java0000644000175000017500000002140511002320023031212 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilterChain.Entry; /** * The default implementation of {@link IoFilterChainBuilder} which is useful * in most cases. {@link DefaultIoFilterChainBuilder} has an identical interface * with {@link IoFilter}; it contains a list of {@link IoFilter}s that you can * modify. The {@link IoFilter}s which are added to this builder will be appended * to the {@link IoFilterChain} when {@link #buildFilterChain(IoFilterChain)} is * invoked. *

* However, the identical interface doesn't mean that it behaves in an exactly * same way with {@link IoFilterChain}. {@link DefaultIoFilterChainBuilder} * doesn't manage the life cycle of the {@link IoFilter}s at all, and the * existing {@link IoSession}s won't get affected by the changes in this builder. * {@link IoFilterChainBuilder}s affect only newly created {@link IoSession}s. * *

 * IoAcceptor acceptor = ...;
 * DefaultIoFilterChainBuilder builder = acceptor.getFilterChain();
 * builder.addLast( "myFilter", new MyFilter() );
 * ...
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 562335 $, $Date: 2007-08-03 14:28:02 +0900 (Fri, 03 Aug 2007) $ */ public class DefaultIoFilterChainBuilder implements IoFilterChainBuilder, Cloneable { private final List entries; /** * Creates a new instance with an empty filter list. */ public DefaultIoFilterChainBuilder() { entries = new CopyOnWriteArrayList(); } /** * @see IoFilterChain#getEntry(String) */ public Entry getEntry(String name) { for (Entry e: entries) { if (e.getName().equals(name)) { return e; } } return null; } /** * @see IoFilterChain#get(String) */ public IoFilter get(String name) { Entry e = getEntry(name); if (e == null) { return null; } return e.getFilter(); } /** * @see IoFilterChain#getAll() */ public List getAll() { return new ArrayList(entries); } /** * @see IoFilterChain#getAllReversed() */ public List getAllReversed() { List result = getAll(); Collections.reverse(result); return result; } /** * @see IoFilterChain#contains(String) */ public boolean contains(String name) { return getEntry(name) != null; } /** * @see IoFilterChain#contains(IoFilter) */ public boolean contains(IoFilter filter) { for (Iterator i = entries.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); if (e.getFilter() == filter) { return true; } } return false; } /** * @see IoFilterChain#contains(Class) */ public boolean contains(Class filterType) { for (Iterator i = entries.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); if (filterType.isAssignableFrom(e.getFilter().getClass())) { return true; } } return false; } /** * @see IoFilterChain#addFirst(String, IoFilter) */ public synchronized void addFirst(String name, IoFilter filter) { register(0, new EntryImpl(name, filter)); } /** * @see IoFilterChain#addLast(String, IoFilter) */ public synchronized void addLast(String name, IoFilter filter) { register(entries.size(), new EntryImpl(name, filter)); } /** * @see IoFilterChain#addBefore(String, String, IoFilter) */ public synchronized void addBefore(String baseName, String name, IoFilter filter) { checkBaseName(baseName); for (ListIterator i = entries.listIterator(); i.hasNext();) { Entry base = i.next(); if (base.getName().equals(baseName)) { register(i.previousIndex(), new EntryImpl(name, filter)); break; } } } /** * @see IoFilterChain#addAfter(String, String, IoFilter) */ public synchronized void addAfter(String baseName, String name, IoFilter filter) { checkBaseName(baseName); for (ListIterator i = entries.listIterator(); i.hasNext();) { Entry base = i.next(); if (base.getName().equals(baseName)) { register(i.nextIndex(), new EntryImpl(name, filter)); break; } } } /** * @see IoFilterChain#remove(String) */ public synchronized IoFilter remove(String name) { if (name == null) { throw new NullPointerException("name"); } for (ListIterator i = entries.listIterator(); i.hasNext();) { Entry e = i.next(); if (e.getName().equals(name)) { entries.remove(i.previousIndex()); return e.getFilter(); } } throw new IllegalArgumentException("Unknown filter name: " + name); } /** * @see IoFilterChain#clear() */ public synchronized void clear() throws Exception { entries.clear(); } public void buildFilterChain(IoFilterChain chain) throws Exception { for (Iterator i = entries.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); chain.addLast(e.getName(), e.getFilter()); } } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{ "); boolean empty = true; for (Iterator i = entries.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); if (!empty) { buf.append(", "); } else { empty = false; } buf.append('('); buf.append(e.getName()); buf.append(':'); buf.append(e.getFilter()); buf.append(')'); } if (empty) { buf.append("empty"); } buf.append(" }"); return buf.toString(); } public Object clone() { DefaultIoFilterChainBuilder ret = new DefaultIoFilterChainBuilder(); for (Entry e : entries) { ret.addLast(e.getName(), e.getFilter()); } return ret; } private void checkBaseName(String baseName) { if (baseName == null) { throw new NullPointerException("baseName"); } if (!contains(baseName)) { throw new IllegalArgumentException("Unknown filter name: " + baseName); } } private void register(int index, Entry e) { if (contains(e.getName())) { throw new IllegalArgumentException( "Other filter is using the same name: " + e.getName()); } entries.add(index, e); } private static class EntryImpl implements Entry { private final String name; private final IoFilter filter; private EntryImpl(String name, IoFilter filter) { if (name == null) { throw new NullPointerException("name"); } if (filter == null) { throw new NullPointerException("filter"); } this.name = name; this.filter = filter; } public String getName() { return name; } public IoFilter getFilter() { return filter; } public NextFilter getNextFilter() { throw new IllegalStateException(); } public String toString() { return "(" + getName() + ':' + filter + ')'; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ConnectFuture.java0000644000175000017500000000445211002320023026505 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * An {@link IoFuture} for asynchronous connect requests. * *

Example

*
 * IoConnector connector = ...;
 * ConnectFuture future = connector.connect(...);
 * future.join(); // Wait until the connection attempt is finished.
 * IoSession session = future.getSession();
 * session.write(...);
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ConnectFuture extends IoFuture { /** * Returns {@link IoSession} which is the result of connect operation. * * @return null if the connect operation is not finished yet * @throws RuntimeIOException if connection attempt failed by an exception */ IoSession getSession() throws RuntimeIOException; /** * Returns true if the connect operation is finished successfully. */ boolean isConnected(); /** * Sets the newly connected session and notifies all threads waiting for * this future. This method is invoked by MINA internally. Please do not * call this method directly. */ void setSession(IoSession session); /** * Sets the exception caught due to connection failure and notifies all * threads waiting for this future. This method is invoked by MINA * internally. Please do not call this method directly. */ void setException(Throwable exception); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ByteBufferAllocator.java0000644000175000017500000000331411002320023027613 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * Allocates {@link ByteBuffer}s and manages them. Please implement this * interface if you need more advanced memory management scheme. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ByteBufferAllocator { /** * Returns the buffer which is capable of the specified size. * * @param capacity the capacity of the buffer * @param direct true to get a direct buffer, * false to get a heap buffer. */ ByteBuffer allocate(int capacity, boolean direct); /** * Wraps the specified NIO {@link java.nio.ByteBuffer} into MINA buffer. */ ByteBuffer wrap(java.nio.ByteBuffer nioBuffer); /** * Dispose of this allocator. */ void dispose(); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoAcceptor.java0000644000175000017500000000671211002320023025752 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.io.IOException; import java.net.SocketAddress; /** * Accepts incoming connection, communicates with clients, and fires events to * {@link IoHandler}s. *

* Please refer to * EchoServer * example. *

* You should bind to the desired socket address to accept incoming * connections, and then events for incoming connections will be sent to * the specified default {@link IoHandler}. *

* Threads accept incoming connections start automatically when * {@link #bind(SocketAddress, IoHandler)} is invoked, and stop when all * addresses are unbound. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoAcceptor extends IoService { /** * Binds to the specified address and handles incoming * connections with the specified handler. * * @throws IOException if failed to bind */ void bind(SocketAddress address, IoHandler handler) throws IOException; /** * Binds to the specified address and handles incoming * connections with the specified handler. * * @param config the configuration * @throws IOException if failed to bind */ void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException; /** * Unbinds from the specified address and disconnects all clients * connected there. */ void unbind(SocketAddress address); /** * Unbinds all addresses which were bound by this acceptor. */ void unbindAll(); /** * (Optional) Returns an {@link IoSession} that is bound to the specified * localAddress and remoteAddress which reuses * the localAddress that is already bound by {@link IoAcceptor} * via {@link #bind(SocketAddress, IoHandler)}. *

* This operation is optional. Please throw {@link UnsupportedOperationException} * if the transport type doesn't support this operation. This operation is * usually implemented for connectionless transport types. * * @throws UnsupportedOperationException if this operation is not supported * @throws IllegalArgumentException if the specified localAddress is * not bound yet. (see {@link #bind(SocketAddress, IoHandler)}) */ IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress); }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/BroadcastIoSession.java0000644000175000017500000000447111002320023027460 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; /** * An {@link IoSession} for broadcast transports. (e.g. UDP broadcast or multicast) * *

Writing Back to the Broadcasting Server

*

* When you implement a client that receives a broadcast message from a server * such as DHCP server, the client might need to send a response message for the * broadcast message the server sent. Because the remote address of the session * is not the address of the server in case of broadcasting, there should be a * way to specify the destination when you write the response message. * This interface provides {@link #write(Object, SocketAddress)} method so you * can specify the destination. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface BroadcastIoSession extends IoSession { /** * Writes the specified message to the specified destination. * This operation is asynchronous; {@link IoHandler#messageSent(IoSession, Object)} * will be invoked when the message is actually sent to remote peer. You can * also wait for the returned {@link WriteFuture} if you want to wait for * the message actually written. * * @param destination null if you want the message sent to the * default remote address */ WriteFuture write(Object message, SocketAddress destination); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/BufferDataException.java0000644000175000017500000000307511002320023027603 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * A {@link RuntimeException} which is thrown when the data the {@link ByteBuffer} * contains is corrupt. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * */ public class BufferDataException extends RuntimeException { private static final long serialVersionUID = -4138189188602563502L; public BufferDataException() { super(); } public BufferDataException(String message) { super(message); } public BufferDataException(String message, Throwable cause) { super(message, cause); } public BufferDataException(Throwable cause) { super(cause); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/WriteTimeoutException.java0000644000175000017500000000301111002320023030227 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.io.IOException; /** * An {@link IOException} which is thrown when write buffer is not flushed for * {@link IoSession#getWriteTimeout()} seconds. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class WriteTimeoutException extends IOException { private static final long serialVersionUID = 3906931157944579121L; /** * Creates a new exception. */ public WriteTimeoutException() { super(); } /** * Creates a new exception. */ public WriteTimeoutException(String s) { super(s); } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFilterLifeCycleException.java0000644000175000017500000000323211002320023031070 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * A {@link RuntimeException} which is thrown when {@link IoFilter#init()} * or {@link IoFilter#onPostAdd(IoFilterChain, String, org.apache.mina.common.IoFilter.NextFilter)} * failed. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoFilterLifeCycleException extends RuntimeException { private static final long serialVersionUID = -5542098881633506449L; public IoFilterLifeCycleException() { } public IoFilterLifeCycleException(String message) { super(message); } public IoFilterLifeCycleException(String message, Throwable cause) { super(message, cause); } public IoFilterLifeCycleException(Throwable cause) { super(cause); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoServiceListener.java0000644000175000017500000000601611002320023027315 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; import java.util.EventListener; /** * Something interested in being notified when the result * of an {@link IoFuture} becomes available. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoServiceListener extends EventListener { /** * Invoked when a new service is activated by an {@link IoService}. * * @param service the {@link IoService} * @param serviceAddress the socket address of the {@link IoService} listens * to manage sessions. If the service is an {@link IoAcceptor}, * it is a bind address. If the service is an {@link IoConnector}, * it is a remote address. * @param handler the {@link IoHandler} that serves the new service * @param config the {@link IoServiceConfig} of the new service */ void serviceActivated(IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config); /** * Invoked when a service is deactivated by an {@link IoService}. * * @param service the {@link IoService} * @param serviceAddress the socket address of the {@link IoService} listens * to manage sessions. If the service is an {@link IoAcceptor}, * it is a bind address. If the service is an {@link IoConnector}, * it is a remote address. * @param handler the {@link IoHandler} that serves the service * @param config the {@link IoServiceConfig} of the service */ void serviceDeactivated(IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config); /** * Invoked when a new session is created by an {@link IoService}. * * @param session the new session */ void sessionCreated(IoSession session); /** * Invoked when a session is being destroyed by an {@link IoService}. * * @param session the session to be destroyed */ void sessionDestroyed(IoSession session); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/TrafficMask.java0000644000175000017500000001037211002320023026111 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.nio.channels.SelectionKey; /** * A type-safe mask that is used to control the traffic of {@link IoSession} * with {@link IoSession#setTrafficMask(TrafficMask)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class TrafficMask { /** * This mask suspends both reads and writes. */ public static final TrafficMask NONE = new TrafficMask(0, "none"); /** * This mask suspends writes, and resumes reads if reads were suspended. */ public static final TrafficMask READ = new TrafficMask( SelectionKey.OP_READ, "read"); /** * This mask suspends reads, and resumes writes if writes were suspended. */ public static final TrafficMask WRITE = new TrafficMask( SelectionKey.OP_WRITE, "write"); /** * This mask resumes both reads and writes if any of them were suspended. */ public static final TrafficMask ALL = new TrafficMask(SelectionKey.OP_READ | SelectionKey.OP_WRITE, "all"); /** * Returns an appropriate {@link TrafficMask} instance from the * specified interestOps. * @see SelectionKey */ public static TrafficMask getInstance(int interestOps) { boolean read = (interestOps & SelectionKey.OP_READ) != 0; boolean write = (interestOps & SelectionKey.OP_WRITE) != 0; if (read) { if (write) { return ALL; } else { return READ; } } else if (write) { return WRITE; } else { return NONE; } } private final int interestOps; private final String name; private TrafficMask(int interestOps, String name) { this.interestOps = interestOps; this.name = name; } /** * Returns the name of this mask. */ public String getName() { return name; } /** * Returns true if this mask allows a read operation. */ public boolean isReadable() { return (interestOps & SelectionKey.OP_READ) != 0; } /** * Returns true if this mask allows a write operation. */ public boolean isWritable() { return (interestOps & SelectionKey.OP_WRITE) != 0; } /** * Returns an interestOps of {@link SelectionKey} for this mask. */ public int getInterestOps() { return interestOps; } /** * Peforms an AND operation on this mask with the specified * mask and returns the result. */ public TrafficMask and(TrafficMask mask) { return getInstance(interestOps & mask.interestOps); } /** * Peforms an OR operation on this mask with the specified * mask and returns the result. */ public TrafficMask or(TrafficMask mask) { return getInstance(interestOps | mask.interestOps); } /** * Returns a negated mask of this one. */ public TrafficMask not() { return getInstance(~interestOps); } /** * Peforms an XOR operation on this mask with the specified * mask and returns the result. */ public TrafficMask xor(TrafficMask mask) { return getInstance(interestOps ^ mask.interestOps); } public String toString() { return name; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoSessionRecycler.java0000644000175000017500000000512411002320023027322 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; /** * A connectionless transport can recycle existing sessions by assigning an * IoSessionRecyler to its {@link IoServiceConfig}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * TODO More documentation */ public interface IoSessionRecycler { /** * A dummy recycler that doesn't recycle any sessions. Using this recycler will * make all session lifecycle events to be fired for every I/O for all connectionless * sessions. */ static IoSessionRecycler NOOP = new IoSessionRecycler() { public void put(IoSession session) { } public IoSession recycle(SocketAddress localAddress, SocketAddress remoteAddress) { return null; } public void remove(IoSession session) { } }; /** * Called when the underlying transport creates or writes a new {@link IoSession}. * * @param session * the new {@link IoSession}. */ void put(IoSession session); /** * Attempts to retrieve a recycled {@link IoSession}. * * @param localAddress * the local socket address of the {@link IoSession} the * transport wants to recycle. * @param remoteAddress * the remote socket address of the {@link IoSession} the * transport wants to recycle. * @return a recycled {@link IoSession}, or null if one cannot be found. */ IoSession recycle(SocketAddress localAddress, SocketAddress remoteAddress); /** * Called when an {@link IoSession} is explicitly closed. * * @param session * the new {@link IoSession}. */ void remove(IoSession session); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/ExecutorThreadModel.java0000644000175000017500000001175211002320023027631 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.filter.executor.ExecutorFilter; import org.apache.mina.util.NamePreservingRunnable; /** * A {@link ThreadModel} which represents a thread model with an {@link Executor} * per service. The default underlying {@link Executor} is {@link ThreadPoolExecutor}, * so you can safely downcast the returned {@link Executor} of {@link #getExecutor()} to * {@link ThreadPoolExecutor} by default. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 588150 $, $Date: 2007-10-25 15:20:04 +0900 (Thu, 25 Oct 2007) $ */ public class ExecutorThreadModel implements ThreadModel { /** * Maps a service name to a PooledThreadModel instance. * Without this map, we might create extremely many thread pools that leads the system to * coma. */ private static final Map service2model = new HashMap(); /** * Returns a {@link ExecutorThreadModel} instance for the specified serviceName. * Please note that all returned instances will be managed globally; the same instance * will be returned if you specified the same service name. Please try to specify * different names for different services. * * @param serviceName the name of the service that needs thread pooling */ public static ExecutorThreadModel getInstance(String serviceName) { if (serviceName == null) { throw new NullPointerException("serviceName"); } ExecutorThreadModel model; synchronized (service2model) { model = service2model.get(serviceName); if (model == null) { model = new ExecutorThreadModel(serviceName); service2model.put(serviceName, model); } } return model; } private final String threadNamePrefix; private final ExecutorFilter defaultFilter; private ExecutorFilter filter = new ExecutorFilter(); private ExecutorThreadModel(String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; // Create the default filter defaultFilter = new ExecutorFilter(); ThreadPoolExecutor tpe = (ThreadPoolExecutor) defaultFilter .getExecutor(); final ThreadFactory originalThreadFactory = tpe.getThreadFactory(); ThreadFactory newThreadFactory = new ThreadFactory() { private final AtomicInteger threadId = new AtomicInteger(0); public Thread newThread(Runnable runnable) { Thread t = originalThreadFactory.newThread( new NamePreservingRunnable( runnable, ExecutorThreadModel.this.threadNamePrefix + '-' + threadId.incrementAndGet())); t.setDaemon(true); return t; } }; tpe.setThreadFactory(newThreadFactory); // Set to default. setExecutor(null); } /** * Returns the underlying {@link Executor} of this model. * You can change various properties such as the number of threads * by calling methods of the {@link Executor} implementation. */ public Executor getExecutor() { return filter.getExecutor(); } /** * Changes the underlying {@link Executor} of this model. * Previous settings such as the number of threads should be configured again. * Only newly created {@link IoSession}s will be affected. * * @param executor null to revert to the default setting */ public void setExecutor(Executor executor) { if (executor == null) { filter = defaultFilter; } else { filter = new ExecutorFilter(executor); } } public void buildFilterChain(IoFilterChain chain) throws Exception { chain.addFirst(ExecutorThreadModel.class.getName(), filter); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/common/IoFilterAdapter.java0000644000175000017500000000650111002320023026734 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; /** * An abstract adapter class for {@link IoFilter}. You can extend * this class and selectively override required event filter methods only. All * methods forwards events to the next filter by default. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoFilterAdapter implements IoFilter { public void init() throws Exception { } public void destroy() throws Exception { } public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { } public void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { } public void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { } public void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { } public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.sessionCreated(session); } public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.sessionOpened(session); } public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.sessionClosed(session); } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { nextFilter.sessionIdle(session, status); } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception { nextFilter.exceptionCaught(session, cause); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { nextFilter.messageReceived(session, message); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception { nextFilter.messageSent(session, message); } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { nextFilter.filterWrite(session, writeRequest); } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.filterClose(session); } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/0000755000175000017500000000000011044712500023211 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/chain/0000755000175000017500000000000011044712500024273 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/chain/package.html0000644000175000017500000000034711002320030026543 0ustar drazzibdrazzib A handler implementation that helps you implement sequentially layered protocols using Chains of Responsibility pattern. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/chain/IoHandlerCommand.java0000644000175000017500000001016411002320030030267 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.chain; import org.apache.mina.common.IoSession; /** *

A {@link IoHandlerCommand} encapsulates a unit of processing work to be * performed, whose purpose is to examine and/or modify the state of a * transaction that is represented by custom attributes provided by * {@link IoSession}. Individual {@link IoHandlerCommand}s can be assembled into * a {@link IoHandlerChain}, which allows them to either complete the * required processing or delegate further processing to the next * {@link IoHandlerCommand} in the {@link IoHandlerChain}.

* *

{@link IoHandlerCommand} implementations typically retrieve and store state * information in the {@link IoSession} that is passed as a parameter to * the {@link #execute(NextCommand,IoSession,Object)} method, using custom * session attributes. If you think getting attributes is tedious process, * you can create a bean which contains getters and setters of all properties * and store the bean as a session attribute:

* *
 * public class MyContext {
 *   public String getPropertyX() { ... };
 *   public void setPropertyX(String propertyX) { ... };
 *   public int getPropertyZ() { ... };
 *   public void setPropertyZ(int propertyZ) { ... };
 * }
 * 
 * public class MyHandlderCommand implements IoHandlerCommand {
 *   public void execute( NextCommand next, IoSession session, Object message ) throws Exception {
 *     MyContext ctx = session.getAttribute( "mycontext" );
 *     ...
 *   }
 * }
 * 
* * @author Apache Directory Project * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoHandlerCommand { /** *

Execute a unit of processing work to be performed. This * {@link IoHandlerCommand} may either complete the required processing * and just return to stop the processing, or delegate remaining * processing to the next {@link IoHandlerCommand} in a {@link IoHandlerChain} * containing this {@link IoHandlerCommand} by calling * {@link NextCommand#execute(IoSession,Object)}. * * @param next an indirect reference to the next {@link IoHandlerCommand} that * provides a way to forward the request to the next {@link IoHandlerCommand}. * @param session the {@link IoSession} which is associated with * this request * @param message the message object of this request * * @exception Exception general purpose exception return * to indicate abnormal termination */ void execute(NextCommand next, IoSession session, Object message) throws Exception; /** * Represents an indirect reference to the next {@link IoHandlerCommand} of * the {@link IoHandlerChain}. This interface provides a way to forward * the request to the next {@link IoHandlerCommand}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface NextCommand { /** * Forwards the request to the next {@link IoHandlerCommand} in the * {@link IoHandlerChain}. */ void execute(IoSession session, Object message) throws Exception; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/chain/ChainedIoHandler.java0000644000175000017500000000464311002320030030251 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.chain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; /** * An {@link IoHandler} which executes an {@link IoHandlerChain} * on a messageReceived event. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ChainedIoHandler extends IoHandlerAdapter { private final IoHandlerChain chain; /** * Creates a new instance which contains an empty {@link IoHandlerChain}. */ public ChainedIoHandler() { chain = new IoHandlerChain(); } /** * Creates a new instance which executes the specified * {@link IoHandlerChain} on a messageReceived event. * * @param chain an {@link IoHandlerChain} to execute */ public ChainedIoHandler(IoHandlerChain chain) { if (chain == null) { throw new NullPointerException("chain"); } this.chain = chain; } /** * Returns the {@link IoHandlerCommand} this handler will use to * handle messageReceived events. */ public IoHandlerChain getChain() { return chain; } /** * Handles the specified messageReceived event with the * {@link IoHandlerCommand} or {@link IoHandlerChain} you specified * in the constructor. */ public void messageReceived(IoSession session, Object message) throws Exception { chain.execute(null, session, message); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/chain/IoHandlerChain.java0000644000175000017500000002327711002320030027744 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.chain; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.mina.common.IoSession; /** * A chain of {@link IoHandlerCommand}s. * * @author Apache Directory Project * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoHandlerChain implements IoHandlerCommand { private static volatile int nextId = 0; private final int id = nextId++; private final String NEXT_COMMAND = IoHandlerChain.class.getName() + '.' + id + ".nextCommand"; private final Map name2entry = new HashMap(); private final Entry head; private final Entry tail; /** * Creates a new, empty chain of {@link IoHandlerCommand}s. */ public IoHandlerChain() { head = new Entry(null, null, "head", createHeadCommand()); tail = new Entry(head, null, "tail", createTailCommand()); head.nextEntry = tail; } private IoHandlerCommand createHeadCommand() { return new IoHandlerCommand() { public void execute(NextCommand next, IoSession session, Object message) throws Exception { next.execute(session, message); } }; } private IoHandlerCommand createTailCommand() { return new IoHandlerCommand() { public void execute(NextCommand next, IoSession session, Object message) throws Exception { next = (NextCommand) session.getAttribute(NEXT_COMMAND); if (next != null) { next.execute(session, message); } } }; } public Entry getEntry(String name) { Entry e = name2entry.get(name); if (e == null) { return null; } return e; } public IoHandlerCommand get(String name) { Entry e = getEntry(name); if (e == null) { return null; } return e.getCommand(); } public NextCommand getNextCommand(String name) { Entry e = getEntry(name); if (e == null) { return null; } return e.getNextCommand(); } public synchronized void addFirst(String name, IoHandlerCommand command) { checkAddable(name); register(head, name, command); } public synchronized void addLast(String name, IoHandlerCommand command) { checkAddable(name); register(tail.prevEntry, name, command); } public synchronized void addBefore(String baseName, String name, IoHandlerCommand command) { Entry baseEntry = checkOldName(baseName); checkAddable(name); register(baseEntry.prevEntry, name, command); } public synchronized void addAfter(String baseName, String name, IoHandlerCommand command) { Entry baseEntry = checkOldName(baseName); checkAddable(name); register(baseEntry, name, command); } public synchronized IoHandlerCommand remove(String name) { Entry entry = checkOldName(name); deregister(entry); return entry.getCommand(); } public synchronized void clear() throws Exception { Iterator it = new ArrayList(name2entry.keySet()) .iterator(); while (it.hasNext()) { this.remove(it.next()); } } private void register(Entry prevEntry, String name, IoHandlerCommand command) { Entry newEntry = new Entry(prevEntry, prevEntry.nextEntry, name, command); prevEntry.nextEntry.prevEntry = newEntry; prevEntry.nextEntry = newEntry; name2entry.put(name, newEntry); } private void deregister(Entry entry) { Entry prevEntry = entry.prevEntry; Entry nextEntry = entry.nextEntry; prevEntry.nextEntry = nextEntry; nextEntry.prevEntry = prevEntry; name2entry.remove(entry.name); } /** * Throws an exception when the specified filter name is not registered in this chain. * * @return An filter entry with the specified name. */ private Entry checkOldName(String baseName) { Entry e = name2entry.get(baseName); if (e == null) { throw new IllegalArgumentException("Unknown filter name:" + baseName); } return e; } /** * Checks the specified filter name is already taken and throws an exception if already taken. */ private void checkAddable(String name) { if (name2entry.containsKey(name)) { throw new IllegalArgumentException( "Other filter is using the same name '" + name + "'"); } } public void execute(NextCommand next, IoSession session, Object message) throws Exception { if (next != null) { session.setAttribute(NEXT_COMMAND, next); } try { callNextCommand(head, session, message); } finally { session.removeAttribute(NEXT_COMMAND); } } private void callNextCommand(Entry entry, IoSession session, Object message) throws Exception { entry.getCommand().execute(entry.getNextCommand(), session, message); } public List getAll() { List list = new ArrayList(); Entry e = head.nextEntry; while (e != tail) { list.add(e); e = e.nextEntry; } return list; } public List getAllReversed() { List list = new ArrayList(); Entry e = tail.prevEntry; while (e != head) { list.add(e); e = e.prevEntry; } return list; } public boolean contains(String name) { return getEntry(name) != null; } public boolean contains(IoHandlerCommand command) { Entry e = head.nextEntry; while (e != tail) { if (e.getCommand() == command) { return true; } e = e.nextEntry; } return false; } public boolean contains(Class commandType) { Entry e = head.nextEntry; while (e != tail) { if (commandType.isAssignableFrom(e.getCommand().getClass())) { return true; } e = e.nextEntry; } return false; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{ "); boolean empty = true; Entry e = head.nextEntry; while (e != tail) { if (!empty) { buf.append(", "); } else { empty = false; } buf.append('('); buf.append(e.getName()); buf.append(':'); buf.append(e.getCommand()); buf.append(')'); e = e.nextEntry; } if (empty) { buf.append("empty"); } buf.append(" }"); return buf.toString(); } /** * Represents a name-command pair that an {@link IoHandlerChain} contains. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Entry { private Entry prevEntry; private Entry nextEntry; private final String name; private final IoHandlerCommand command; private final NextCommand nextCommand; private Entry(Entry prevEntry, Entry nextEntry, String name, IoHandlerCommand command) { if (command == null) { throw new NullPointerException("command"); } if (name == null) { throw new NullPointerException("name"); } this.prevEntry = prevEntry; this.nextEntry = nextEntry; this.name = name; this.command = command; this.nextCommand = new NextCommand() { public void execute(IoSession session, Object message) throws Exception { Entry nextEntry = Entry.this.nextEntry; callNextCommand(nextEntry, session, message); } }; } /** * Returns the name of the command. */ public String getName() { return name; } /** * Returns the command. */ public IoHandlerCommand getCommand() { return command; } /** * Returns the {@link IoHandlerCommand.NextCommand} of the command. */ public NextCommand getNextCommand() { return nextCommand; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/StreamIoHandler.java0000644000175000017500000001302711002320030027063 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketTimeoutException; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.handler.support.IoSessionInputStream; import org.apache.mina.handler.support.IoSessionOutputStream; import org.apache.mina.util.SessionLog; /** * A {@link IoHandler} that adapts asynchronous MINA events to stream I/O. *

* Please extend this class and implement * {@link #processStreamIo(IoSession, InputStream, OutputStream)} to * execute your stream I/O logic; please note that you must forward * the process request to other thread or thread pool. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class StreamIoHandler extends IoHandlerAdapter { private static final String KEY_IN = StreamIoHandler.class.getName() + ".in"; private static final String KEY_OUT = StreamIoHandler.class.getName() + ".out"; private int readTimeout; private int writeTimeout; protected StreamIoHandler() { } /** * Implement this method to execute your stream I/O logic; * please note that you must forward the process request to other * thread or thread pool. */ protected abstract void processStreamIo(IoSession session, InputStream in, OutputStream out); /** * Returns read timeout in seconds. * The default value is 0 (disabled). */ public int getReadTimeout() { return readTimeout; } /** * Sets read timeout in seconds. * The default value is 0 (disabled). */ public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } /** * Returns write timeout in seconds. * The default value is 0 (disabled). */ public int getWriteTimeout() { return writeTimeout; } /** * Sets write timeout in seconds. * The default value is 0 (disabled). */ public void setWriteTimeout(int writeTimeout) { this.writeTimeout = writeTimeout; } /** * Initializes streams and timeout settings. */ public void sessionOpened(IoSession session) { // Set timeouts session.setWriteTimeout(writeTimeout); session.setIdleTime(IdleStatus.READER_IDLE, readTimeout); // Create streams InputStream in = new IoSessionInputStream(); OutputStream out = new IoSessionOutputStream(session); session.setAttribute(KEY_IN, in); session.setAttribute(KEY_OUT, out); processStreamIo(session, in, out); } /** * Closes streams */ public void sessionClosed(IoSession session) throws Exception { final InputStream in = (InputStream) session.getAttribute(KEY_IN); final OutputStream out = (OutputStream) session.getAttribute(KEY_OUT); try { in.close(); } finally { out.close(); } } /** * Forwards read data to input stream. */ public void messageReceived(IoSession session, Object buf) { final IoSessionInputStream in = (IoSessionInputStream) session .getAttribute(KEY_IN); in.write((ByteBuffer) buf); } /** * Forwards caught exceptions to input stream. */ public void exceptionCaught(IoSession session, Throwable cause) { final IoSessionInputStream in = (IoSessionInputStream) session .getAttribute(KEY_IN); IOException e = null; if (cause instanceof StreamIoException) { e = (IOException) cause.getCause(); } else if (cause instanceof IOException) { e = (IOException) cause; } if (e != null && in != null) { in.throwException(e); } else { SessionLog.warn(session, "Unexpected exception.", cause); session.close(); } } /** * Handles read timeout. */ public void sessionIdle(IoSession session, IdleStatus status) { if (status == IdleStatus.READER_IDLE) { throw new StreamIoException(new SocketTimeoutException( "Read timeout")); } } private static class StreamIoException extends RuntimeException { private static final long serialVersionUID = 3976736960742503222L; public StreamIoException(IOException cause) { super(cause); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/package.html0000644000175000017500000000023011002320030025450 0ustar drazzibdrazzib Useful IoHandler implementations. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/0000755000175000017500000000000011044712500025064 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandlerFactory.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandlerFactory.ja0000644000175000017500000000272211002320030033271 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.multiton; import org.apache.mina.common.IoSession; /** * A factory that creates {@link SingleSessionIoHandler} to be used with one * particular session. * * @see SingleSessionIoHandler * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface SingleSessionIoHandlerFactory { /** * Returns a {@link SingleSessionIoHandler} for the given session. * * @param session the session for which a handler is requested */ SingleSessionIoHandler getHandler(IoSession session); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/package.html0000644000175000017500000000043111002320030027326 0ustar drazzibdrazzib Enables creating a handler per session instead of having one handler for many sessions, using Multiton pattern. ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandlerAdapter.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandlerAdapter.ja0000644000175000017500000000504611002320030033244 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.multiton; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoSession; import org.apache.mina.util.SessionUtil; /** * Adapter class for implementors of the {@link SingleSessionIoHandler} * interface. The session to which the handler is assigned is accessible * through the {@link #getSession()} method. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SingleSessionIoHandlerAdapter implements SingleSessionIoHandler { /** * The session to which the handler is assigned. */ private final IoSession session; /** * Creates a new instance that is assigned to the passed in session. * * @param session the session to which the handler is assigned */ public SingleSessionIoHandlerAdapter(IoSession session) { if (session == null) { throw new NullPointerException("session"); } this.session = session; } /** * Retrieves the session to which this handler is assigned. * * @return the session */ protected IoSession getSession() { return session; } public void exceptionCaught(Throwable th) throws Exception { } public void messageReceived(Object message) throws Exception { } public void messageSent(Object message) throws Exception { } public void sessionClosed() throws Exception { } public void sessionCreated() throws Exception { SessionUtil.initialize(getSession()); } public void sessionIdle(IdleStatus status) throws Exception { } public void sessionOpened() throws Exception { } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandler.java0000644000175000017500000000725111002320030032272 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.multiton; import java.io.IOException; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; /** * A session handler without an {@link IoSession} parameter for simplicity. *

* A {@link SingleSessionIoHandler} is similar to an {@link IoHandler} with * the notable difference that a {@link SingleSessionIoHandler} is used only * by one session at a time. Thus, there is no {@link IoSession} parameter in * the methods of this interface. *

*

* Because events are passed to the session in order, it is possible to store * conversational state as instance variables in this object. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface SingleSessionIoHandler { /** * Invoked when the session is created. Initialize default socket parameters * and user-defined attributes here. * * @throws Exception * @see IoHandler#sessionCreated(IoSession) */ void sessionCreated() throws Exception; /** * Invoked when the connection is opened. This method is not invoked if the * transport type is UDP. * * @see IoHandler#sessionOpened(IoSession) */ void sessionOpened() throws Exception; /** * Invoked when the connection is closed. This method is not invoked if the * transport type is UDP. * * @see IoHandler#sessionClosed(IoSession) */ void sessionClosed() throws Exception; /** * Invoked when the connection is idle. Refer to {@link IdleStatus}. This * method is not invoked if the transport type is UDP. * * @param status the type of idleness * @see IoHandler#sessionIdle(IoSession, IdleStatus) */ void sessionIdle(IdleStatus status) throws Exception; /** * Invoked when any exception is thrown by user {@link IoHandler} * implementation or by MINA. If cause is instanceof * {@link IOException}, MINA will close the connection automatically. * * @param cause the caught exception * @see IoHandler#exceptionCaught(IoSession, Throwable) */ void exceptionCaught(Throwable cause) throws Exception; /** * Invoked when protocol message is received. Implement your protocol flow * here. * * @param message the received message * @see IoHandler#messageReceived(IoSession, Object) */ void messageReceived(Object message) throws Exception; /** * Invoked when protocol message that user requested by * {@link IoSession#write(Object)} is sent out actually. * * @param message the sent message * @see IoHandler#messageSent(IoSession, Object) */ void messageSent(Object message) throws Exception; } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandlerDelegate.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/multiton/SingleSessionIoHandlerDelegate.j0000644000175000017500000001237211002320030033235 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.multiton; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; /** * An {@link IoHandler} implementation which delegates all requests to * {@link SingleSessionIoHandler}s. A {@link SingleSessionIoHandlerFactory} * is used to create a new {@link SingleSessionIoHandler} for each newly * created session. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SingleSessionIoHandlerDelegate implements IoHandler { /** * The key used to store the {@link SingleSessionIoHandler} as a session * attribute. */ public static final String HANDLER = SingleSessionIoHandlerDelegate.class .getName() + ".handler"; /** * The {@link SingleSessionIoHandlerFactory} used to create new * {@link SingleSessionIoHandler}s. */ private final SingleSessionIoHandlerFactory factory; /** * Creates a new instance that uses the passed in * {@link SingleSessionIoHandlerFactory} to create new * {@link SingleSessionIoHandler}s. * * @param factory the factory for {@link SingleSessionIoHandler}s */ public SingleSessionIoHandlerDelegate(SingleSessionIoHandlerFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } this.factory = factory; } /** * Creates a new instance with the factory passed to the constructor of * this class. The created handler is stored as a session * attribute named {@link #HANDLER}. * * @see org.apache.mina.common.IoHandler#sessionCreated(org.apache.mina.common.IoSession) */ public void sessionCreated(IoSession session) throws Exception { SingleSessionIoHandler handler = factory.getHandler(session); session.setAttribute(HANDLER, handler); handler.sessionCreated(); } /** * Delegates the method call to the * {@link SingleSessionIoHandler#sessionOpened()} method of the handler * assigned to this session. */ public void sessionOpened(IoSession session) throws Exception { SingleSessionIoHandler handler = (SingleSessionIoHandler) session .getAttribute(HANDLER); handler.sessionOpened(); } /** * Delegates the method call to the * {@link SingleSessionIoHandler#sessionClosed()} method of the handler * assigned to this session. */ public void sessionClosed(IoSession session) throws Exception { SingleSessionIoHandler handler = (SingleSessionIoHandler) session .getAttribute(HANDLER); handler.sessionClosed(); } /** * Delegates the method call to the * {@link SingleSessionIoHandler#sessionIdle(IdleStatus)} method of the * handler assigned to this session. */ public void sessionIdle(IoSession session, IdleStatus status) throws Exception { SingleSessionIoHandler handler = (SingleSessionIoHandler) session .getAttribute(HANDLER); handler.sessionIdle(status); } /** * Delegates the method call to the * {@link SingleSessionIoHandler#exceptionCaught(Throwable)} method of the * handler assigned to this session. */ public void exceptionCaught(IoSession session, Throwable cause) throws Exception { SingleSessionIoHandler handler = (SingleSessionIoHandler) session .getAttribute(HANDLER); handler.exceptionCaught(cause); } /** * Delegates the method call to the * {@link SingleSessionIoHandler#messageReceived(Object)} method of the * handler assigned to this session. */ public void messageReceived(IoSession session, Object message) throws Exception { SingleSessionIoHandler handler = (SingleSessionIoHandler) session .getAttribute(HANDLER); handler.messageReceived(message); } /** * Delegates the method call to the * {@link SingleSessionIoHandler#messageSent(Object)} method of the handler * assigned to this session. */ public void messageSent(IoSession session, Object message) throws Exception { SingleSessionIoHandler handler = (SingleSessionIoHandler) session .getAttribute(HANDLER); handler.messageSent(message); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/demux/0000755000175000017500000000000011044712500024333 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/demux/DemuxingIoHandler.java0000644000175000017500000001640411002320030030534 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.demux; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.util.IdentityHashSet; /** * A {@link IoHandler} that demuxes messageReceived events * to the appropriate {@link MessageHandler}. *

* You can freely register and deregister {@link MessageHandler}s using * {@link #addMessageHandler(Class, MessageHandler)} and * {@link #removeMessageHandler(Class)}. *

*

* When message is received through a call to * {@link #messageReceived(IoSession, Object)} the class of the * message object will be used to find a {@link MessageHandler} for * that particular message type. If no {@link MessageHandler} instance can be * found for the immediate class (i.e. message.getClass()) the * interfaces implemented by the immediate class will be searched in depth-first * order. If no match can be found for any of the interfaces the search will be * repeated recursively for the superclass of the immediate class * (i.e. message.getClass().getSuperclass()). *

*

* Consider the following type hierarchy (Cx are classes while * Ix are interfaces): *

 *     C3 - I7 - I9
 *      |    |   /\
 *      |   I8  I3 I4
 *      |
 *     C2 - I5 - I6
 *      |
 *     C1 - I1 - I2 - I4
 *      |         |
 *      |        I3
 *    Object          
 * 
* When message is of type C3 this hierarchy will be * searched in the following order: * C3, I7, I8, I9, I3, I4, C2, I5, I6, C1, I1, I2, I3, I4, Object. *

*

* For efficiency searches will be cached. Calls to * {@link #addMessageHandler(Class, MessageHandler)} and * {@link #removeMessageHandler(Class)} clear this cache. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DemuxingIoHandler extends IoHandlerAdapter { private final Map findHandlerCache = new ConcurrentHashMap(); private final Map type2handler = new ConcurrentHashMap(); /** * Creates a new instance with no registered {@link MessageHandler}s. */ public DemuxingIoHandler() { } /** * Registers a {@link MessageHandler} that receives the messages of * the specified type. * * @return the old handler if there is already a registered handler for * the specified type. null otherwise. */ @SuppressWarnings("unchecked") public MessageHandler addMessageHandler(Class type, MessageHandler handler) { findHandlerCache.clear(); return type2handler.put(type, handler); } /** * Deregisters a {@link MessageHandler} that receives the messages of * the specified type. * * @return the removed handler if successfully removed. null otherwise. */ @SuppressWarnings("unchecked") public MessageHandler removeMessageHandler(Class type) { findHandlerCache.clear(); return type2handler.remove(type); } /** * Returns the {@link MessageHandler} which is registered to process * the specified type. */ @SuppressWarnings("unchecked") public MessageHandler getMessageHandler(Class type) { return type2handler.get(type); } /** * Returns the {@link Map} which contains all messageType-{@link MessageHandler} * pairs registered to this handler. */ public Map getMessageHandlerMap() { return Collections.unmodifiableMap(type2handler); } /** * Forwards the received events into the appropriate {@link MessageHandler} * which is registered by {@link #addMessageHandler(Class, MessageHandler)}. */ public void messageReceived(IoSession session, Object message) throws Exception { MessageHandler handler = findHandler(message.getClass()); if (handler != null) { handler.messageReceived(session, message); } else { throw new UnknownMessageTypeException( "No message handler found for message: " + message); } } protected MessageHandler findHandler(Class type) { return findHandler(type, null); } @SuppressWarnings("unchecked") private MessageHandler findHandler(Class type, Set triedClasses) { MessageHandler handler = null; if (triedClasses != null && triedClasses.contains(type)) return null; /* * Try the cache first. */ handler = findHandlerCache.get(type); if (handler != null) return handler; /* * Try the registered handlers for an immediate match. */ handler = type2handler.get(type); if (handler == null) { /* * No immediate match could be found. Search the type's interfaces. */ if (triedClasses == null) triedClasses = new IdentityHashSet(); triedClasses.add(type); Class[] interfaces = type.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { handler = findHandler(interfaces[i], triedClasses); if (handler != null) break; } } if (handler == null) { /* * No match in type's interfaces could be found. Search the * superclass. */ Class superclass = type.getSuperclass(); if (superclass != null) handler = findHandler(superclass); } /* * Make sure the handler is added to the cache. By updating the cache * here all the types (superclasses and interfaces) in the path which * led to a match will be cached along with the immediate message type. */ if (handler != null) findHandlerCache.put(type, handler); return handler; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/demux/package.html0000644000175000017500000000037511002320030026604 0ustar drazzibdrazzib A handler implementation that helps you implement complex protocols by splitting messageReceived handlers into multiple sub-handlers. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/demux/MessageHandler.java0000644000175000017500000000356111002320030030050 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.demux; import org.apache.mina.common.IoSession; /** * A handler interface that {@link DemuxingIoHandler} forwards * messageReceived events to. You have to register your * handler with the type of message you want to get notified using * {@link DemuxingIoHandler#addMessageHandler(Class, MessageHandler)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface MessageHandler { /** * A {@link MessageHandler} that does nothing. This is usefule when * you want to ignore messages of the specific type silently. */ static MessageHandler NOOP = new MessageHandler() { public void messageReceived(IoSession session, Object message) { } }; /** * Invoked when the specific type of message is received from the * specified session. */ void messageReceived(IoSession session, E message) throws Exception; }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/demux/UnknownMessageTypeException.java0000644000175000017500000000342011002320030032645 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.demux; /** * An exception that is thrown when {@link DemuxingIoHandler} * cannot find any {@link MessageHandler}s associated with the specific * message type. You have to use * {@link DemuxingIoHandler#addMessageHandler(Class, MessageHandler)} * to associate a message type and a message handler. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class UnknownMessageTypeException extends RuntimeException { private static final long serialVersionUID = 3257290227428047158L; public UnknownMessageTypeException() { } public UnknownMessageTypeException(String message, Throwable cause) { super(message, cause); } public UnknownMessageTypeException(String message) { super(message); } public UnknownMessageTypeException(Throwable cause) { super(cause); } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/support/0000755000175000017500000000000011044712500024725 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/support/package.html0000644000175000017500000000026011002320030027167 0ustar drazzibdrazzib Internal classes used by org.apache.mina.handler package. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/support/IoSessionInputStream.java0000644000175000017500000001052011002320030031660 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.support; import java.io.IOException; import java.io.InputStream; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; /** * An {@link InputStream} that buffers data read from * {@link IoHandler#messageReceived(IoSession, Object)} events. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoSessionInputStream extends InputStream { private final Object mutex = new Object(); private final ByteBuffer buf; private volatile boolean closed; private volatile boolean released; private IOException exception; public IoSessionInputStream() { buf = ByteBuffer.allocate(16); buf.setAutoExpand(true); buf.limit(0); } public int available() { if (released) { return 0; } else { synchronized (mutex) { return buf.remaining(); } } } public void close() { if (closed) { return; } synchronized (mutex) { closed = true; releaseBuffer(); mutex.notifyAll(); } } public int read() throws IOException { synchronized (mutex) { if (!waitForData()) { return -1; } return buf.get() & 0xff; } } public int read(byte[] b, int off, int len) throws IOException { synchronized (mutex) { if (!waitForData()) { return -1; } int readBytes; if (len > buf.remaining()) { readBytes = buf.remaining(); } else { readBytes = len; } buf.get(b, off, readBytes); return readBytes; } } private boolean waitForData() throws IOException { if (released) { return false; } synchronized (mutex) { while (!released && buf.remaining() == 0 && exception == null) { try { mutex.wait(); } catch (InterruptedException e) { IOException ioe = new IOException( "Interrupted while waiting for more data"); ioe.initCause(e); throw ioe; } } } if (exception != null) { releaseBuffer(); throw exception; } if (closed && buf.remaining() == 0) { releaseBuffer(); return false; } return true; } private void releaseBuffer() { if (released) { return; } released = true; buf.release(); } public void write(ByteBuffer src) { synchronized (mutex) { if (closed) { return; } if (buf.hasRemaining()) { this.buf.compact(); this.buf.put(src); this.buf.flip(); } else { this.buf.clear(); this.buf.put(src); this.buf.flip(); mutex.notifyAll(); } } } public void throwException(IOException e) { synchronized (mutex) { if (exception == null) { exception = e; mutex.notifyAll(); } } } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/handler/support/IoSessionOutputStream.java0000644000175000017500000000523111002320030032064 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.support; import java.io.IOException; import java.io.OutputStream; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; /** * An {@link OutputStream} that forwards all write operations to * the associated {@link IoSession}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoSessionOutputStream extends OutputStream { private final IoSession session; private WriteFuture lastWriteFuture; public IoSessionOutputStream(IoSession session) { this.session = session; } @Override public void close() throws IOException { try { flush(); } finally { session.close().join(); } } private void checkClosed() throws IOException { if (!session.isConnected()) { throw new IOException("The session has been closed."); } } private synchronized void write(ByteBuffer buf) throws IOException { checkClosed(); lastWriteFuture = session.write(buf); } @Override public void write(byte[] b, int off, int len) throws IOException { write(ByteBuffer.wrap(b.clone(), off, len)); } @Override public void write(int b) throws IOException { ByteBuffer buf = ByteBuffer.allocate(1); buf.put((byte) b); buf.flip(); write(buf); } @Override public synchronized void flush() throws IOException { if (lastWriteFuture == null) { return; } lastWriteFuture.join(); if (!lastWriteFuture.isWritten()) { throw new IOException( "The bytes could not be written to the session"); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/0000755000175000017500000000000011044712500023061 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/ReadThrottleFilterBuilder.java0000644000175000017500000001543111002320021030771 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import java.util.Iterator; import java.util.List; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoFilterChain.Entry; import org.apache.mina.filter.executor.ExecutorFilter; /** * This filter will automatically disable reads on an IoSession once the data * batched for that session in the {@link ExecutorFilter} reaches a defined threshold (the * default is 1 megabytes). It accomplishes this by being in the filter chain before * and after the {@link ExecutorFilter}. It is possible to subvert the * behavior of this filter by adding filters immediately after the {@link ExecutorFilter} * after adding this filter. Thus, it is recommended to add this filter towards the end of * your filter chain construction, if you need to ensure that other filters need to be right * after the {@link ExecutorFilter} * *

Usage: * *


 * DefaultFilterChainBuilder builder = ...
 * ReadThrottleFilterBuilder filter = new ReadThrottleFilterBuilder();
 * filter.attach( builder );
 * 
* * or * *

 * IoFilterChain chain = ...
 * ReadThrottleFilterBuilder filter = new ReadThrottleFilterBuilder();
 * filter.attach( chain );
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 406554 $, $Date: 2006-05-15 06:46:02Z $ */ public class ReadThrottleFilterBuilder { public static final String COUNTER = ReadThrottleFilterBuilder.class .getName() + ".counter"; public static final String SUSPENDED_READS = ReadThrottleFilterBuilder.class .getName() + ".suspendedReads"; private volatile int maximumConnectionBufferSize = 1024 * 1024; // 1mb /** * Set the maximum amount of data to buffer in the ThreadPoolFilter prior to disabling * reads. Changing the value will only take effect when new data is received for a * connection, including existing connections. Default value is 1 megabytes. * * @param maximumConnectionBufferSize New buffer size. Must be > 0 */ public void setMaximumConnectionBufferSize(int maximumConnectionBufferSize) { this.maximumConnectionBufferSize = maximumConnectionBufferSize; } /** * Attach this filter to the specified filter chain. It will search for the ThreadPoolFilter, and attach itself * before and after that filter. * * @param chain {@link IoFilterChain} to attach self to. */ public void attach(IoFilterChain chain) { String name = getThreadPoolFilterEntryName(chain.getAll()); chain.addBefore(name, getClass().getName() + ".add", new Add()); chain.addAfter(name, getClass().getName() + ".release", new Release()); } /** * Attach this filter to the specified builder. It will search for the * {@link ExecutorFilter}, and attach itself before and after that filter. * * @param builder {@link DefaultIoFilterChainBuilder} to attach self to. */ public void attach(DefaultIoFilterChainBuilder builder) { String name = getThreadPoolFilterEntryName(builder.getAll()); builder.addBefore(name, getClass().getName() + ".add", new Add()); builder .addAfter(name, getClass().getName() + ".release", new Release()); } private String getThreadPoolFilterEntryName(List entries) { Iterator i = entries.iterator(); while (i.hasNext()) { IoFilterChain.Entry entry = i.next(); if (entry.getFilter().getClass().isAssignableFrom( ExecutorFilter.class)) { return entry.getName(); } } throw new IllegalStateException( "Chain does not contain a ExecutorFilter"); } private void add(IoSession session, int size) { synchronized (session) { int counter = getCounter(session) + size; session.setAttribute(COUNTER, new Integer(counter)); if (counter >= maximumConnectionBufferSize && session.getTrafficMask().isReadable()) { session.suspendRead(); session.setAttribute(SUSPENDED_READS); } } } private void release(IoSession session, int size) { synchronized (session) { int counter = Math.max(0, getCounter(session) - size); session.setAttribute(COUNTER, new Integer(counter)); if (counter < maximumConnectionBufferSize && isSuspendedReads(session)) { session.resumeRead(); session.removeAttribute(SUSPENDED_READS); } } } private boolean isSuspendedReads(IoSession session) { Boolean flag = (Boolean) session.getAttribute(SUSPENDED_READS); return null != flag && flag.booleanValue(); } private int getCounter(IoSession session) { Integer i = (Integer) session.getAttribute(COUNTER); return null == i ? 0 : i.intValue(); } private class Add extends IoFilterAdapter { public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (message instanceof ByteBuffer) { add(session, ((ByteBuffer) message).remaining()); } nextFilter.messageReceived(session, message); } } private class Release extends IoFilterAdapter { public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (message instanceof ByteBuffer) { release(session, ((ByteBuffer) message).remaining()); } nextFilter.messageReceived(session, message); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/package.html0000644000175000017500000000022711002320021025326 0ustar drazzibdrazzib Useful IoFilter implementations. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/LoggingFilter.java0000644000175000017500000000731711002320021026453 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.util.SessionLog; import org.slf4j.Logger; /** * Logs all MINA protocol events to {@link Logger}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ * * @see SessionLog */ public class LoggingFilter extends IoFilterAdapter { /** * Session attribute key: prefix string */ public static final String PREFIX = SessionLog.PREFIX; /** * Session attribute key: {@link Logger} */ public static final String LOGGER = SessionLog.LOGGER; /** * Creates a new instance. */ public LoggingFilter() { } public void sessionCreated(NextFilter nextFilter, IoSession session) { SessionLog.info(session, "CREATED"); nextFilter.sessionCreated(session); } public void sessionOpened(NextFilter nextFilter, IoSession session) { SessionLog.info(session, "OPENED"); nextFilter.sessionOpened(session); } public void sessionClosed(NextFilter nextFilter, IoSession session) { SessionLog.info(session, "CLOSED"); nextFilter.sessionClosed(session); } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) { if (SessionLog.isInfoEnabled(session)) { SessionLog.info(session, "IDLE: " + status); } nextFilter.sessionIdle(session, status); } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) { if (SessionLog.isWarnEnabled(session)) { SessionLog.warn(session, "EXCEPTION:", cause); } nextFilter.exceptionCaught(session, cause); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) { if (SessionLog.isInfoEnabled(session)) { SessionLog.info(session, "RECEIVED: " + message); } nextFilter.messageReceived(session, message); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) { if (SessionLog.isInfoEnabled(session)) { SessionLog.info(session, "SENT: " + message); } nextFilter.messageSent(session, message); } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) { if (SessionLog.isInfoEnabled(session)) { SessionLog.info(session, "WRITE: " + writeRequest); } nextFilter.filterWrite(session, writeRequest); } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { SessionLog.info(session, "CLOSE"); nextFilter.filterClose(session); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/StreamWriteFilter.java0000644000175000017500000001634311002320021027332 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import java.io.IOException; import java.io.InputStream; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; /** * Filter implementation which makes it possible to write {@link InputStream} * objects directly using {@link IoSession#write(Object)}. When an * {@link InputStream} is written to a session this filter will read the bytes * from the stream into {@link ByteBuffer} objects and write those buffers * to the next filter. When end of stream has been reached this filter will * call {@link NextFilter#messageSent(IoSession, Object)} using the original * {@link InputStream} written to the session and notifies * {@link org.apache.mina.common.WriteFuture} on the * original {@link org.apache.mina.common.IoFilter.WriteRequest}. *

* This filter will ignore written messages which aren't {@link InputStream} * instances. Such messages will be passed to the next filter directly. *

*

* NOTE: this filter does not close the stream after all data from stream * has been written. The {@link org.apache.mina.common.IoHandler} should take * care of that in its * {@link org.apache.mina.common.IoHandler#messageSent(IoSession, Object)} * callback. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class StreamWriteFilter extends IoFilterAdapter { /** * The default buffer size this filter uses for writing. */ public static final int DEFAULT_STREAM_BUFFER_SIZE = 4096; /** * The attribute name used when binding the {@link InputStream} to the session. */ public static final String CURRENT_STREAM = StreamWriteFilter.class .getName() + ".stream"; protected static final String WRITE_REQUEST_QUEUE = StreamWriteFilter.class .getName() + ".queue"; protected static final String INITIAL_WRITE_FUTURE = StreamWriteFilter.class .getName() + ".future"; private int writeBufferSize = DEFAULT_STREAM_BUFFER_SIZE; @Override public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { // If we're already processing a stream we need to queue the WriteRequest. if (session.getAttribute(CURRENT_STREAM) != null) { Queue queue = getWriteRequestQueue(session); if (queue == null) { queue = new ConcurrentLinkedQueue(); session.setAttribute(WRITE_REQUEST_QUEUE, queue); } queue.add(writeRequest); return; } Object message = writeRequest.getMessage(); if (message instanceof InputStream) { InputStream inputStream = (InputStream) message; ByteBuffer byteBuffer = getNextByteBuffer(inputStream); if (byteBuffer == null) { // End of stream reached. writeRequest.getFuture().setWritten(true); nextFilter.messageSent(session, message); } else { session.setAttribute(CURRENT_STREAM, inputStream); session.setAttribute(INITIAL_WRITE_FUTURE, writeRequest .getFuture()); nextFilter.filterWrite(session, new WriteRequest(byteBuffer)); } } else { nextFilter.filterWrite(session, writeRequest); } } @SuppressWarnings("unchecked") private Queue getWriteRequestQueue(IoSession session) { return (Queue) session.getAttribute(WRITE_REQUEST_QUEUE); } @Override public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception { InputStream inputStream = (InputStream) session .getAttribute(CURRENT_STREAM); if (inputStream == null) { nextFilter.messageSent(session, message); } else { ByteBuffer byteBuffer = getNextByteBuffer(inputStream); if (byteBuffer == null) { // End of stream reached. session.removeAttribute(CURRENT_STREAM); WriteFuture writeFuture = (WriteFuture) session .removeAttribute(INITIAL_WRITE_FUTURE); // Write queued WriteRequests. Queue queue = (Queue) session .removeAttribute(WRITE_REQUEST_QUEUE); if (queue != null) { WriteRequest wr = queue.poll(); while (wr != null) { filterWrite(nextFilter, session, wr); wr = queue.poll(); } } writeFuture.setWritten(true); nextFilter.messageSent(session, inputStream); } else { nextFilter.filterWrite(session, new WriteRequest(byteBuffer)); } } } private ByteBuffer getNextByteBuffer(InputStream is) throws IOException { byte[] bytes = new byte[writeBufferSize]; int off = 0; int n = 0; while (off < bytes.length && (n = is.read(bytes, off, bytes.length - off)) != -1) { off += n; } if (n == -1 && off == 0) { return null; } return ByteBuffer.wrap(bytes, 0, off); } /** * Returns the size of the write buffer in bytes. Data will be read from the * stream in chunks of this size and then written to the next filter. * * @return the write buffer size. */ public int getWriteBufferSize() { return writeBufferSize; } /** * Sets the size of the write buffer in bytes. Data will be read from the * stream in chunks of this size and then written to the next filter. * * @throws IllegalArgumentException if the specified size is < 1. */ public void setWriteBufferSize(int writeBufferSize) { if (writeBufferSize < 1) { throw new IllegalArgumentException( "writeBufferSize must be at least 1"); } this.writeBufferSize = writeBufferSize; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/ReferenceCountingIoFilter.java0000644000175000017500000001027611002320021030760 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; /** * An {@link IoFilter}s wrapper that keeps track of the number of usages of this filter and will call init/destroy * when the filter is not in use. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class ReferenceCountingIoFilter implements IoFilter { private final IoFilter filter; private int count = 0; public ReferenceCountingIoFilter(IoFilter filter) { this.filter = filter; } public void init() throws Exception { // no-op, will init on-demand in pre-add if count == 0 } public void destroy() throws Exception { //no-op, will destroy on-demand in post-remove if count == 0 } public synchronized void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { if (0 == count) { filter.init(); ++count; } filter.onPreAdd(parent, name, nextFilter); } public synchronized void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { filter.onPostRemove(parent, name, nextFilter); --count; if (0 == count) { filter.destroy(); } } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception { filter.exceptionCaught(nextFilter, session, cause); } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { filter.filterClose(nextFilter, session); } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { filter.filterWrite(nextFilter, session, writeRequest); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { filter.messageReceived(nextFilter, session, message); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception { filter.messageSent(nextFilter, session, message); } public void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { filter.onPostAdd(parent, name, nextFilter); } public void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { filter.onPreRemove(parent, name, nextFilter); } public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { filter.sessionClosed(nextFilter, session); } public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { filter.sessionCreated(nextFilter, session); } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { filter.sessionIdle(nextFilter, session, status); } public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception { filter.sessionOpened(nextFilter, session); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/executor/0000755000175000017500000000000011044712500024717 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/executor/ExecutorFilter.java0000644000175000017500000002137111002320021030515 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.executor; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A filter that forward events to {@link Executor} in * backport-util-concurrent. * You can apply various thread model by inserting this filter to the {@link IoFilterChain}. *

* Please note that this filter doesn't manage the life cycle of the underlying * {@link Executor}. You have to destroy or stop it by yourself. * * @author The Apache MINA Project (dev@mina.apache.org) * @version $Rev: 350169 $, $Date: 2005-12-01 00:17:41 -0500 (Thu, 01 Dec 2005) $ */ public class ExecutorFilter extends IoFilterAdapter { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Executor executor; /** * Creates a new instace with the default thread pool implementation * (new ThreadPoolExecutor(16, 16, 60, TimeUnit.SECONDS, new LinkedBlockingQueue() )). */ public ExecutorFilter() { this(new ThreadPoolExecutor(16, 16, 60, TimeUnit.SECONDS, new LinkedBlockingQueue())); } /** * Creates a new instance with the specified executor. */ public ExecutorFilter(Executor executor) { if (executor == null) { throw new NullPointerException("executor"); } this.executor = executor; } /** * Returns the underlying {@link Executor} instance this filter uses. */ public Executor getExecutor() { return executor; } private void fireEvent(NextFilter nextFilter, IoSession session, EventType type, Object data) { Event event = new Event(type, nextFilter, data); SessionBuffer buf = SessionBuffer.getSessionBuffer(session); boolean execute; synchronized (buf.eventQueue) { buf.eventQueue.offer(event); if (buf.processingCompleted) { buf.processingCompleted = false; execute = true; } else { execute = false; } } if (execute) { if (logger.isDebugEnabled()) { logger.debug("Launching thread for " + session.getRemoteAddress()); } executor.execute(new ProcessEventsRunnable(buf)); } } private static class SessionBuffer { private static final String KEY = SessionBuffer.class.getName() + ".KEY"; private static SessionBuffer getSessionBuffer(IoSession session) { synchronized (session) { SessionBuffer buf = (SessionBuffer) session.getAttribute(KEY); if (buf == null) { buf = new SessionBuffer(session); session.setAttribute(KEY, buf); } return buf; } } private final IoSession session; private final Queue eventQueue = new LinkedList(); private boolean processingCompleted = true; private SessionBuffer(IoSession session) { this.session = session; } } protected static class EventType { public static final EventType OPENED = new EventType("OPENED"); public static final EventType CLOSED = new EventType("CLOSED"); public static final EventType READ = new EventType("READ"); public static final EventType WRITTEN = new EventType("WRITTEN"); public static final EventType RECEIVED = new EventType("RECEIVED"); public static final EventType SENT = new EventType("SENT"); public static final EventType IDLE = new EventType("IDLE"); public static final EventType EXCEPTION = new EventType("EXCEPTION"); private final String value; private EventType(String value) { this.value = value; } public String toString() { return value; } } protected static class Event { private final EventType type; private final NextFilter nextFilter; private final Object data; Event(EventType type, NextFilter nextFilter, Object data) { this.type = type; this.nextFilter = nextFilter; this.data = data; } public Object getData() { return data; } public NextFilter getNextFilter() { return nextFilter; } public EventType getType() { return type; } } public void sessionCreated(NextFilter nextFilter, IoSession session) { nextFilter.sessionCreated(session); } public void sessionOpened(NextFilter nextFilter, IoSession session) { fireEvent(nextFilter, session, EventType.OPENED, null); } public void sessionClosed(NextFilter nextFilter, IoSession session) { fireEvent(nextFilter, session, EventType.CLOSED, null); } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) { fireEvent(nextFilter, session, EventType.IDLE, status); } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) { fireEvent(nextFilter, session, EventType.EXCEPTION, cause); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) { fireEvent(nextFilter, session, EventType.RECEIVED, message); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) { fireEvent(nextFilter, session, EventType.SENT, message); } protected void processEvent(NextFilter nextFilter, IoSession session, EventType type, Object data) { if (type == EventType.RECEIVED) { nextFilter.messageReceived(session, data); } else if (type == EventType.SENT) { nextFilter.messageSent(session, data); } else if (type == EventType.EXCEPTION) { nextFilter.exceptionCaught(session, (Throwable) data); } else if (type == EventType.IDLE) { nextFilter.sessionIdle(session, (IdleStatus) data); } else if (type == EventType.OPENED) { nextFilter.sessionOpened(session); } else if (type == EventType.CLOSED) { nextFilter.sessionClosed(session); } } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) { nextFilter.filterWrite(session, writeRequest); } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.filterClose(session); } private class ProcessEventsRunnable implements Runnable { private final SessionBuffer buffer; ProcessEventsRunnable(SessionBuffer buffer) { this.buffer = buffer; } public void run() { while (true) { Event event; synchronized (buffer.eventQueue) { event = buffer.eventQueue.poll(); if (event == null) { buffer.processingCompleted = true; break; } } processEvent(event.getNextFilter(), buffer.session, event .getType(), event.getData()); } if (logger.isDebugEnabled()) { logger.debug("Exiting since queue is empty for " + buffer.session.getRemoteAddress()); } } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/executor/package.html0000644000175000017500000000024711002320021027166 0ustar drazzibdrazzib An IoFilter that provides flexible thread models mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/0000755000175000017500000000000011044712500024136 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolDecoderException.java0000644000175000017500000000554211002320021031740 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; /** * An exception that is thrown when {@link ProtocolDecoder} * cannot understand or failed to validate the specified {@link ByteBuffer} * content. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ProtocolDecoderException extends ProtocolCodecException { private static final long serialVersionUID = 3545799879533408565L; private String hexdump; /** * Constructs a new instance. */ public ProtocolDecoderException() { } /** * Constructs a new instance with the specified message. */ public ProtocolDecoderException(String message) { super(message); } /** * Constructs a new instance with the specified cause. */ public ProtocolDecoderException(Throwable cause) { super(cause); } /** * Constructs a new instance with the specified message and the specified * cause. */ public ProtocolDecoderException(String message, Throwable cause) { super(message, cause); } /** * Returns the message and the hexdump of the unknown part. */ public String getMessage() { String message = super.getMessage(); if (message == null) { message = ""; } if (hexdump != null) { return message + ((message.length() > 0) ? " " : "") + "(Hexdump: " + hexdump + ')'; } else { return message; } } /** * Returns the hexdump of the unknown message part. */ public String getHexdump() { return hexdump; } /** * Sets the hexdump of the unknown message part. */ public void setHexdump(String hexdump) { if (this.hexdump != null) { throw new IllegalStateException( "Hexdump cannot be set more than once."); } this.hexdump = hexdump; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolEncoderException.java0000644000175000017500000000363411002320021031752 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; /** * An exception that is thrown when {@link ProtocolEncoder} * cannot understand or failed to validate the specified message object. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ProtocolEncoderException extends ProtocolCodecException { private static final long serialVersionUID = 8752989973624459604L; /** * Constructs a new instance. */ public ProtocolEncoderException() { } /** * Constructs a new instance with the specified message. */ public ProtocolEncoderException(String message) { super(message); } /** * Constructs a new instance with the specified cause. */ public ProtocolEncoderException(Throwable cause) { super(cause); } /** * Constructs a new instance with the specified message and the specified * cause. */ public ProtocolEncoderException(String message, Throwable cause) { super(message, cause); } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolCodecFilter.java0000644000175000017500000003144311002320021030676 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ByteBufferProxy; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.support.DefaultWriteFuture; import org.apache.mina.filter.codec.support.SimpleProtocolDecoderOutput; import org.apache.mina.filter.codec.support.SimpleProtocolEncoderOutput; import org.apache.mina.util.SessionLog; /** * An {@link IoFilter} which translates binary or protocol specific data into * message object and vice versa using {@link ProtocolCodecFactory}, * {@link ProtocolEncoder}, or {@link ProtocolDecoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 612026 $, $Date: 2008-01-15 15:16:14 +0900 (Tue, 15 Jan 2008) $ */ public class ProtocolCodecFilter extends IoFilterAdapter { public static final String ENCODER = ProtocolCodecFilter.class.getName() + ".encoder"; public static final String DECODER = ProtocolCodecFilter.class.getName() + ".decoder"; private static final String DECODER_OUT = ProtocolCodecFilter.class.getName() + ".decoderOut"; private static final Class[] EMPTY_PARAMS = new Class[0]; private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]); private final ProtocolCodecFactory factory; public ProtocolCodecFilter(ProtocolCodecFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } this.factory = factory; } public ProtocolCodecFilter(final ProtocolEncoder encoder, final ProtocolDecoder decoder) { if (encoder == null) { throw new NullPointerException("encoder"); } if (decoder == null) { throw new NullPointerException("decoder"); } this.factory = new ProtocolCodecFactory() { public ProtocolEncoder getEncoder() { return encoder; } public ProtocolDecoder getDecoder() { return decoder; } }; } public ProtocolCodecFilter( final Class encoderClass, final Class decoderClass) { if (encoderClass == null) { throw new NullPointerException("encoderClass"); } if (decoderClass == null) { throw new NullPointerException("decoderClass"); } if (!ProtocolEncoder.class.isAssignableFrom(encoderClass)) { throw new IllegalArgumentException("encoderClass: " + encoderClass.getName()); } if (!ProtocolDecoder.class.isAssignableFrom(decoderClass)) { throw new IllegalArgumentException("decoderClass: " + decoderClass.getName()); } try { encoderClass.getConstructor(EMPTY_PARAMS); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "encoderClass doesn't have a public default constructor."); } try { decoderClass.getConstructor(EMPTY_PARAMS); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "decoderClass doesn't have a public default constructor."); } this.factory = new ProtocolCodecFactory() { public ProtocolEncoder getEncoder() throws Exception { return encoderClass.newInstance(); } public ProtocolDecoder getDecoder() throws Exception { return decoderClass.newInstance(); } }; } @Override public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { if (parent.contains(ProtocolCodecFilter.class)) { throw new IllegalStateException( "A filter chain cannot contain more than one ProtocolCodecFilter."); } } @Override public void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { disposeEncoder(parent.getSession()); disposeDecoder(parent.getSession()); disposeDecoderOut(parent.getSession()); } @Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (!(message instanceof ByteBuffer)) { nextFilter.messageReceived(session, message); return; } ByteBuffer in = (ByteBuffer) message; ProtocolDecoder decoder = getDecoder(session); ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter); int oldPos = in.position(); try { synchronized (decoderOut) { decoder.decode(session, in, decoderOut); } } catch (Throwable t) { ProtocolDecoderException pde; if (t instanceof ProtocolDecoderException) { pde = (ProtocolDecoderException) t; } else { pde = new ProtocolDecoderException(t); } if (pde.getHexdump() == null) { int curPos = in.position(); in.position(oldPos); pde.setHexdump(in.getHexDump()); in.position(curPos); } throw pde; } finally { try { // Release the read buffer. in.release(); } finally { decoderOut.flush(); } } } @Override public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (message instanceof HiddenByteBuffer) { return; } if (!(message instanceof MessageByteBuffer)) { nextFilter.messageSent(session, message); return; } nextFilter.messageSent(session, ((MessageByteBuffer) message).message); } @Override public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { Object message = writeRequest.getMessage(); if (message instanceof ByteBuffer) { nextFilter.filterWrite(session, writeRequest); return; } ProtocolEncoder encoder = getEncoder(session); ProtocolEncoderOutputImpl encoderOut = getEncoderOut(session, nextFilter, writeRequest); try { encoder.encode(session, message, encoderOut); encoderOut.flush(); nextFilter.filterWrite(session, new WriteRequest( new MessageByteBuffer(writeRequest.getMessage()), writeRequest.getFuture(), writeRequest.getDestination())); } catch (Throwable t) { ProtocolEncoderException pee; if (t instanceof ProtocolEncoderException) { pee = (ProtocolEncoderException) t; } else { pee = new ProtocolEncoderException(t); } throw pee; } } @Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { // Call finishDecode() first when a connection is closed. ProtocolDecoder decoder = getDecoder(session); ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter); try { decoder.finishDecode(session, decoderOut); } catch (Throwable t) { ProtocolDecoderException pde; if (t instanceof ProtocolDecoderException) { pde = (ProtocolDecoderException) t; } else { pde = new ProtocolDecoderException(t); } throw pde; } finally { // Dispose all. disposeEncoder(session); disposeDecoder(session); disposeDecoderOut(session); decoderOut.flush(); } nextFilter.sessionClosed(session); } private ProtocolEncoder getEncoder(IoSession session) throws Exception { ProtocolEncoder encoder = (ProtocolEncoder) session .getAttribute(ENCODER); if (encoder == null) { encoder = factory.getEncoder(); session.setAttribute(ENCODER, encoder); } return encoder; } private ProtocolEncoderOutputImpl getEncoderOut(IoSession session, NextFilter nextFilter, WriteRequest writeRequest) { return new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest); } private ProtocolDecoder getDecoder(IoSession session) throws Exception { ProtocolDecoder decoder = (ProtocolDecoder) session .getAttribute(DECODER); if (decoder == null) { decoder = factory.getDecoder(); session.setAttribute(DECODER, decoder); } return decoder; } private ProtocolDecoderOutput getDecoderOut(IoSession session, NextFilter nextFilter) { ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT); if (out == null) { out = new SimpleProtocolDecoderOutput(session, nextFilter); session.setAttribute(DECODER_OUT, out); } return out; } private void disposeEncoder(IoSession session) { ProtocolEncoder encoder = (ProtocolEncoder) session .removeAttribute(ENCODER); if (encoder == null) { return; } try { encoder.dispose(session); } catch (Throwable t) { SessionLog.warn(session, "Failed to dispose: " + encoder.getClass().getName() + " (" + encoder + ')'); } } private void disposeDecoder(IoSession session) { ProtocolDecoder decoder = (ProtocolDecoder) session .removeAttribute(DECODER); if (decoder == null) { return; } try { decoder.dispose(session); } catch (Throwable t) { SessionLog.warn(session, "Falied to dispose: " + decoder.getClass().getName() + " (" + decoder + ')'); } } private void disposeDecoderOut(IoSession session) { session.removeAttribute(DECODER_OUT); } private static class HiddenByteBuffer extends ByteBufferProxy { private HiddenByteBuffer(ByteBuffer buf) { super(buf); } } private static class MessageByteBuffer extends ByteBufferProxy { private final Object message; private MessageByteBuffer(Object message) { super(EMPTY_BUFFER); this.message = message; } @Override public void acquire() { // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message } @Override public void release() { // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message } } private static class ProtocolEncoderOutputImpl extends SimpleProtocolEncoderOutput { private final IoSession session; private final NextFilter nextFilter; private final WriteRequest writeRequest; ProtocolEncoderOutputImpl(IoSession session, NextFilter nextFilter, WriteRequest writeRequest) { this.session = session; this.nextFilter = nextFilter; this.writeRequest = writeRequest; } @Override protected WriteFuture doFlush(ByteBuffer buf) { WriteFuture future = new DefaultWriteFuture(session); nextFilter.filterWrite(session, new WriteRequest( new HiddenByteBuffer(buf), future, writeRequest .getDestination())); return future; } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolEncoder.java0000644000175000017500000000465311002320021030075 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; /** * Encodes higher-level message objects into binary or protocol-specific data. * MINA invokes {@link #encode(IoSession, Object, ProtocolEncoderOutput)} * method with message which is popped from the session write queue, and then * the encoder implementation puts encoded {@link ByteBuffer}s into * {@link ProtocolEncoderOutput} by calling * {@link ProtocolEncoderOutput#write(ByteBuffer)}. *

* Please refer to * TextLineEncoder * example. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ProtocolEncoder { /** * Encodes higher-level message objects into binary or protocol-specific data. * MINA invokes {@link #encode(IoSession, Object, ProtocolEncoderOutput)} * method with message which is popped from the session write queue, and then * the encoder implementation puts encoded {@link ByteBuffer}s into * {@link ProtocolEncoderOutput}. * * @throws Exception if the message violated protocol specification */ void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception; /** * Releases all resources related with this encoder. * * @throws Exception if failed to dispose all resources */ void dispose(IoSession session) throws Exception; }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolDecoderAdapter.java0000644000175000017500000000343411002320021031360 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.IoSession; /** * An abstract {@link ProtocolDecoder} implementation for those who don't need * {@link ProtocolDecoder#finishDecode(IoSession, ProtocolDecoderOutput)} nor * {@link ProtocolDecoder#dispose(IoSession)} method. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class ProtocolDecoderAdapter implements ProtocolDecoder { /** * Override this method to deal with the closed connection. * The default implementation does nothing. */ public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { } /** * Override this method to dispose all resources related with this decoder. * The default implementation does nothing. */ public void dispose(IoSession session) throws Exception { } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolDecoderOutput.java0000644000175000017500000000314511002320021031277 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; /** * Callback for {@link ProtocolDecoder} to generate decoded messages. * {@link ProtocolDecoder} must call {@link #write(Object)} for each decoded * messages. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ProtocolDecoderOutput { /** * Callback for {@link ProtocolDecoder} to generate decoded messages. * {@link ProtocolDecoder} must call {@link #write(Object)} for each * decoded messages. * * @param message the decoded message */ void write(Object message); /** * Flushes all messages you wrote via {@link #write(Object)} to * the next filter. */ void flush(); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/package.html0000644000175000017500000000031011002320021026374 0ustar drazzibdrazzib Filter implementations that helps you to implement complex protocols via 'codec' concept. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/CumulativeProtocolDecoder.java0000644000175000017500000001657611002320021032131 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; /** * A {@link ProtocolDecoder} that cumulates the content of received * buffers to a cumulative buffer to help users implement decoders. *

* If the received {@link ByteBuffer} is only a part of a message. * decoders should cumulate received buffers to make a message complete or * to postpone decoding until more buffers arrive. *

* Here is an example decoder that decodes CRLF terminated lines into * Command objects: *

 * public class CRLFTerminatedCommandLineDecoder 
 *         extends CumulativeProtocolDecoder {
 * 
 *     private Command parseCommand(ByteBuffer in) {
 *         // Convert the bytes in the specified buffer to a 
 *         // Command object.
 *         ...
 *     }
 * 
 *     protected boolean doDecode(IoSession session, ByteBuffer in,
 *                                ProtocolDecoderOutput out) 
 *             throws Exception {
 * 
 *         // Remember the initial position.
 *         int start = in.position();
 *        
 *         // Now find the first CRLF in the buffer.
 *         byte previous = 0;
 *         while (in.hasRemaining()) {
 *             byte current = in.get();
 *            
 *             if (previous == '\r' && current == '\n') {
 *                 // Remember the current position and limit.
 *                 int position = in.position();
 *                 int limit = in.limit();
 *                 try {
 *                     in.position(start);
 *                     in.limit(position);
 *                     // The bytes between in.position() and in.limit()
 *                     // now contain a full CRLF terminated line.
 *                     out.write(parseCommand(in.slice()));
 *                 } finally {
 *                     // Set the position to point right after the
 *                     // detected line and set the limit to the old
 *                     // one.
 *                     in.position(position);
 *                     in.limit(limit);
 *                 }
 *                 // Decoded one line; CumulativeProtocolDecoder will  
 *                 // call me again until I return false. So just 
 *                 // return true until there are no more lines in the 
 *                 // buffer.
 *                 return true;
 *             }
 *            
 *             previous = current;
 *         }
 *         
 *         // Could not find CRLF in the buffer. Reset the initial 
 *         // position to the one we recorded above.
 *         in.position(start);
 *        
 *         return false;
 *     }
 * }
 * 
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class CumulativeProtocolDecoder extends ProtocolDecoderAdapter { private static final String BUFFER = CumulativeProtocolDecoder.class .getName() + ".Buffer"; /** * Creates a new instance. */ protected CumulativeProtocolDecoder() { } /** * Cumulates content of in into internal buffer and forwards * decoding request to {@link #doDecode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. * doDecode() is invoked repeatedly until it returns false * and the cumulative buffer is compacted after decoding ends. * * @throws IllegalStateException if your doDecode() returned * true not consuming the cumulative buffer. */ public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { boolean usingSessionBuffer = true; ByteBuffer buf = (ByteBuffer) session.getAttribute(BUFFER); // If we have a session buffer, append data to that; otherwise // use the buffer read from the network directly. if (buf != null) { buf.put(in); buf.flip(); } else { buf = in; usingSessionBuffer = false; } for (;;) { int oldPos = buf.position(); boolean decoded = doDecode(session, buf, out); if (decoded) { if (buf.position() == oldPos) { throw new IllegalStateException( "doDecode() can't return true when buffer is not consumed."); } if (!buf.hasRemaining()) { break; } } else { break; } } // if there is any data left that cannot be decoded, we store // it in a buffer in the session and next time this decoder is // invoked the session buffer gets appended to if (buf.hasRemaining()) { if (usingSessionBuffer) buf.compact(); else storeRemainingInSession(buf, session); } else { if (usingSessionBuffer) removeSessionBuffer(session); } } /** * Implement this method to consume the specified cumulative buffer and * decode its content into message(s). * * @param in the cumulative buffer * @return true if and only if there's more to decode in the buffer * and you want to have doDecode method invoked again. * Return false if remaining data is not enough to decode, * then this method will be invoked again when more data is cumulated. * @throws Exception if cannot decode in. */ protected abstract boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception; /** * Releases the cumulative buffer used by the specified session. * Please don't forget to call super.dispose( session ) when * you override this method. */ public void dispose(IoSession session) throws Exception { removeSessionBuffer(session); } private void removeSessionBuffer(IoSession session) { ByteBuffer buf = (ByteBuffer) session.removeAttribute(BUFFER); if (buf != null) { buf.release(); } } private void storeRemainingInSession(ByteBuffer buf, IoSession session) { ByteBuffer remainingBuf = ByteBuffer.allocate(buf.capacity()); remainingBuf.setAutoExpand(true); remainingBuf.order(buf.order()); remainingBuf.put(buf); session.setAttribute(BUFFER, remainingBuf); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolCodecFactory.java0000644000175000017500000000346611002320021031064 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; /** * Provides {@link ProtocolEncoder} and {@link ProtocolDecoder} which translates * binary or protocol specific data into message object and vice versa. *

* Please refer to * ReverserProtocolProvider * example. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ProtocolCodecFactory { /** * Returns a new (or reusable) instance of {@link ProtocolEncoder} which * encodes message objects into binary or protocol-specific data. */ ProtocolEncoder getEncoder() throws Exception; /** * Returns a new (or reusable) instance of {@link ProtocolDecoder} which * decodes binary or protocol-specific data into message objects. */ ProtocolDecoder getDecoder() throws Exception; }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/0000755000175000017500000000000011044712500025260 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/MessageEncoderFactory.java0000644000175000017500000000242311002320020032322 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; /** * A factory that creates a new instance of {@link MessageEncoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see DemuxingProtocolCodecFactory */ public interface MessageEncoderFactory { /** * Creates a new message encoder. */ MessageEncoder getEncoder() throws Exception; } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/MessageEncoder.java0000644000175000017500000000403111002320020030767 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; import java.util.Set; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /** * Encodes messages of specific types specified by {@link #getMessageTypes()}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see DemuxingProtocolCodecFactory * @see MessageEncoderFactory */ public interface MessageEncoder { /** * Returns the set of message classes this encoder can encode. */ Set> getMessageTypes(); /** * Encodes higher-level message objects into binary or protocol-specific data. * MINA invokes {@link #encode(IoSession, Object, ProtocolEncoderOutput)} * method with message which is popped from the session write queue, and then * the encoder implementation puts encoded {@link ByteBuffer}s into * {@link ProtocolEncoderOutput}. * * @throws Exception if the message violated protocol specification */ void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception; } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/package.html0000644000175000017500000000034511002320020027525 0ustar drazzibdrazzib Protocol codecs that helps you to implement even more complex protocols by splitting a codec into multiple sub-codecs. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/MessageDecoderResult.java0000644000175000017500000000477611002320020032174 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * Represents results from {@link MessageDecoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see MessageDecoder */ public class MessageDecoderResult { /** * Represents a result from {@link MessageDecoder#decodable(IoSession, ByteBuffer)} * and {@link MessageDecoder#decode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. * Please refer to each method's documentation for detailed explanation. */ public static MessageDecoderResult OK = new MessageDecoderResult("OK"); /** * Represents a result from {@link MessageDecoder#decodable(IoSession, ByteBuffer)} * and {@link MessageDecoder#decode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. * Please refer to each method's documentation for detailed explanation. */ public static MessageDecoderResult NEED_DATA = new MessageDecoderResult( "NEED_DATA"); /** * Represents a result from {@link MessageDecoder#decodable(IoSession, ByteBuffer)} * and {@link MessageDecoder#decode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. * Please refer to each method's documentation for detailed explanation. */ public static MessageDecoderResult NOT_OK = new MessageDecoderResult( "NOT_OK"); private final String name; private MessageDecoderResult(String name) { this.name = name; } public String toString() { return name; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/MessageDecoderFactory.java0000644000175000017500000000242311002320020032310 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; /** * A factory that creates a new instance of {@link MessageDecoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see DemuxingProtocolCodecFactory */ public interface MessageDecoderFactory { /** * Creates a new message decoder. */ MessageDecoder getDecoder() throws Exception; } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/MessageDecoder.java0000644000175000017500000001020511002320020030755 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * Decodes specific messages. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see DemuxingProtocolCodecFactory * @see MessageDecoderFactory */ public interface MessageDecoder { /** * Represents a result from {@link #decodable(IoSession, ByteBuffer)} and * {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. Please * refer to each method's documentation for detailed explanation. */ static MessageDecoderResult OK = MessageDecoderResult.OK; /** * Represents a result from {@link #decodable(IoSession, ByteBuffer)} and * {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. Please * refer to each method's documentation for detailed explanation. */ static MessageDecoderResult NEED_DATA = MessageDecoderResult.NEED_DATA; /** * Represents a result from {@link #decodable(IoSession, ByteBuffer)} and * {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)}. Please * refer to each method's documentation for detailed explanation. */ static MessageDecoderResult NOT_OK = MessageDecoderResult.NOT_OK; /** * Checks the specified buffer is decodable by this decoder. * * @return {@link #OK} if this decoder can decode the specified buffer. * {@link #NOT_OK} if this decoder cannot decode the specified buffer. * {@link #NEED_DATA} if more data is required to determine if the * specified buffer is decodable ({@link #OK}) or not decodable * {@link #NOT_OK}. */ MessageDecoderResult decodable(IoSession session, ByteBuffer in); /** * Decodes binary or protocol-specific content into higher-level message objects. * MINA invokes {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)} * method with read data, and then the decoder implementation puts decoded * messages into {@link ProtocolDecoderOutput}. * * @return {@link #OK} if you finished decoding messages successfully. * {@link #NEED_DATA} if you need more data to finish decoding current message. * {@link #NOT_OK} if you cannot decode current message due to protocol specification violation. * * @throws Exception if the read data violated protocol specification */ MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception; /** * Invoked when the specified session is closed while this decoder was * parsing the data. This method is useful when you deal with the protocol which doesn't * specify the length of a message such as HTTP response without content-length * header. Implement this method to process the remaining data that * {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)} method didn't process * completely. * * @throws Exception if the read data violated protocol specification */ void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception; } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolCodecFactory.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolCodecFactory.j0000644000175000017500000003630111002320020033210 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderException; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderException; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.util.IdentityHashSet; /** * A composite {@link ProtocolCodecFactory} that consists of multiple * {@link MessageEncoder}s and {@link MessageDecoder}s. * {@link ProtocolEncoder} and {@link ProtocolDecoder} this factory * returns demultiplex incoming messages and buffers to * appropriate {@link MessageEncoder}s and {@link MessageDecoder}s. * *

Disposing resources acquired by {@link MessageEncoder} and {@link MessageDecoder}

*

* Make your {@link MessageEncoder} and {@link MessageDecoder} to put all * resources that need to be released as a session attribute. {@link #disposeCodecResources(IoSession)} * method will be invoked when a session is closed. Override {@link #disposeCodecResources(IoSession)} * to release the resources you've put as an attribute. *

* We didn't provide any dispose method for {@link MessageEncoder} and {@link MessageDecoder} * because they can give you a big performance penalty in case you have a lot of * message types to handle. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 612026 $, $Date: 2008-01-15 15:16:14 +0900 (Tue, 15 Jan 2008) $ * * @see MessageEncoder * @see MessageDecoder */ public class DemuxingProtocolCodecFactory implements ProtocolCodecFactory { private MessageDecoderFactory[] decoderFactories = new MessageDecoderFactory[0]; private MessageEncoderFactory[] encoderFactories = new MessageEncoderFactory[0]; private static final Class[] EMPTY_PARAMS = new Class[0]; public DemuxingProtocolCodecFactory() { } public void register(Class encoderOrDecoderClass) { if (encoderOrDecoderClass == null) { throw new NullPointerException("encoderOrDecoderClass"); } try { encoderOrDecoderClass.getConstructor(EMPTY_PARAMS); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "The specifiec class doesn't have a public default constructor."); } boolean registered = false; if (MessageEncoder.class.isAssignableFrom(encoderOrDecoderClass)) { register(new DefaultConstructorMessageEncoderFactory( encoderOrDecoderClass)); registered = true; } if (MessageDecoder.class.isAssignableFrom(encoderOrDecoderClass)) { register(new DefaultConstructorMessageDecoderFactory( encoderOrDecoderClass)); registered = true; } if (!registered) { throw new IllegalArgumentException("Unregisterable type: " + encoderOrDecoderClass); } } public void register(MessageEncoder encoder) { register(new SingletonMessageEncoderFactory(encoder)); } public void register(MessageEncoderFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } MessageEncoderFactory[] encoderFactories = this.encoderFactories; MessageEncoderFactory[] newEncoderFactories = new MessageEncoderFactory[encoderFactories.length + 1]; System.arraycopy(encoderFactories, 0, newEncoderFactories, 0, encoderFactories.length); newEncoderFactories[encoderFactories.length] = factory; this.encoderFactories = newEncoderFactories; } public void register(MessageDecoder decoder) { register(new SingletonMessageDecoderFactory(decoder)); } public void register(MessageDecoderFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } MessageDecoderFactory[] decoderFactories = this.decoderFactories; MessageDecoderFactory[] newDecoderFactories = new MessageDecoderFactory[decoderFactories.length + 1]; System.arraycopy(decoderFactories, 0, newDecoderFactories, 0, decoderFactories.length); newDecoderFactories[decoderFactories.length] = factory; this.decoderFactories = newDecoderFactories; } public ProtocolEncoder getEncoder() throws Exception { return new ProtocolEncoderImpl(); } public ProtocolDecoder getDecoder() throws Exception { return new ProtocolDecoderImpl(); } /** * Implement this method to release all resources acquired to perform * encoding and decoding messages for the specified session. * By default, this method does nothing. * * @param session the session that requires resource deallocation now */ protected void disposeCodecResources(IoSession session) { // Do nothing by default; let users implement it as they want. // This statement is just to avoid compiler warning. Please ignore. session.getTransportType(); } private class ProtocolEncoderImpl implements ProtocolEncoder { private final Map, MessageEncoder> encoders = new IdentityHashMap, MessageEncoder>(); private ProtocolEncoderImpl() throws Exception { MessageEncoderFactory[] encoderFactories = DemuxingProtocolCodecFactory.this.encoderFactories; for (int i = encoderFactories.length - 1; i >= 0; i--) { MessageEncoder encoder = encoderFactories[i].getEncoder(); Set> messageTypes = encoder.getMessageTypes(); if (messageTypes == null) { throw new IllegalStateException(encoder.getClass() .getName() + "#getMessageTypes() may not return null."); } Iterator> it = messageTypes.iterator(); while (it.hasNext()) { Class type = it.next(); encoders.put(type, encoder); } } } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { Class type = message.getClass(); MessageEncoder encoder = findEncoder(type); if (encoder == null) { throw new ProtocolEncoderException("Unexpected message type: " + type); } encoder.encode(session, message, out); } private MessageEncoder findEncoder(Class type) { MessageEncoder encoder = encoders.get(type); if (encoder == null) { encoder = findEncoder(type, new IdentityHashSet>()); } return encoder; } private MessageEncoder findEncoder(Class type, Set> triedClasses) { MessageEncoder encoder; if (triedClasses.contains(type)) return null; triedClasses.add(type); encoder = encoders.get(type); if (encoder == null) { encoder = findEncoder(type, triedClasses); if (encoder != null) return encoder; Class[] interfaces = type.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { encoder = findEncoder(interfaces[i], triedClasses); if (encoder != null) return encoder; } return null; } else return encoder; } public void dispose(IoSession session) throws Exception { DemuxingProtocolCodecFactory.this.disposeCodecResources(session); } } private class ProtocolDecoderImpl extends CumulativeProtocolDecoder { private final MessageDecoder[] decoders; private MessageDecoder currentDecoder; protected ProtocolDecoderImpl() throws Exception { MessageDecoderFactory[] decoderFactories = DemuxingProtocolCodecFactory.this.decoderFactories; decoders = new MessageDecoder[decoderFactories.length]; for (int i = decoderFactories.length - 1; i >= 0; i--) { decoders[i] = decoderFactories[i].getDecoder(); } } @Override protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { if (currentDecoder == null) { MessageDecoder[] decoders = this.decoders; int undecodables = 0; for (int i = decoders.length - 1; i >= 0; i--) { MessageDecoder decoder = decoders[i]; int limit = in.limit(); int pos = in.position(); MessageDecoderResult result; try { result = decoder.decodable(session, in); } finally { in.position(pos); in.limit(limit); } if (result == MessageDecoder.OK) { currentDecoder = decoder; break; } else if (result == MessageDecoder.NOT_OK) { undecodables++; } else if (result != MessageDecoder.NEED_DATA) { throw new IllegalStateException( "Unexpected decode result (see your decodable()): " + result); } } if (undecodables == decoders.length) { // Throw an exception if all decoders cannot decode data. String dump = in.getHexDump(); in.position(in.limit()); // Skip data ProtocolDecoderException e = new ProtocolDecoderException( "No appropriate message decoder: " + dump); e.setHexdump(dump); throw e; } if (currentDecoder == null) { // Decoder is not determined yet (i.e. we need more data) return false; } } MessageDecoderResult result = currentDecoder.decode(session, in, out); if (result == MessageDecoder.OK) { currentDecoder = null; return true; } else if (result == MessageDecoder.NEED_DATA) { return false; } else if (result == MessageDecoder.NOT_OK) { currentDecoder = null; throw new ProtocolDecoderException( "Message decoder returned NOT_OK."); } else { currentDecoder = null; throw new IllegalStateException( "Unexpected decode result (see your decode()): " + result); } } @Override public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { if (currentDecoder == null) { return; } currentDecoder.finishDecode(session, out); } @Override public void dispose(IoSession session) throws Exception { super.dispose(session); // ProtocolEncoder.dispose() already called disposeCodec(), // so there's nothing more we need to do. } } private static class SingletonMessageEncoderFactory implements MessageEncoderFactory { private final MessageEncoder encoder; private SingletonMessageEncoderFactory(MessageEncoder encoder) { if (encoder == null) { throw new NullPointerException("encoder"); } this.encoder = encoder; } public MessageEncoder getEncoder() { return encoder; } } private static class SingletonMessageDecoderFactory implements MessageDecoderFactory { private final MessageDecoder decoder; private SingletonMessageDecoderFactory(MessageDecoder decoder) { if (decoder == null) { throw new NullPointerException("decoder"); } this.decoder = decoder; } public MessageDecoder getDecoder() { return decoder; } } private static class DefaultConstructorMessageEncoderFactory implements MessageEncoderFactory { private final Class encoderClass; private DefaultConstructorMessageEncoderFactory(Class encoderClass) { if (encoderClass == null) { throw new NullPointerException("encoderClass"); } if (!MessageEncoder.class.isAssignableFrom(encoderClass)) { throw new IllegalArgumentException( "encoderClass is not assignable to MessageEncoder"); } this.encoderClass = encoderClass; } public MessageEncoder getEncoder() throws Exception { return (MessageEncoder) encoderClass.newInstance(); } } private static class DefaultConstructorMessageDecoderFactory implements MessageDecoderFactory { private final Class decoderClass; private DefaultConstructorMessageDecoderFactory(Class decoderClass) { if (decoderClass == null) { throw new NullPointerException("decoderClass"); } if (!MessageDecoder.class.isAssignableFrom(decoderClass)) { throw new IllegalArgumentException( "decoderClass is not assignable to MessageDecoder"); } this.decoderClass = decoderClass; } public MessageDecoder getDecoder() throws Exception { return (MessageDecoder) decoderClass.newInstance(); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/demux/MessageDecoderAdapter.java0000644000175000017500000000301711002320020032261 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.demux; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * An abstract {@link MessageDecoder} implementation for those who don't need to * implement {@link MessageDecoder#finishDecode(IoSession, ProtocolDecoderOutput)} * method. * * @author The Apache Directory Project (mina-dev@directory.apache.org) */ public abstract class MessageDecoderAdapter implements MessageDecoder { /** * Override this method to deal with the closed connection. * The default implementation does nothing. */ public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolDecoder.java0000644000175000017500000000562711002320021030065 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; /** * Decodes binary or protocol-specific data into higher-level message objects. * MINA invokes {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)} * method with read data, and then the decoder implementation puts decoded * messages into {@link ProtocolDecoderOutput} by calling * {@link ProtocolDecoderOutput#write(Object)}. *

* Please refer to * TextLineDecoder * example. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ProtocolDecoder { /** * Decodes binary or protocol-specific content into higher-level message objects. * MINA invokes {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)} * method with read data, and then the decoder implementation puts decoded * messages into {@link ProtocolDecoderOutput}. * * @throws Exception if the read data violated protocol specification */ void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception; /** * Invoked when the specified session is closed. This method is useful * when you deal with the protocol which doesn't specify the length of a message * such as HTTP response without content-length header. Implement this * method to process the remaining data that {@link #decode(IoSession, ByteBuffer, ProtocolDecoderOutput)} * method didn't process completely. * * @throws Exception if the read data violated protocol specification */ void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception; /** * Releases all resources related with this decoder. * * @throws Exception if failed to dispose all resources */ void dispose(IoSession session) throws Exception; }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/support/0000755000175000017500000000000011044712500025652 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/support/package.html0000644000175000017500000000026511002320021030121 0ustar drazzibdrazzib Internal classes used by org.apache.mina.filter.codec package. ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/support/SimpleProtocolEncoderOutput.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/support/SimpleProtocolEncoderOutput.0000644000175000017500000000601411002320021033333 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.support; import java.util.LinkedList; import java.util.Queue; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.WriteFuture; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /** * A {@link ProtocolEncoderOutput} based on queue. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class SimpleProtocolEncoderOutput implements ProtocolEncoderOutput { private final Queue bufferQueue = new LinkedList(); public SimpleProtocolEncoderOutput() { } public Queue getBufferQueue() { return bufferQueue; } public void write(ByteBuffer buf) { bufferQueue.add(buf); } public void mergeAll() { int sum = 0; final int size = bufferQueue.size(); if (size < 2) { // no need to merge! return; } // Get the size of merged BB for (Object o : bufferQueue) { sum += ((ByteBuffer) o).remaining(); } // Allocate a new BB that will contain all fragments ByteBuffer newBuf = ByteBuffer.allocate(sum); // and merge all. for (;;) { ByteBuffer buf = bufferQueue.poll(); if (buf == null) { break; } newBuf.put(buf); buf.release(); } // Push the new buffer finally. newBuf.flip(); bufferQueue.offer(newBuf); } public WriteFuture flush() { Queue bufferQueue = this.bufferQueue; WriteFuture future = null; if (bufferQueue.isEmpty()) { return null; } else { for (;;) { ByteBuffer buf = bufferQueue.poll(); if (buf == null) { break; } // Flush only when the buffer has remaining. if (buf.hasRemaining()) { future = doFlush(buf); } } } return future; } protected abstract WriteFuture doFlush(ByteBuffer buf); }././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/support/SimpleProtocolDecoderOutput.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/support/SimpleProtocolDecoderOutput.0000644000175000017500000000406111002320021033321 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.support; import java.util.ArrayList; import java.util.List; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoSession; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * A {@link ProtocolDecoderOutput} based on queue. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 560326 $, $Date: 2007-07-28 02:30:25 +0900 (Sat, 28 Jul 2007) $ * */ public class SimpleProtocolDecoderOutput implements ProtocolDecoderOutput { private final NextFilter nextFilter; private final IoSession session; private final List messageQueue = new ArrayList(); public SimpleProtocolDecoderOutput(IoSession session, NextFilter nextFilter) { this.nextFilter = nextFilter; this.session = session; } public void write(Object message) { messageQueue.add(message); if (session instanceof BaseIoSession) { ((BaseIoSession) session).increaseReadMessages(); } } public void flush() { while (!messageQueue.isEmpty()) { nextFilter.messageReceived(session, messageQueue.remove(0)); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/textline/0000755000175000017500000000000011044712500025772 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/textline/package.html0000644000175000017500000000023011002320020030230 0ustar drazzibdrazzib A protocol codec for text-based protocols. mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/textline/LineDelimiter.java0000644000175000017500000000661211002320020031352 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.textline; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; /** * A delimiter which is appended to the end of a text line, such as * CR/LF. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class LineDelimiter { /** * the line delimiter constant of the current O/S. */ public static final LineDelimiter DEFAULT; static { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter out = new PrintWriter(bout); out.println(); DEFAULT = new LineDelimiter(new String(bout.toByteArray())); } /** * A special line delimiter which is used for auto-detection of * EOL in {@link TextLineDecoder}. If this delimiter is used, * {@link TextLineDecoder} will consider both '\r' and * '\n' as a delimiter. */ public static final LineDelimiter AUTO = new LineDelimiter(""); /** * The line delimiter constant of UNIX ("\n") */ public static final LineDelimiter UNIX = new LineDelimiter("\n"); /** * The line delimiter constant of MS Windows/DOS ("\r\n") */ public static final LineDelimiter WINDOWS = new LineDelimiter("\r\n"); /** * The line delimiter constant of Mac OS ("\r") */ public static final LineDelimiter MAC = new LineDelimiter("\r"); private final String value; /** * Creates a new line delimiter with the specified value. */ public LineDelimiter(String value) { if (value == null) { throw new NullPointerException("delimiter"); } this.value = value; } /** * Return the delimiter string. */ public String getValue() { return value; } public int hashCode() { return value.hashCode(); } public boolean equals(Object o) { if (!(o instanceof LineDelimiter)) { return false; } LineDelimiter that = (LineDelimiter) o; return this.value.equals(that.value); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("delimiter:"); if (value.length() == 0) { buf.append(" auto"); } else { for (int i = 0; i < value.length(); i++) { buf.append(" 0x"); buf.append(Integer.toHexString(value.charAt(i))); } } return buf.toString(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineEncoder.java0000644000175000017500000001022311002320020031651 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.textline; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderAdapter; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /** * A {@link ProtocolEncoder} which encodes a string into a text line * which ends with the delimiter. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class TextLineEncoder extends ProtocolEncoderAdapter { private static final String ENCODER = TextLineEncoder.class.getName() + ".encoder"; private final Charset charset; private final LineDelimiter delimiter; private int maxLineLength = Integer.MAX_VALUE; public TextLineEncoder() { this(Charset.defaultCharset(), LineDelimiter.UNIX); } public TextLineEncoder(LineDelimiter delimiter) { this(Charset.defaultCharset(), delimiter); } public TextLineEncoder(Charset charset) { this(charset, LineDelimiter.UNIX); } public TextLineEncoder(Charset charset, LineDelimiter delimiter) { if (charset == null) { throw new NullPointerException("charset"); } if (delimiter == null) { throw new NullPointerException("delimiter"); } if (LineDelimiter.AUTO.equals(delimiter)) { throw new IllegalArgumentException( "AUTO delimiter is not allowed for encoder."); } this.charset = charset; this.delimiter = delimiter; } /** * Returns the allowed maximum size of the encoded line. * If the size of the encoded line exceeds this value, the encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. */ public int getMaxLineLength() { return maxLineLength; } /** * Sets the allowed maximum size of the encoded line. * If the size of the encoded line exceeds this value, the encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. */ public void setMaxLineLength(int maxLineLength) { if (maxLineLength <= 0) { throw new IllegalArgumentException("maxLineLength: " + maxLineLength); } this.maxLineLength = maxLineLength; } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER); if (encoder == null) { encoder = charset.newEncoder(); session.setAttribute(ENCODER, encoder); } String value = message.toString(); ByteBuffer buf = ByteBuffer.allocate(value.length()) .setAutoExpand(true); buf.putString(value, encoder); if (buf.position() > maxLineLength) { throw new IllegalArgumentException("Line length: " + buf.position()); } buf.putString(delimiter.getValue(), encoder); buf.flip(); out.write(buf); } public void dispose() throws Exception { } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineCodecFactory.java0000644000175000017500000001001111002320020032632 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.textline; import java.nio.charset.Charset; import org.apache.mina.common.BufferDataException; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; /** * A {@link ProtocolCodecFactory} that performs encoding and decoding between * a text line data and a Java string object. This codec is useful especially * when you work with a text-based protocols such as SMTP and IMAP. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class TextLineCodecFactory implements ProtocolCodecFactory { private final TextLineEncoder encoder; private final TextLineDecoder decoder; /** * Creates a new instance with the current default {@link Charset}. */ public TextLineCodecFactory() { this(Charset.defaultCharset()); } /** * Creates a new instance with the specified {@link Charset}. */ public TextLineCodecFactory(Charset charset) { encoder = new TextLineEncoder(charset, LineDelimiter.UNIX); decoder = new TextLineDecoder(charset, LineDelimiter.AUTO); } public ProtocolEncoder getEncoder() { return encoder; } public ProtocolDecoder getDecoder() { return decoder; } /** * Returns the allowed maximum size of the encoded line. * If the size of the encoded line exceeds this value, the encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. *

* This method does the same job with {@link TextLineEncoder#getMaxLineLength()}. */ public int getEncoderMaxLineLength() { return encoder.getMaxLineLength(); } /** * Sets the allowed maximum size of the encoded line. * If the size of the encoded line exceeds this value, the encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. *

* This method does the same job with {@link TextLineEncoder#setMaxLineLength(int)}. */ public void setEncoderMaxLineLength(int maxLineLength) { encoder.setMaxLineLength(maxLineLength); } /** * Returns the allowed maximum size of the line to be decoded. * If the size of the line to be decoded exceeds this value, the * decoder will throw a {@link BufferDataException}. The default * value is 1024 (1KB). *

* This method does the same job with {@link TextLineDecoder#getMaxLineLength()}. */ public int getDecoderMaxLineLength() { return decoder.getMaxLineLength(); } /** * Sets the allowed maximum size of the line to be decoded. * If the size of the line to be decoded exceeds this value, the * decoder will throw a {@link BufferDataException}. The default * value is 1024 (1KB). *

* This method does the same job with {@link TextLineDecoder#setMaxLineLength(int)}. */ public void setDecoderMaxLineLength(int maxLineLength) { decoder.setMaxLineLength(maxLineLength); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineDecoder.java0000644000175000017500000002411111002320020031640 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.textline; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import org.apache.mina.common.BufferDataException; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * A {@link ProtocolDecoder} which decodes a text line into a string. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 636237 $, $Date: 2008-03-12 16:35:18 +0900 (Wed, 12 Mar 2008) $, */ public class TextLineDecoder implements ProtocolDecoder { private static final String CONTEXT = TextLineDecoder.class.getName() + ".context"; private final Charset charset; private final LineDelimiter delimiter; private ByteBuffer delimBuf; private int maxLineLength = 1024; /** * Creates a new instance with the current default {@link Charset} * and {@link LineDelimiter#AUTO} delimiter. */ public TextLineDecoder() { this(Charset.defaultCharset(), LineDelimiter.AUTO); } /** * Creates a new instance with the spcified charset * and {@link LineDelimiter#AUTO} delimiter. */ public TextLineDecoder(Charset charset) { this(charset, LineDelimiter.AUTO); } /** * Creates a new instance with the specified charset * and the specified delimiter. */ public TextLineDecoder(Charset charset, LineDelimiter delimiter) { if (charset == null) { throw new NullPointerException("charset"); } if (delimiter == null) { throw new NullPointerException("delimiter"); } this.charset = charset; this.delimiter = delimiter; } /** * Returns the allowed maximum size of the line to be decoded. * If the size of the line to be decoded exceeds this value, the * decoder will throw a {@link BufferDataException}. The default * value is 1024 (1KB). */ public int getMaxLineLength() { return maxLineLength; } /** * Sets the allowed maximum size of the line to be decoded. * If the size of the line to be decoded exceeds this value, the * decoder will throw a {@link BufferDataException}. The default * value is 1024 (1KB). */ public void setMaxLineLength(int maxLineLength) { if (maxLineLength <= 0) { throw new IllegalArgumentException("maxLineLength: " + maxLineLength); } this.maxLineLength = maxLineLength; } public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { Context ctx = getContext(session); if (LineDelimiter.AUTO.equals(delimiter)) { decodeAuto(ctx, in, out); } else { decodeNormal(ctx, in, out); } } private Context getContext(IoSession session) { Context ctx = (Context) session.getAttribute(CONTEXT); if (ctx == null) { ctx = new Context(); session.setAttribute(CONTEXT, ctx); } return ctx; } public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { } public void dispose(IoSession session) throws Exception { Context ctx = (Context) session.getAttribute(CONTEXT); if (ctx != null) { ctx.getBuffer().release(); session.removeAttribute(CONTEXT); } } private void decodeAuto(Context ctx, ByteBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException { int matchCount = ctx.getMatchCount(); // Try to find a match int oldPos = in.position(); int oldLimit = in.limit(); while (in.hasRemaining()) { byte b = in.get(); boolean matched = false; switch (b) { case '\r': // Might be Mac, but we don't auto-detect Mac EOL // to avoid confusion. matchCount++; break; case '\n': // UNIX matchCount++; matched = true; break; default: matchCount = 0; } if (matched) { // Found a match. int pos = in.position(); in.limit(pos); in.position(oldPos); ctx.append(in); in.limit(oldLimit); in.position(pos); if (ctx.getOverflowPosition() == 0) { ByteBuffer buf = ctx.getBuffer(); buf.flip(); buf.limit(buf.limit() - matchCount); try { out.write(buf.getString(ctx.getDecoder())); } finally { buf.clear(); } } else { int overflowPosition = ctx.getOverflowPosition(); ctx.reset(); throw new BufferDataException( "Line is too long: " + overflowPosition); } oldPos = pos; matchCount = 0; } } // Put remainder to buf. in.position(oldPos); ctx.append(in); ctx.setMatchCount(matchCount); } private void decodeNormal(Context ctx, ByteBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException { int matchCount = ctx.getMatchCount(); // Convert delimiter to ByteBuffer if not done yet. if (delimBuf == null) { ByteBuffer tmp = ByteBuffer.allocate(2).setAutoExpand(true); tmp.putString(delimiter.getValue(), charset.newEncoder()); tmp.flip(); delimBuf = tmp; } // Try to find a match int oldPos = in.position(); int oldLimit = in.limit(); while (in.hasRemaining()) { byte b = in.get(); if (delimBuf.get(matchCount) == b) { matchCount++; if (matchCount == delimBuf.limit()) { // Found a match. int pos = in.position(); in.limit(pos); in.position(oldPos); ctx.append(in); in.limit(oldLimit); in.position(pos); if (ctx.getOverflowPosition() == 0) { ByteBuffer buf = ctx.getBuffer(); buf.flip(); buf.limit(buf.limit() - matchCount); try { out.write(buf.getString(ctx.getDecoder())); } finally { buf.clear(); } } else { int overflowPosition = ctx.getOverflowPosition(); ctx.reset(); throw new BufferDataException( "Line is too long: " + overflowPosition); } oldPos = pos; matchCount = 0; } } else { // fix for DIRMINA-506 & DIRMINA-536 in.position(Math.max(0, in.position() - matchCount)); matchCount = 0; } } // Put remainder to buf. in.position(oldPos); ctx.append(in); ctx.setMatchCount(matchCount); } private class Context { private final CharsetDecoder decoder; private final ByteBuffer buf; private int matchCount = 0; private int overflowPosition = 0; private Context() { decoder = charset.newDecoder(); buf = ByteBuffer.allocate(80).setAutoExpand(true); } public CharsetDecoder getDecoder() { return decoder; } public ByteBuffer getBuffer() { return buf; } public int getOverflowPosition() { return overflowPosition; } public int getMatchCount() { return matchCount; } public void setMatchCount(int matchCount) { this.matchCount = matchCount; } public void reset() { overflowPosition = 0; matchCount = 0; decoder.reset(); } public void append(ByteBuffer in) { if (overflowPosition != 0) { discard(in); } else if (buf.position() > maxLineLength - in.remaining()) { overflowPosition = buf.position(); buf.clear(); discard(in); } else { getBuffer().put(in); } } private void discard(ByteBuffer in) { if (Integer.MAX_VALUE - in.remaining() < overflowPosition) { overflowPosition = Integer.MAX_VALUE; } else { overflowPosition += in.remaining(); } in.position(in.limit()); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolEncoderAdapter.java0000644000175000017500000000270011002320021031365 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.IoSession; /** * An abstract {@link ProtocolEncoder} implementation for those who don't have any * resources to dispose. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class ProtocolEncoderAdapter implements ProtocolEncoder { /** * Override this method dispose all resources related with this encoder. * The default implementation does nothing. */ public void dispose(IoSession session) throws Exception { } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolEncoderOutput.java0000644000175000017500000000434111002320021031310 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.WriteFuture; /** * Callback for {@link ProtocolEncoder} to generate encoded {@link ByteBuffer}s. * {@link ProtocolEncoder} must call {@link #write(ByteBuffer)} for each encoded * message. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface ProtocolEncoderOutput { /** * Callback for {@link ProtocolEncoder} to generate encoded * {@link ByteBuffer}s. {@link ProtocolEncoder} must call * {@link #write(ByteBuffer)} for each encoded message. * * @param buf the buffer which contains encoded data */ void write(ByteBuffer buf); /** * Merges all buffers you wrote via {@link #write(ByteBuffer)} into * one {@link ByteBuffer} and replaces the old fragmented ones with it. * This method is useful when you want to control the way MINA generates * network packets. */ void mergeAll(); /** * Flushes all buffers you wrote via {@link #write(ByteBuffer)} to * the session. This operation is asynchronous; please wait for * the returned {@link WriteFuture} if you want to wait for * the buffers flushed. * * @return null if there is nothing to flush at all. */ WriteFuture flush(); }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/SynchronizedProtocolDecoder.java0000644000175000017500000000523111002320021032454 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; /** * A {@link ProtocolDecoder} implementation which decorates an existing decoder * to be thread-safe. Please be careful if you're going to use this decorator * because it can be a root of performance degradation in a multi-thread * environment. Also, by default, appropriate synchronization is done * on a per-session basis by {@link ProtocolCodecFilter}. Please use this * decorator only when you need to synchronize on a per-decoder basis, which * is not common. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SynchronizedProtocolDecoder implements ProtocolDecoder { private final ProtocolDecoder decoder; /** * Creates a new instance which decorates the specified decoder. */ public SynchronizedProtocolDecoder(ProtocolDecoder decoder) { if (decoder == null) { throw new NullPointerException("decoder"); } this.decoder = decoder; } /** * Returns the decoder this decoder is decorating. */ public ProtocolDecoder getDecoder() { return decoder; } public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { synchronized (decoder) { decoder.decode(session, in, out); } } public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { synchronized (decoder) { decoder.finishDecode(session, out); } } public void dispose(IoSession session) throws Exception { synchronized (decoder) { decoder.dispose(session); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/SynchronizedProtocolEncoder.java0000644000175000017500000000453211002320021032471 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import org.apache.mina.common.IoSession; /** * A {@link ProtocolEncoder} implementation which decorates an existing encoder * to be thread-safe. Please be careful if you're going to use this decorator * because it can be a root of performance degradation in a multi-thread * environment. Please use this decorator only when you need to synchronize * on a per-encoder basis instead of on a per-session basis, which is not * common. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SynchronizedProtocolEncoder implements ProtocolEncoder { private final ProtocolEncoder encoder; /** * Creates a new instance which decorates the specified encoder. */ public SynchronizedProtocolEncoder(ProtocolEncoder encoder) { if (encoder == null) { throw new NullPointerException("encoder"); } this.encoder = encoder; } /** * Returns the encoder this encoder is decorating. */ public ProtocolEncoder getEncoder() { return encoder; } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { synchronized (encoder) { encoder.encode(session, message, out); } } public void dispose(IoSession session) throws Exception { synchronized (encoder) { encoder.dispose(session); } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/0000755000175000017500000000000011044712500027013 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationDecoder.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationDec0000644000175000017500000000644211002320021033307 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.serialization; import java.io.Serializable; import org.apache.mina.common.BufferDataException; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * A {@link ProtocolDecoder} which deserializes {@link Serializable} Java * objects using {@link ByteBuffer#getObject(ClassLoader)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ObjectSerializationDecoder extends CumulativeProtocolDecoder { private final ClassLoader classLoader; private int maxObjectSize = 1048576; // 1MB /** * Creates a new instance with the {@link ClassLoader} of * the current thread. */ public ObjectSerializationDecoder() { this(Thread.currentThread().getContextClassLoader()); } /** * Creates a new instance with the specified {@link ClassLoader}. */ public ObjectSerializationDecoder(ClassLoader classLoader) { if (classLoader == null) { throw new NullPointerException("classLoader"); } this.classLoader = classLoader; } /** * Returns the allowed maximum size of the object to be decoded. * If the size of the object to be decoded exceeds this value, this * decoder will throw a {@link BufferDataException}. The default * value is 1048576 (1MB). */ public int getMaxObjectSize() { return maxObjectSize; } /** * Sets the allowed maximum size of the object to be decoded. * If the size of the object to be decoded exceeds this value, this * decoder will throw a {@link BufferDataException}. The default * value is 1048576 (1MB). */ public void setMaxObjectSize(int maxObjectSize) { if (maxObjectSize <= 0) { throw new IllegalArgumentException("maxObjectSize: " + maxObjectSize); } this.maxObjectSize = maxObjectSize; } protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { if (!in.prefixedDataAvailable(4, maxObjectSize)) { return false; } out.write(in.getObject(classLoader)); return true; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/package.html0000644000175000017500000000031611002320021031257 0ustar drazzibdrazzib Protocol codecs which uses Java object serilization and leads to rapid protocol implementation. ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationEncoder.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationEnc0000644000175000017500000000631511002320021033320 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.serialization; import java.io.NotSerializableException; import java.io.Serializable; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderAdapter; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /** * A {@link ProtocolEncoder} which serializes {@link Serializable} Java objects * using {@link ByteBuffer#putObject(Object)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ObjectSerializationEncoder extends ProtocolEncoderAdapter { private int maxObjectSize = Integer.MAX_VALUE; // 2GB /** * Creates a new instance. */ public ObjectSerializationEncoder() { } /** * Returns the allowed maximum size of the encoded object. * If the size of the encoded object exceeds this value, this encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. */ public int getMaxObjectSize() { return maxObjectSize; } /** * Sets the allowed maximum size of the encoded object. * If the size of the encoded object exceeds this value, this encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. */ public void setMaxObjectSize(int maxObjectSize) { if (maxObjectSize <= 0) { throw new IllegalArgumentException("maxObjectSize: " + maxObjectSize); } this.maxObjectSize = maxObjectSize; } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { if (!(message instanceof Serializable)) { throw new NotSerializableException(); } ByteBuffer buf = ByteBuffer.allocate(64); buf.setAutoExpand(true); buf.putObject(message); int objectSize = buf.position() - 4; if (objectSize > maxObjectSize) { buf.release(); throw new IllegalArgumentException( "The encoded object is too big: " + objectSize + " (> " + maxObjectSize + ')'); } buf.flip(); out.write(buf); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationOutputStream.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationOut0000644000175000017500000001115511002320021033360 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.serialization; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.OutputStream; import org.apache.mina.common.ByteBuffer; /** * An {@link ObjectOutput} and {@link OutputStream} that can write the objects as * the serialized form that {@link ObjectSerializationDecoder} can decode. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ObjectSerializationOutputStream extends OutputStream implements ObjectOutput { private final DataOutputStream out; private int maxObjectSize = Integer.MAX_VALUE; public ObjectSerializationOutputStream(OutputStream out) { if (out == null) { throw new NullPointerException("out"); } if (out instanceof DataOutputStream) { this.out = (DataOutputStream) out; } else { this.out = new DataOutputStream(out); } } /** * Returns the allowed maximum size of the encoded object. * If the size of the encoded object exceeds this value, this encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. */ public int getMaxObjectSize() { return maxObjectSize; } /** * Sets the allowed maximum size of the encoded object. * If the size of the encoded object exceeds this value, this encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. */ public void setMaxObjectSize(int maxObjectSize) { if (maxObjectSize <= 0) { throw new IllegalArgumentException("maxObjectSize: " + maxObjectSize); } this.maxObjectSize = maxObjectSize; } public void close() throws IOException { out.close(); } public void flush() throws IOException { out.flush(); } public void write(int b) throws IOException { out.write(b); } public void write(byte[] b) throws IOException { out.write(b); } public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } public void writeObject(Object obj) throws IOException { ByteBuffer buf = ByteBuffer.allocate(64, false); buf.setAutoExpand(true); buf.putObject(obj); int objectSize = buf.position() - 4; if (objectSize > maxObjectSize) { buf.release(); throw new IllegalArgumentException( "The encoded object is too big: " + objectSize + " (> " + maxObjectSize + ')'); } out.write(buf.array(), 0, buf.position()); buf.release(); } public void writeBoolean(boolean v) throws IOException { out.writeBoolean(v); } public void writeByte(int v) throws IOException { out.writeByte(v); } public void writeBytes(String s) throws IOException { out.writeBytes(s); } public void writeChar(int v) throws IOException { out.writeChar(v); } public void writeChars(String s) throws IOException { out.writeChars(s); } public void writeDouble(double v) throws IOException { out.writeDouble(v); } public void writeFloat(float v) throws IOException { out.writeFloat(v); } public void writeInt(int v) throws IOException { out.writeInt(v); } public void writeLong(long v) throws IOException { out.writeLong(v); } public void writeShort(int v) throws IOException { out.writeShort(v); } public void writeUTF(String str) throws IOException { out.writeUTF(str); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationCodecFactory.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationCod0000644000175000017500000001015211002320021033312 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.serialization; import org.apache.mina.common.BufferDataException; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; /** * A {@link ProtocolCodecFactory} that serializes and deserializes Java objects. * This codec is very useful when you have to prototype your application rapidly * without any specific codec. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ObjectSerializationCodecFactory implements ProtocolCodecFactory { private final ObjectSerializationEncoder encoder; private final ObjectSerializationDecoder decoder; /** * Creates a new instance with the {@link ClassLoader} of * the current thread. */ public ObjectSerializationCodecFactory() { this(Thread.currentThread().getContextClassLoader()); } /** * Creates a new instance with the specified {@link ClassLoader}. */ public ObjectSerializationCodecFactory(ClassLoader classLoader) { encoder = new ObjectSerializationEncoder(); decoder = new ObjectSerializationDecoder(classLoader); } public ProtocolEncoder getEncoder() { return encoder; } public ProtocolDecoder getDecoder() { return decoder; } /** * Returns the allowed maximum size of the encoded object. * If the size of the encoded object exceeds this value, the encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. *

* This method does the same job with {@link ObjectSerializationEncoder#getMaxObjectSize()}. */ public int getEncoderMaxObjectSize() { return encoder.getMaxObjectSize(); } /** * Sets the allowed maximum size of the encoded object. * If the size of the encoded object exceeds this value, the encoder * will throw a {@link IllegalArgumentException}. The default value * is {@link Integer#MAX_VALUE}. *

* This method does the same job with {@link ObjectSerializationEncoder#setMaxObjectSize(int)}. */ public void setEncoderMaxObjectSize(int maxObjectSize) { encoder.setMaxObjectSize(maxObjectSize); } /** * Returns the allowed maximum size of the object to be decoded. * If the size of the object to be decoded exceeds this value, the * decoder will throw a {@link BufferDataException}. The default * value is 1048576 (1MB). *

* This method does the same job with {@link ObjectSerializationDecoder#getMaxObjectSize()}. */ public int getDecoderMaxObjectSize() { return decoder.getMaxObjectSize(); } /** * Sets the allowed maximum size of the object to be decoded. * If the size of the object to be decoded exceeds this value, the * decoder will throw a {@link BufferDataException}. The default * value is 1048576 (1MB). *

* This method does the same job with {@link ObjectSerializationDecoder#setMaxObjectSize(int)}. */ public void setDecoderMaxObjectSize(int maxObjectSize) { decoder.setMaxObjectSize(maxObjectSize); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationInputStream.javamina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/serialization/ObjectSerializationInp0000644000175000017500000001247011002320021033340 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.serialization; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.StreamCorruptedException; import org.apache.mina.common.BufferDataException; import org.apache.mina.common.ByteBuffer; /** * An {@link ObjectInput} and {@link InputStream} that can read the objects encoded * by {@link ObjectSerializationEncoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ObjectSerializationInputStream extends InputStream implements ObjectInput { private final DataInputStream in; private final ClassLoader classLoader; private int maxObjectSize = 1048576; public ObjectSerializationInputStream(InputStream in) { this(in, null); } public ObjectSerializationInputStream(InputStream in, ClassLoader classLoader) { if (in == null) { throw new NullPointerException("in"); } if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (in instanceof DataInputStream) { this.in = (DataInputStream) in; } else { this.in = new DataInputStream(in); } this.classLoader = classLoader; } /** * Returns the allowed maximum size of the object to be decoded. * If the size of the object to be decoded exceeds this value, this * decoder will throw a {@link BufferDataException}. The default * value is 1048576 (1MB). */ public int getMaxObjectSize() { return maxObjectSize; } /** * Sets the allowed maximum size of the object to be decoded. * If the size of the object to be decoded exceeds this value, this * decoder will throw a {@link BufferDataException}. The default * value is 1048576 (1MB). */ public void setMaxObjectSize(int maxObjectSize) { if (maxObjectSize <= 0) { throw new IllegalArgumentException("maxObjectSize: " + maxObjectSize); } this.maxObjectSize = maxObjectSize; } public int read() throws IOException { return in.read(); } public Object readObject() throws ClassNotFoundException, IOException { int objectSize = in.readInt(); if (objectSize <= 0) { throw new StreamCorruptedException("Invalid objectSize: " + objectSize); } if (objectSize > maxObjectSize) { throw new StreamCorruptedException("ObjectSize too big: " + objectSize + " (expected: <= " + maxObjectSize + ')'); } ByteBuffer buf = ByteBuffer.allocate(objectSize + 4, false); buf.putInt(objectSize); in.readFully(buf.array(), 4, objectSize); buf.position(0); buf.limit(objectSize + 4); Object answer = buf.getObject(classLoader); buf.release(); return answer; } public boolean readBoolean() throws IOException { return in.readBoolean(); } public byte readByte() throws IOException { return in.readByte(); } public char readChar() throws IOException { return in.readChar(); } public double readDouble() throws IOException { return in.readDouble(); } public float readFloat() throws IOException { return in.readFloat(); } public void readFully(byte[] b) throws IOException { in.readFully(b); } public void readFully(byte[] b, int off, int len) throws IOException { in.readFully(b, off, len); } public int readInt() throws IOException { return in.readInt(); } /** * @see DataInput#readLine() * @deprecated */ public String readLine() throws IOException { return in.readLine(); } public long readLong() throws IOException { return in.readLong(); } public short readShort() throws IOException { return in.readShort(); } public String readUTF() throws IOException { return in.readUTF(); } public int readUnsignedByte() throws IOException { return in.readUnsignedByte(); } public int readUnsignedShort() throws IOException { return in.readUnsignedShort(); } public int skipBytes(int n) throws IOException { return in.skipBytes(n); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/codec/ProtocolCodecException.java0000644000175000017500000000362611002320021031411 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; /** * An exception that is thrown when {@link ProtocolEncoder} or * {@link ProtocolDecoder} cannot understand or failed to validate * data to process. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ProtocolCodecException extends Exception { private static final long serialVersionUID = 5939878548186330695L; /** * Constructs a new instance. */ public ProtocolCodecException() { } /** * Constructs a new instance with the specified message. */ public ProtocolCodecException(String message) { super(message); } /** * Constructs a new instance with the specified cause. */ public ProtocolCodecException(Throwable cause) { super(cause); } /** * Constructs a new instance with the specified message and the specified * cause. */ public ProtocolCodecException(String message, Throwable cause) { super(message, cause); } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/filter/BlacklistFilter.java0000644000175000017500000001405611002320021026773 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.util.SessionLog; /** * A {@link IoFilter} which blocks connections from blacklisted remote * address. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 587373 $, $Date: 2007-10-23 11:54:05 +0900 (Tue, 23 Oct 2007) $ */ public class BlacklistFilter extends IoFilterAdapter { private final Set blacklist = new CopyOnWriteArraySet(); /** * Sets the addresses to be blacklisted. * * NOTE: this call will remove any previously blacklisted addresses. * * @param addresses an array of addresses to be blacklisted. */ public void setBlacklist(InetAddress... addresses) { if (addresses == null) throw new NullPointerException("addresses"); blacklist.clear(); for (int i = 0; i < addresses.length; i++) { InetAddress addr = addresses[i]; block(addr, "addresses[" + i + ']'); } } /** * Sets the addresses to be blacklisted. * * NOTE: this call will remove any previously blacklisted addresses. * * @param addresses a collection of InetAddress objects representing the * addresses to be blacklisted. * @throws IllegalArgumentException if the specified collections contains * non-{@link InetAddress} objects. */ public void setBlacklist(Collection addresses) { if (addresses == null) throw new NullPointerException("addresses"); InetAddress[] inetAddresses = new InetAddress[addresses.size()]; try { setBlacklist(addresses.toArray(inetAddresses)); } catch (ArrayStoreException ase) { IllegalArgumentException iae = new IllegalArgumentException( "Collection of addresses must contain only InetAddress instances."); iae.initCause(ase); throw iae; } } /** * Blocks the specified endpoint. */ public void block(InetAddress address, String error_string) { if (address == null) throw new NullPointerException(error_string); blacklist.add(address); } /** * Blocks the specified endpoint. */ public void block(InetAddress address) { block(address, "address"); } /** * Unblocks the specified endpoint. */ public void unblock(InetAddress address) { if (address == null) throw new NullPointerException("address"); blacklist.remove(address); } @Override public void sessionCreated(NextFilter nextFilter, IoSession session) { if (!isBlocked(session)) { // forward if not blocked nextFilter.sessionCreated(session); } else { blockSession(session); } } @Override public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception { if (!isBlocked(session)) { // forward if not blocked nextFilter.sessionOpened(session); } else { blockSession(session); } } @Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { if (!isBlocked(session)) { // forward if not blocked nextFilter.sessionClosed(session); } else { blockSession(session); } } @Override public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { if (!isBlocked(session)) { // forward if not blocked nextFilter.sessionIdle(session, status); } else { blockSession(session); } } @Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) { if (!isBlocked(session)) { // forward if not blocked nextFilter.messageReceived(session, message); } else { blockSession(session); } } @Override public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (!isBlocked(session)) { // forward if not blocked nextFilter.messageSent(session, message); } else { blockSession(session); } } private void blockSession(IoSession session) { SessionLog.info(session, "Remote address in the blacklist; closing."); session.close(); } private boolean isBlocked(IoSession session) { SocketAddress remoteAddress = session.getRemoteAddress(); if (remoteAddress instanceof InetSocketAddress) { if (blacklist.contains(((InetSocketAddress) remoteAddress) .getAddress())) { return true; } } return false; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/0000755000175000017500000000000011044712500022551 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/IdentityHashSet.java0000644000175000017500000000413511002320030026453 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import java.util.AbstractSet; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * An {@link IdentityHashMap}-backed {@link Set}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IdentityHashSet extends AbstractSet { private final Map delegate = new IdentityHashMap(); public IdentityHashSet() { } public IdentityHashSet(Collection c) { addAll(c); } @Override public int size() { return delegate.size(); } @Override public boolean contains(Object o) { //noinspection SuspiciousMethodCalls return delegate.containsKey(o); } @Override public Iterator iterator() { return delegate.keySet().iterator(); } @Override public boolean add(E arg0) { return delegate.put(arg0, Boolean.TRUE) == null; } @Override public boolean remove(Object o) { //noinspection SuspiciousMethodCalls return delegate.remove(o) != null; } @Override public void clear() { delegate.clear(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/package.html0000644000175000017500000000021311002320030025011 0ustar drazzibdrazzib Miscellaneous utility classes mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/SessionUtil.java0000644000175000017500000000300711002320030025660 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.transport.socket.nio.SocketSessionConfig; /** * A session utility * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SessionUtil { public static void initialize(IoSession session) { IoSessionConfig cfg = session.getConfig(); if (cfg instanceof SocketSessionConfig) { SocketSessionConfig sCfg = (SocketSessionConfig) cfg; sCfg.setKeepAlive(true); } } private SessionUtil() { } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/NamePreservingRunnable.java0000644000175000017500000000455411002320030030023 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link Runnable} wrapper that preserves the name of the thread after the runnable is * complete (for {@link Runnable}s that change the name of the Thread they use.) * * @author The Apache MINA Project (dev@mina.apache.org) * @version $Rev: 446581 $, $Date: 2006-09-15 11:36:12Z $, */ public class NamePreservingRunnable implements Runnable { private final Logger logger = LoggerFactory.getLogger(NamePreservingRunnable.class); private final String newName; private final Runnable runnable; public NamePreservingRunnable(Runnable runnable, String newName) { this.runnable = runnable; this.newName = newName; } public void run() { Thread currentThread = Thread.currentThread(); String oldName = currentThread.getName(); if (newName != null) { setName(currentThread, newName); } try { runnable.run(); } finally { setName(currentThread, oldName); } } /** * Wraps {@link Thread#setName(String)} to catch a possible {@link Exception}s such as * {@link SecurityException} in sandbox environments, such as applets */ private void setName(Thread thread, String name) { try { thread.setName(name); } catch (Exception e) { // Probably SecurityException. if (logger.isWarnEnabled()) { logger.warn("Failed to set the thread name.", e); } } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/ExpiringMap.java0000644000175000017500000002416611002320030025633 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * A map with expiration. * * @author The Apache Directory Project (mina-dev@directory.apache.org) */ public class ExpiringMap implements Map { public static final int DEFAULT_TIME_TO_LIVE = 60; public static final int DEFAULT_EXPIRATION_INTERVAL = 1; private static volatile int expirerCount = 1; private final ConcurrentHashMap delegate; private final CopyOnWriteArrayList expirationListeners; private final Expirer expirer; public ExpiringMap() { this(DEFAULT_TIME_TO_LIVE, DEFAULT_EXPIRATION_INTERVAL); } public ExpiringMap(int timeToLive) { this(timeToLive, DEFAULT_EXPIRATION_INTERVAL); } public ExpiringMap(int timeToLive, int expirationInterval) { this(new ConcurrentHashMap(), new CopyOnWriteArrayList(), timeToLive, expirationInterval); } private ExpiringMap(ConcurrentHashMap delegate, CopyOnWriteArrayList expirationListeners, int timeToLive, int expirationInterval) { this.delegate = delegate; this.expirationListeners = expirationListeners; this.expirer = new Expirer(); expirer.setTimeToLive(timeToLive); expirer.setExpirationInterval(expirationInterval); } public V put(K key, V value) { ExpiringObject answer = delegate.put(key, new ExpiringObject(key, value, System.currentTimeMillis())); if (answer == null) { return null; } return answer.getValue(); } public V get(Object key) { ExpiringObject object = delegate.get(key); if (object != null) { object.setLastAccessTime(System.currentTimeMillis()); return object.getValue(); } return null; } public V remove(Object key) { ExpiringObject answer = delegate.remove(key); if (answer == null) { return null; } return answer.getValue(); } public boolean containsKey(Object key) { return delegate.containsKey(key); } public boolean containsValue(Object value) { return delegate.containsValue(value); } public int size() { return delegate.size(); } public boolean isEmpty() { return delegate.isEmpty(); } public void clear() { delegate.clear(); } @Override public int hashCode() { return delegate.hashCode(); } public Set keySet() { return delegate.keySet(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } public void putAll(Map inMap) { for (Entry e : inMap.entrySet()) { this.put(e.getKey(), e.getValue()); } } public Collection values() { throw new UnsupportedOperationException(); } public Set> entrySet() { throw new UnsupportedOperationException(); } public void addExpirationListener(ExpirationListener listener) { expirationListeners.add(listener); } public void removeExpirationListener( ExpirationListener listener) { expirationListeners.remove(listener); } public Expirer getExpirer() { return expirer; } public int getExpirationInterval() { return expirer.getExpirationInterval(); } public int getTimeToLive() { return expirer.getTimeToLive(); } public void setExpirationInterval(int expirationInterval) { expirer.setExpirationInterval(expirationInterval); } public void setTimeToLive(int timeToLive) { expirer.setTimeToLive(timeToLive); } private class ExpiringObject { private K key; private V value; private long lastAccessTime; private ReadWriteLock lastAccessTimeLock = new ReentrantReadWriteLock(); ExpiringObject(K key, V value, long lastAccessTime) { if (value == null) { throw new IllegalArgumentException( "An expiring object cannot be null."); } this.key = key; this.value = value; this.lastAccessTime = lastAccessTime; } public long getLastAccessTime() { lastAccessTimeLock.readLock().lock(); try { return lastAccessTime; } finally { lastAccessTimeLock.readLock().unlock(); } } public void setLastAccessTime(long lastAccessTime) { lastAccessTimeLock.writeLock().lock(); try { this.lastAccessTime = lastAccessTime; } finally { lastAccessTimeLock.writeLock().unlock(); } } public K getKey() { return key; } public V getValue() { return value; } @Override public boolean equals(Object obj) { return value.equals(obj); } @Override public int hashCode() { return value.hashCode(); } } public class Expirer implements Runnable { private ReadWriteLock stateLock = new ReentrantReadWriteLock(); private long timeToLiveMillis; private long expirationIntervalMillis; private boolean running = false; private final Thread expirerThread; public Expirer() { expirerThread = new Thread(this, "ExpiringMapExpirer-" + (expirerCount++)); expirerThread.setDaemon(true); } public void run() { while (running) { processExpires(); try { Thread.sleep(expirationIntervalMillis); } catch (InterruptedException e) { } } } private void processExpires() { long timeNow = System.currentTimeMillis(); for (ExpiringObject o : delegate.values()) { if (timeToLiveMillis <= 0) continue; long timeIdle = timeNow - o.getLastAccessTime(); if (timeIdle >= timeToLiveMillis) { delegate.remove(o.getKey()); for (ExpirationListener listener : expirationListeners) { listener.expired(o.getValue()); } } } } public void startExpiring() { stateLock.writeLock().lock(); try { if (!running) { running = true; expirerThread.start(); } } finally { stateLock.writeLock().unlock(); } } public void startExpiringIfNotStarted() { stateLock.readLock().lock(); try { if (running) { return; } } finally { stateLock.readLock().unlock(); } stateLock.writeLock().lock(); try { if (!running) { running = true; expirerThread.start(); } } finally { stateLock.writeLock().unlock(); } } public void stopExpiring() { stateLock.writeLock().lock(); try { if (running) { running = false; expirerThread.interrupt(); } } finally { stateLock.writeLock().unlock(); } } public boolean isRunning() { stateLock.readLock().lock(); try { return running; } finally { stateLock.readLock().unlock(); } } public int getTimeToLive() { stateLock.readLock().lock(); try { return (int) timeToLiveMillis / 1000; } finally { stateLock.readLock().unlock(); } } public void setTimeToLive(long timeToLive) { stateLock.writeLock().lock(); try { this.timeToLiveMillis = timeToLive * 1000; } finally { stateLock.writeLock().unlock(); } } public int getExpirationInterval() { stateLock.readLock().lock(); try { return (int) expirationIntervalMillis / 1000; } finally { stateLock.readLock().unlock(); } } public void setExpirationInterval(long expirationInterval) { stateLock.writeLock().lock(); try { this.expirationIntervalMillis = expirationInterval * 1000; } finally { stateLock.writeLock().unlock(); } } } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/ByteBufferUtil.java0000644000175000017500000000273211002320030026276 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import org.apache.mina.common.ByteBuffer; /** * ByteBuffer utility. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 560326 $, $Date: 2007-07-28 02:30:25 +0900 (Sat, 28 Jul 2007) $ */ public class ByteBufferUtil { public static void acquireIfPossible(Object message) { if (message instanceof ByteBuffer) { ((ByteBuffer) message).acquire(); } } public static void releaseIfPossible(Object message) { if (message instanceof ByteBuffer) { ((ByteBuffer) message).release(); } } private ByteBufferUtil() { } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/AnonymousSocketAddress.java0000644000175000017500000000333411002320030030051 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import java.net.SocketAddress; /** * A {@link SocketAddress} which represents anonymous address. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class AnonymousSocketAddress extends SocketAddress implements Comparable { private static final long serialVersionUID = 3978421416766944048L; /** * Creates a new instance with the specifid port number. */ public AnonymousSocketAddress() { } public int hashCode() { return System.identityHashCode(this); } public boolean equals(Object o) { return this == o; } public int compareTo(Object o) { return this.hashCode() - ((AnonymousSocketAddress) o).hashCode(); } public String toString() { return "anonymous(" + hashCode() + ')'; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/ExpiringStack.java0000644000175000017500000001024611002320030026155 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import java.io.Serializable; import java.util.Arrays; /** * A unbounded stack with expiration. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ExpiringStack implements Serializable { private static final long serialVersionUID = 3546919169401434168L; private static final int DEFAULT_CAPACITY = 4; private Object[] items; private long[] timestamps; private int size = 0; /** * Construct a new, empty stack. */ public ExpiringStack() { items = new Object[DEFAULT_CAPACITY]; timestamps = new long[DEFAULT_CAPACITY]; } /** * Clears this stack. */ public void clear() { Arrays.fill(items, null); size = 0; } /** * Pops from this stack. * * @return null, if this stack is empty or the element is * really null. */ public Object pop() { if (size == 0) { return null; } int pos = size - 1; Object ret = items[pos]; items[pos] = null; size--; return ret; } /** * Push into this stack. */ public void push(Object obj) { if (size == items.length) { // expand queue final int oldLen = items.length; Object[] tmpItems = new Object[oldLen * 2]; System.arraycopy(items, 0, tmpItems, 0, size); long[] tmpTimestamps = new long[oldLen * 2]; System.arraycopy(timestamps, 0, tmpTimestamps, 0, size); items = tmpItems; timestamps = tmpTimestamps; } items[size] = obj; timestamps[size] = System.currentTimeMillis(); size++; } public void remove(Object o) { for (int i = size - 1; i >= 0; i--) { if (items[i] == o) { System.arraycopy(items, i + 1, items, i, size - i - 1); System .arraycopy(timestamps, i + 1, timestamps, i, size - i - 1); items[size - 1] = null; size--; break; } } } public void expireBefore(long time) { int i; for (i = 0; i < size; i++) { if (timestamps[i] >= time) { break; } } if (i > 0) { size -= i; System.arraycopy(items, i, items, 0, size); System.arraycopy(timestamps, i, timestamps, 0, size); Arrays.fill(items, size, items.length, null); } } /** * Returns the first element of the stack. * * @return null, if the stack is empty, or the element is * really null. */ public Object first() { if (size == 0) { return null; } return items[size - 1]; } public Object last() { if (size == 0) { return null; } return items[0]; } /** * Returns true if the stack is empty. */ public boolean isEmpty() { return (size == 0); } /** * Returns the number of elements in the stack. */ public int size() { return size; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/ExpirationListener.java0000644000175000017500000000213511002320030027230 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; /** * A listener for expired object events. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * TODO Make this a inner interface of ExpiringMap */ public interface ExpirationListener { void expired(E expiredObject); } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/AvailablePortFinder.java0000644000175000017500000001217511002320030027262 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeSet; /** * Finds currently available server ports. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $ * @see IANA.org */ public class AvailablePortFinder { /** * The minimum number of server port number. */ public static final int MIN_PORT_NUMBER = 1; /** * The maximum number of server port number. */ public static final int MAX_PORT_NUMBER = 49151; /** * Creates a new instance. */ private AvailablePortFinder() { } /** * Returns the {@link Set} of currently available port numbers * ({@link Integer}). This method is identical to * getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER). * * WARNING: this can take a very long time. */ public static Set getAvailablePorts() { return getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER); } /** * Gets the next available port starting at the lowest port number. * * @throws NoSuchElementException if there are no ports available */ public static int getNextAvailable() { return getNextAvailable(MIN_PORT_NUMBER); } /** * Gets the next available port starting at a port. * * @param fromPort the port to scan for availability * @throws NoSuchElementException if there are no ports available */ public static int getNextAvailable(int fromPort) { if ((fromPort < MIN_PORT_NUMBER) || (fromPort > MAX_PORT_NUMBER)) { throw new IllegalArgumentException("Invalid start port: " + fromPort); } for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) { if (available(i)) { return i; } } throw new NoSuchElementException("Could not find an available port " + "above " + fromPort); } /** * Checks to see if a specific port is available. * * @param port the port to check for availability */ public static boolean available(int port) { if ((port < MIN_PORT_NUMBER) || (port > MAX_PORT_NUMBER)) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; } /** * Returns the {@link Set} of currently avaliable port numbers ({@link Integer}) * between the specified port range. * * @throws IllegalArgumentException if port range is not between * {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER} or * fromPort if greater than toPort. */ public static Set getAvailablePorts(int fromPort, int toPort) { if ((fromPort < MIN_PORT_NUMBER) || (toPort > MAX_PORT_NUMBER) || (fromPort > toPort)) { throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort); } Set result = new TreeSet(); for (int i = fromPort; i <= toPort; i++) { ServerSocket s = null; try { s = new ServerSocket(i); result.add(new Integer(i)); } catch (IOException e) { } finally { if (s != null) { try { s.close(); } catch (IOException e) { /* should not be thrown */ } } } } return result; } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/NewThreadExecutor.java0000644000175000017500000000227511002320030027005 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.util; import java.util.concurrent.Executor; /** * An Executor that just launches in a new thread. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 446581 $, $Date: 2006-09-15 11:36:12Z $, */ public class NewThreadExecutor implements Executor { public void execute(Runnable command) { new Thread(command).start(); } } mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/Stack.java0000644000175000017500000000642611002320030024454 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import java.io.Serializable; import java.util.Arrays; /** * A unbounded stack. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Stack implements Serializable { private static final long serialVersionUID = 3546919169401434168L; private static final int DEFAULT_CAPACITY = 4; private Object[] items; private int size = 0; /** * Construct a new, empty stack. */ public Stack() { items = new Object[DEFAULT_CAPACITY]; } /** * Clears this stack. */ public void clear() { Arrays.fill(items, null); size = 0; } /** * Pops from this stack. * * @return null, if this stack is empty or the element is * really null. */ public Object pop() { if (size == 0) { return null; } int pos = size - 1; Object ret = items[pos]; items[pos] = null; size--; return ret; } /** * Push into this stack. */ public void push(Object obj) { if (size == items.length) { // expand queue final int oldLen = items.length; Object[] tmp = new Object[oldLen * 2]; System.arraycopy(items, 0, tmp, 0, size); items = tmp; } items[size] = obj; size++; } public void remove(Object o) { for (int i = size - 1; i >= 0; i--) { if (items[i] == o) { System.arraycopy(items, i + 1, items, i, size - i - 1); items[size - 1] = null; size--; break; } } } /** * Returns the first element of the stack. * * @return null, if the stack is empty, or the element is * really null. */ public Object first() { if (size == 0) { return null; } return items[size - 1]; } public Object last() { if (size == 0) { return null; } return items[0]; } /** * Returns true if the stack is empty. */ public boolean isEmpty() { return (size == 0); } /** * Returns the number of elements in the stack. */ public int size() { return size; } }mina-1.1.7.dfsg/core/src/main/java/org/apache/mina/util/SessionLog.java0000644000175000017500000001130611002320030025465 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import org.apache.mina.common.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides utility methods to log protocol-specific messages. *

* Set {@link #PREFIX} and {@link #LOGGER} session attributes * to override prefix string and logger. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * */ public class SessionLog { /** * Session attribute key: prefix string */ public static final String PREFIX = SessionLog.class.getName() + ".prefix"; /** * Session attribute key: {@link Logger} */ public static final String LOGGER = SessionLog.class.getName() + ".logger"; private static Class getClass(IoSession session) { return session.getHandler().getClass(); } public static void debug(IoSession session, String message) { Logger log = getLogger(session); if (log.isDebugEnabled()) { log.debug(String.valueOf(session.getAttribute(PREFIX)) + message); } } public static void debug(IoSession session, String message, Throwable cause) { Logger log = getLogger(session); if (log.isDebugEnabled()) { log.debug(String.valueOf(session.getAttribute(PREFIX)) + message, cause); } } public static void info(IoSession session, String message) { Logger log = getLogger(session); if (log.isInfoEnabled()) { log.info(String.valueOf(session.getAttribute(PREFIX)) + message); } } public static void info(IoSession session, String message, Throwable cause) { Logger log = getLogger(session); if (log.isInfoEnabled()) { log.info(String.valueOf(session.getAttribute(PREFIX)) + message, cause); } } public static void warn(IoSession session, String message) { Logger log = getLogger(session); if (log.isWarnEnabled()) { log.warn(String.valueOf(session.getAttribute(PREFIX)) + message); } } public static void warn(IoSession session, String message, Throwable cause) { Logger log = getLogger(session); if (log.isWarnEnabled()) { log.warn(String.valueOf(session.getAttribute(PREFIX)) + message, cause); } } public static void error(IoSession session, String message) { Logger log = getLogger(session); if (log.isErrorEnabled()) { log.error(String.valueOf(session.getAttribute(PREFIX)) + message); } } public static void error(IoSession session, String message, Throwable cause) { Logger log = getLogger(session); if (log.isErrorEnabled()) { log.error(String.valueOf(session.getAttribute(PREFIX)) + message, cause); } } public static boolean isDebugEnabled(IoSession session) { return getLogger(session).isDebugEnabled(); } public static boolean isInfoEnabled(IoSession session) { return getLogger(session).isInfoEnabled(); } public static boolean isWarnEnabled(IoSession session) { return getLogger(session).isWarnEnabled(); } public static boolean isErrorEnabled(IoSession session) { return getLogger(session).isErrorEnabled(); } private static Logger getLogger(IoSession session) { Logger log = (Logger) session.getAttribute(LOGGER); if (log == null) { log = LoggerFactory.getLogger(getClass(session)); String prefix = (String) session.getAttribute(PREFIX); if (prefix == null) { prefix = "[" + session.getRemoteAddress() + "] "; session.setAttribute(PREFIX, prefix); } session.setAttribute(LOGGER, log); } return log; } } mina-1.1.7.dfsg/core/src/test/0000755000175000017500000000000011002320016015741 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/0000755000175000017500000000000011002320016016662 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/0000755000175000017500000000000011002320016017451 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/0000755000175000017500000000000011002320016020672 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/0000755000175000017500000000000011002320020021611 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/0000755000175000017500000000000011044712500023663 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/AbstractConnectorTest.java0000644000175000017500000000724311002320020030774 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport; import java.net.InetSocketAddress; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.util.AvailablePortFinder; /** * Tests a generic {@link IoConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public abstract class AbstractConnectorTest extends TestCase { protected abstract IoAcceptor createAcceptor(); protected abstract IoConnector createConnector(); public void testConnectFutureSuccessTiming() throws Exception { int port = AvailablePortFinder.getNextAvailable(1025); IoAcceptor acceptor = createAcceptor(); acceptor.bind(new InetSocketAddress(port), new IoHandlerAdapter()); try { final StringBuffer buf = new StringBuffer(); IoConnector connector = createConnector(); ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), new IoHandlerAdapter() { public void sessionCreated(IoSession session) { buf.append("1"); } public void sessionOpened(IoSession session) { buf.append("2"); } public void exceptionCaught(IoSession session, Throwable cause) { buf.append("X"); } }); future.join(); buf.append("3"); future.getSession().close(); Assert.assertEquals("123", buf.toString()); } finally { acceptor.unbind(new InetSocketAddress(port)); } } public void testConnectFutureFailureTiming() throws Exception { int port = AvailablePortFinder.getNextAvailable(1025); final StringBuffer buf = new StringBuffer(); IoConnector connector = createConnector(); ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), new IoHandlerAdapter() { public void sessionCreated(IoSession session) { buf.append("X"); } public void sessionOpened(IoSession session) { buf.append("Y"); } public void exceptionCaught(IoSession session, Throwable cause) { buf.append("Z"); } }); future.join(); buf.append("1"); try { future.getSession().close(); fail(); } catch (RuntimeIOException e) { // OK. } Assert.assertEquals("1", buf.toString()); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/vmpipe/0000755000175000017500000000000011044712500025163 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/vmpipe/VmPipeTrafficControlTest.java0000644000175000017500000000361511002320017032723 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe; import java.net.SocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandler; import org.apache.mina.transport.AbstractTrafficControlTest; /** * Tests suspending and resuming reads and writes for the * {@link org.apache.mina.common.TransportType#VM_PIPE} transport type. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Id: VmPipeTrafficControlTest.java 555855 2007-07-13 03:19:00Z trustin $ */ public class VmPipeTrafficControlTest extends AbstractTrafficControlTest { public VmPipeTrafficControlTest() { super(new VmPipeAcceptor()); } protected ConnectFuture connect(int port, IoHandler handler) throws Exception { IoConnector connector = new VmPipeConnector(); SocketAddress addr = new VmPipeAddress(port); return connector.connect(addr, handler); } protected SocketAddress createServerSocketAddress(int port) { return new VmPipeAddress(port); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/vmpipe/VmPipeBindTest.java0000644000175000017500000000573211002320017030662 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe; import java.net.SocketAddress; import java.util.Collection; import junit.framework.Assert; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.transport.AbstractBindTest; /** * Tests {@link VmPipeAcceptor} bind and unbind. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class VmPipeBindTest extends AbstractBindTest { public VmPipeBindTest() { super(new VmPipeAcceptor()); } protected SocketAddress createSocketAddress(int port) { return new VmPipeAddress(port); } protected int getPort(SocketAddress address) { return ((VmPipeAddress) address).getPort(); } public void testUnbindDisconnectsClients() throws Exception { // TODO: This test is almost identical to the test with the same name in SocketBindTest bind(false); SocketAddress addr = createSocketAddress(port); IoConnector connector = new VmPipeConnector(); IoSession[] sessions = new IoSession[5]; for (int i = 0; i < sessions.length; i++) { ConnectFuture future = connector.connect(addr, new IoHandlerAdapter()); future.join(); sessions[i] = future.getSession(); Assert.assertTrue(sessions[i].isConnected()); } // Wait for the server side sessions to be created. Thread.sleep(500); Collection managedSessions = acceptor.getManagedSessions(addr); Assert.assertEquals(5, managedSessions.size()); // Make sure it's the server side sessions we get when calling getManagedSessions() for (int i = 0; i < sessions.length; i++) { Assert.assertFalse(managedSessions.contains(sessions[i])); } acceptor.unbind(addr); // Wait for the client side sessions to close. Thread.sleep(500); for (int i = 0; i < sessions.length; i++) { Assert.assertFalse(sessions[i].isConnected()); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/vmpipe/VmPipeEventOrderTest.java0000644000175000017500000001645711002320017032071 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.vmpipe; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.ThreadModel; /** * Makes sure if the order of event is correct. * * @author The Apache MINA Project Team (dev@mina.apache.org) * @version $Rev: 635494 $, $Date: 2008-03-10 18:04:45 +0900 (Mon, 10 Mar 2008) $ */ public class VmPipeEventOrderTest extends TestCase { public void testServerToClient() throws Exception { IoAcceptor acceptor = new VmPipeAcceptor(); acceptor.getDefaultConfig().setThreadModel(ThreadModel.MANUAL); //acceptor.getFilterChain().addLast( "logger", new LoggingFilter() ); IoConnector connector = new VmPipeConnector(); connector.getDefaultConfig().setThreadModel(ThreadModel.MANUAL); //connector.getFilterChain().addLast( "logger", new LoggingFilter() ); acceptor.bind(new VmPipeAddress(1), new IoHandlerAdapter() { public void sessionOpened(IoSession session) throws Exception { session.write("B"); } public void messageSent(IoSession session, Object message) throws Exception { session.close(); } }); final StringBuffer actual = new StringBuffer(); ConnectFuture future = connector.connect(new VmPipeAddress(1), new IoHandlerAdapter() { public void messageReceived(IoSession session, Object message) throws Exception { actual.append(message); } public void sessionClosed(IoSession session) throws Exception { actual.append("C"); } public void sessionOpened(IoSession session) throws Exception { actual.append("A"); } }); future.join(); future.getSession().getCloseFuture().join(); acceptor.unbindAll(); // sessionClosed() might not be invoked yet // even if the connection is closed. while (actual.indexOf("C") < 0) { Thread.yield(); } Assert.assertEquals("ABC", actual.toString()); } public void testClientToServer() throws Exception { IoAcceptor acceptor = new VmPipeAcceptor(); acceptor.getDefaultConfig().setThreadModel(ThreadModel.MANUAL); //acceptor.getFilterChain().addLast( "logger", new LoggingFilter() ); IoConnector connector = new VmPipeConnector(); connector.getDefaultConfig().setThreadModel(ThreadModel.MANUAL); //connector.getFilterChain().addLast( "logger", new LoggingFilter() ); final StringBuffer actual = new StringBuffer(); acceptor.bind(new VmPipeAddress(1), new IoHandlerAdapter() { public void messageReceived(IoSession session, Object message) throws Exception { actual.append(message); } public void sessionClosed(IoSession session) throws Exception { actual.append("C"); } public void sessionOpened(IoSession session) throws Exception { actual.append("A"); } }); ConnectFuture future = connector.connect(new VmPipeAddress(1), new IoHandlerAdapter() { public void sessionOpened(IoSession session) throws Exception { session.write("B"); } public void messageSent(IoSession session, Object message) throws Exception { session.close(); } }); future.join(); future.getSession().getCloseFuture().join(); acceptor.unbindAll(); // sessionClosed() might not be invoked yet // even if the connection is closed. while (actual.indexOf("C") < 0) { Thread.yield(); } Assert.assertEquals("ABC", actual.toString()); } public void testSessionCreated() throws Exception { final Semaphore semaphore = new Semaphore(0); final StringBuffer stringBuffer = new StringBuffer(); VmPipeAcceptor vmPipeAcceptor = new VmPipeAcceptor(); vmPipeAcceptor.getDefaultConfig().setThreadModel(ThreadModel.MANUAL); final VmPipeAddress vmPipeAddress = new VmPipeAddress(12345); vmPipeAcceptor.bind(vmPipeAddress, new IoHandlerAdapter() { @Override public void sessionCreated(IoSession session) throws Exception { // pretend we are doing some time-consuming work. For // performance reasons, you would never want to do time // consuming work in sessionCreated. // However, this increases the likelihood of the timing bug. Thread.sleep(1000); stringBuffer.append("A"); } @Override public void sessionOpened(IoSession session) throws Exception { stringBuffer.append("B"); } @Override public void messageReceived(IoSession session, Object message) throws Exception { stringBuffer.append("C"); } @Override public void sessionClosed(IoSession session) throws Exception { stringBuffer.append("D"); semaphore.release(); } }); final VmPipeConnector vmPipeConnector = new VmPipeConnector(); ConnectFuture connectFuture = vmPipeConnector.connect(vmPipeAddress, new IoHandlerAdapter() { @Override public void sessionOpened(IoSession session) throws Exception { session.write(ByteBuffer.wrap(new byte[1])); } }); connectFuture.join(); connectFuture.getSession().close(); semaphore.tryAcquire(1, TimeUnit.SECONDS); vmPipeAcceptor.unbind(vmPipeAddress); Assert.assertEquals("ABCD", stringBuffer.toString()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/vmpipe/VmPipeSessionCrossCommunicationTest.javamina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/vmpipe/VmPipeSessionCrossCommunicationT0000644000175000017500000001372011002320017033531 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.transport.vmpipe; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.ThreadModel; import junit.framework.TestCase; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class VmPipeSessionCrossCommunicationTest extends TestCase { public void testOneSessionTalkingBackAndForthDoesNotDeadlock() throws Exception { final VmPipeAddress address = new VmPipeAddress( 1 ); final IoConnector connector = new VmPipeConnector(); final AtomicReference c1 = new AtomicReference(); final CountDownLatch latch = new CountDownLatch( 1 ); final CountDownLatch messageCount = new CountDownLatch( 2 ); IoAcceptor acceptor = new VmPipeAcceptor(); acceptor.bind( address, new IoHandlerAdapter() { @Override public void messageReceived( IoSession session, Object message ) throws Exception { System.out.println( Thread.currentThread().getName() + ": " + message ); if ( "start".equals( message ) ) { session.write( "open new" ); } else if ( "re-use c1".equals( message ) ) { session.write( "tell me something on c1 now" ); } else if ( ( (String) message ).startsWith( "please don't deadlock" ) ) { messageCount.countDown(); } else { fail( "unexpected message received " + message ); } } } ); connector.getDefaultConfig().setThreadModel( ThreadModel.MANUAL ); ConnectFuture future = connector.connect( address, new IoHandlerAdapter() { @Override public void messageReceived( IoSession session, Object message ) throws Exception { System.out.println( Thread.currentThread().getName() + ": " + message ); if ( "open new".equals( message ) ) { System.out.println( "opening c2 from " + Thread.currentThread().getName() ); ConnectFuture c2Future = connector.connect( address, new IoHandlerAdapter() { @Override public void sessionOpened( IoSession session ) throws Exception { session.write( "re-use c1" ); } @Override public void messageReceived( IoSession session, Object message ) throws Exception { System.out.println( Thread.currentThread().getName() + ": " + message ); if ( "tell me something on c1 now".equals( message ) ) { latch.countDown(); c1.get().write( "please don't deadlock via c1" ); } else { fail( "unexpected message received " + message ); } } } ); c2Future.join(); latch.await(); c2Future.getSession().write( "please don't deadlock via c2" ); } else { fail( "unexpeced message received " + message ); } } } ); future.join(); c1.set( future.getSession() ); c1.get().write( "start" ); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); while ( !messageCount.await( 100, TimeUnit.MILLISECONDS ) ) { long[] threads = threadMXBean.findMonitorDeadlockedThreads(); if ( null != threads ) { StringBuffer sb = new StringBuffer( 256 ); ThreadInfo[] infos = threadMXBean.getThreadInfo( threads, Integer.MAX_VALUE ); for ( ThreadInfo info : infos ) { sb.append( info.getThreadName() ) .append( " blocked on " ) .append( info.getLockName() ) .append( " owned by " ) .append( info.getLockOwnerName() ) .append( "\n" ); } for ( ThreadInfo info : infos ) { sb.append( "\nStack for " ).append( info.getThreadName() ).append( "\n" ); for ( StackTraceElement element : info.getStackTrace() ) { sb.append( "\t" ).append( element ).append( "\n" ); } } fail( "deadlocked! \n" + sb ); } } ( (IoAcceptorConfig) acceptor.getDefaultConfig() ).setDisconnectOnUnbind( false ); acceptor.unbindAll(); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/AbstractTrafficControlTest.java0000644000175000017500000001701211002320020031754 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport; import java.net.SocketAddress; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.TransportType; import org.apache.mina.util.AvailablePortFinder; /** * Abstract base class for testing suspending and resuming reads and * writes. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public abstract class AbstractTrafficControlTest extends TestCase { protected int port = 0; protected IoAcceptor acceptor; protected TransportType transportType; public AbstractTrafficControlTest(IoAcceptor acceptor) { this.acceptor = acceptor; } protected void setUp() throws Exception { super.setUp(); port = AvailablePortFinder.getNextAvailable(); acceptor.bind(createServerSocketAddress(port), new ServerIoHandler()); } protected void tearDown() throws Exception { super.tearDown(); acceptor.unbind(createServerSocketAddress(port)); } protected abstract ConnectFuture connect(int port, IoHandler handler) throws Exception; protected abstract SocketAddress createServerSocketAddress(int port); public void testSuspendResumeReadWrite() throws Exception { ConnectFuture future = connect(port, new ClientIoHandler()); future.join(); IoSession session = future.getSession(); // We wait for the sessionCreated() event is fired becayse we cannot guarentee that // it is invoked already. while (session.getAttribute("lock") == null) { Thread.yield(); } Object lock = session.getAttribute("lock"); synchronized (lock) { write(session, "1"); assertEquals('1', read(session)); assertEquals("1", getReceived(session)); assertEquals("1", getSent(session)); session.suspendRead(); write(session, "2"); assertFalse(canRead(session)); assertEquals("1", getReceived(session)); assertEquals("12", getSent(session)); session.suspendWrite(); write(session, "3"); assertFalse(canRead(session)); assertEquals("1", getReceived(session)); assertEquals("12", getSent(session)); session.resumeRead(); write(session, "4"); assertEquals('2', read(session)); assertEquals("12", getReceived(session)); assertEquals("12", getSent(session)); session.resumeWrite(); assertEquals('3', read(session)); assertEquals('4', read(session)); write(session, "5"); assertEquals('5', read(session)); assertEquals("12345", getReceived(session)); assertEquals("12345", getSent(session)); session.suspendWrite(); write(session, "6"); assertFalse(canRead(session)); assertEquals("12345", getReceived(session)); assertEquals("12345", getSent(session)); session.suspendRead(); session.resumeWrite(); write(session, "7"); assertFalse(canRead(session)); assertEquals("12345", getReceived(session)); assertEquals("1234567", getSent(session)); session.resumeRead(); assertEquals('6', read(session)); assertEquals('7', read(session)); assertEquals("1234567", getReceived(session)); assertEquals("1234567", getSent(session)); } session.close().join(); } private void write(IoSession session, String s) throws Exception { session.write(ByteBuffer.wrap(s.getBytes("ASCII"))); } private int read(IoSession session) throws Exception { int pos = ((Integer) session.getAttribute("pos")).intValue(); for (int i = 0; i < 10 && pos == getReceived(session).length(); i++) { Object lock = session.getAttribute("lock"); lock.wait(200); } session.setAttribute("pos", new Integer(pos + 1)); return getReceived(session).charAt(pos); } private boolean canRead(IoSession session) throws Exception { int pos = ((Integer) session.getAttribute("pos")).intValue(); Object lock = session.getAttribute("lock"); lock.wait(250); String received = getReceived(session); return pos < received.length(); } private String getReceived(IoSession session) throws Exception { return session.getAttribute("received").toString(); } private String getSent(IoSession session) throws Exception { return session.getAttribute("sent").toString(); } public static class ClientIoHandler extends IoHandlerAdapter { public void sessionCreated(IoSession session) throws Exception { super.sessionCreated(session); session.setAttribute("pos", new Integer(0)); session.setAttribute("received", new StringBuffer()); session.setAttribute("sent", new StringBuffer()); session.setAttribute("lock", new Object()); } public void messageReceived(IoSession session, Object message) throws Exception { ByteBuffer buffer = (ByteBuffer) message; byte[] data = new byte[buffer.remaining()]; buffer.get(data); Object lock = session.getAttribute("lock"); synchronized (lock) { StringBuffer sb = (StringBuffer) session .getAttribute("received"); sb.append(new String(data, "ASCII")); lock.notifyAll(); } } public void messageSent(IoSession session, Object message) throws Exception { ByteBuffer buffer = (ByteBuffer) message; buffer.rewind(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); StringBuffer sb = (StringBuffer) session.getAttribute("sent"); sb.append(new String(data, "ASCII")); } } private static class ServerIoHandler extends IoHandlerAdapter { public void messageReceived(IoSession session, Object message) throws Exception { // Just echo the received bytes. ByteBuffer rb = (ByteBuffer) message; ByteBuffer wb = ByteBuffer.allocate(rb.remaining()); wb.put(rb); wb.flip(); session.write(wb); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/AbstractBindTest.java0000644000175000017500000001603211002320020027712 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport; import java.io.IOException; import java.net.SocketAddress; import java.util.Date; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.transport.socket.nio.DatagramAcceptor; import org.apache.mina.transport.socket.nio.DatagramSessionConfig; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.apache.mina.transport.socket.nio.SocketSessionConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tests {@link IoAcceptor} resource leakage by repeating bind and unbind. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class AbstractBindTest extends TestCase { protected final IoAcceptor acceptor; protected int port; public AbstractBindTest(IoAcceptor acceptor) { this.acceptor = acceptor; } protected abstract SocketAddress createSocketAddress(int port); protected abstract int getPort(SocketAddress address); protected void bind(boolean reuseAddress) throws IOException { setReuseAddress(reuseAddress); // Find an availble test port and bind to it. boolean socketBound = false; // Let's start from port #1 to detect possible resource leak // because test will fail in port 1-1023 if user run this test // as a normal user. for (port = 1; port <= 65535; port++) { socketBound = false; try { acceptor.bind(createSocketAddress(port), new EchoProtocolHandler()); socketBound = true; break; } catch (IOException e) { } } // If there is no port available, test fails. if (!socketBound) { throw new IOException("Cannot bind any test port."); } //System.out.println( "Using port " + port + " for testing." ); } private void setReuseAddress(boolean reuseAddress) { if (acceptor instanceof DatagramAcceptor) { ((DatagramSessionConfig) acceptor.getDefaultConfig() .getSessionConfig()).setReuseAddress(reuseAddress); } else if (acceptor instanceof SocketAcceptor) { ((SocketAcceptorConfig) acceptor.getDefaultConfig()) .setReuseAddress(reuseAddress); } } public void tearDown() { try { acceptor.unbindAll(); } catch (Exception e) { // ignore } } public void testAnonymousBind() throws Exception { acceptor.bind(null, new IoHandlerAdapter()); Assert.assertEquals(1, acceptor.getManagedServiceAddresses().size()); acceptor.unbindAll(); Thread.sleep(500); Assert.assertEquals(0, acceptor.getManagedServiceAddresses().size()); acceptor.bind(createSocketAddress(0), new IoHandlerAdapter()); Assert.assertEquals(1, acceptor.getManagedServiceAddresses().size()); SocketAddress address = acceptor.getManagedServiceAddresses() .iterator().next(); Assert.assertTrue(getPort(address) != 0); acceptor.unbind(address); } public void testDuplicateBind() throws IOException { bind(false); try { acceptor.bind(createSocketAddress(port), new EchoProtocolHandler()); Assert.fail("IOException is not thrown"); } catch (IOException e) { } } public void testDuplicateUnbind() throws IOException { bind(false); // this should succeed acceptor.unbind(createSocketAddress(port)); try { // this should fail acceptor.unbind(createSocketAddress(port)); Assert.fail("Exception is not thrown"); } catch (Exception e) { } } public void testManyTimes() throws IOException { bind(true); SocketAddress addr = createSocketAddress(port); EchoProtocolHandler handler = new EchoProtocolHandler(); for (int i = 0; i < 1024; i++) { acceptor.unbind(addr); acceptor.bind(addr, handler); } } public void _testRegressively() throws IOException { setReuseAddress(true); SocketAddress addr = createSocketAddress(port); EchoProtocolHandler handler = new EchoProtocolHandler(); for (int i = 0; i < 1048576; i++) { acceptor.bind(addr, handler); testDuplicateBind(); testDuplicateUnbind(); if (i % 100 == 0) { System.out.println(i + " (" + new Date() + ")"); } } bind(false); } private static class EchoProtocolHandler extends IoHandlerAdapter { private static final Logger log = LoggerFactory .getLogger(EchoProtocolHandler.class); public void sessionCreated(IoSession session) { if (session.getConfig() instanceof SocketSessionConfig) { ((SocketSessionConfig) session.getConfig()) .setReceiveBufferSize(2048); } session.setIdleTime(IdleStatus.BOTH_IDLE, 10); } public void sessionIdle(IoSession session, IdleStatus status) { log.info("*** IDLE #" + session.getIdleCount(IdleStatus.BOTH_IDLE) + " ***"); } public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); session.close(); } public void messageReceived(IoSession session, Object message) throws Exception { if (!(message instanceof ByteBuffer)) { return; } ByteBuffer rb = (ByteBuffer) message; // Write the received data back to remote peer ByteBuffer wb = ByteBuffer.allocate(rb.remaining()); wb.put(rb); wb.flip(); session.write(wb); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/0000755000175000017500000000000011002320017025143 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/0000755000175000017500000000000011044712500025740 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/SocketBindTest.java0000644000175000017500000000560611002320020031461 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import junit.framework.Assert; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.transport.AbstractBindTest; /** * Tests {@link SocketAcceptor} resource leakage. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SocketBindTest extends AbstractBindTest { public SocketBindTest() { super(new SocketAcceptor()); } protected SocketAddress createSocketAddress(int port) { return new InetSocketAddress(port); } protected int getPort(SocketAddress address) { return ((InetSocketAddress) address).getPort(); } public void testUnbindDisconnectsClients() throws Exception { // TODO: This test is almost identical to the test with the same name in VmPipeBindTest bind(false); SocketAddress addr = createSocketAddress(port); IoConnector connector = new SocketConnector(); IoSession[] sessions = new IoSession[5]; for (int i = 0; i < sessions.length; i++) { ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), new IoHandlerAdapter()); future.join(); sessions[i] = future.getSession(); Assert.assertTrue(sessions[i].isConnected()); } // Wait for the server side sessions to be created. Thread.sleep(500); Collection managedSessions = acceptor.getManagedSessions(addr); Assert.assertEquals(5, managedSessions.size()); acceptor.unbind(addr); // Wait for the client side sessions to close. Thread.sleep(500); for (int i = 0; i < sessions.length; i++) { Assert.assertFalse(sessions[i].isConnected()); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/DatagramConfigTest.java0000644000175000017500000000741111002320020032276 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.InetSocketAddress; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.util.AvailablePortFinder; /** * Tests if {@link DatagramAcceptor} session is configured properly. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DatagramConfigTest extends TestCase { private final IoAcceptor acceptor = new DatagramAcceptor(); private final IoConnector connector = new DatagramConnector(); private String result; public DatagramConfigTest() { } protected void setUp() throws Exception { result = ""; } public void testAcceptorFilterChain() throws Exception { int port = AvailablePortFinder.getNextAvailable(1024); DatagramAcceptorConfig expectedConfig = new DatagramAcceptorConfig(); IoFilter mockFilter = new MockFilter(); IoHandler mockHandler = new MockHandler(); expectedConfig.getFilterChain().addLast("mock", mockFilter); acceptor.bind(new InetSocketAddress(port), mockHandler, expectedConfig); try { ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), new IoHandlerAdapter()); future.join(); WriteFuture writeFuture = future.getSession().write( ByteBuffer.allocate(16).putInt(0).flip()); writeFuture.join(); Assert.assertTrue(writeFuture.isWritten()); future.getSession().close(); for (int i = 0; i < 30; i++) { if (result.length() == 2) { break; } Thread.sleep(100); } Assert.assertEquals("FH", result); } finally { acceptor.unbind(new InetSocketAddress(port)); } } private class MockFilter extends IoFilterAdapter { public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { result += "F"; nextFilter.messageReceived(session, message); } } private class MockHandler extends IoHandlerAdapter { public void messageReceived(IoSession session, Object message) throws Exception { result += "H"; } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/DatagramBindTest.java0000644000175000017500000000305311002320020031743 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.InetSocketAddress; import java.net.SocketAddress; import org.apache.mina.transport.AbstractBindTest; /** * Tests {@link DatagramAcceptor} resource leakage. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DatagramBindTest extends AbstractBindTest { public DatagramBindTest() { super(new DatagramAcceptor()); } protected SocketAddress createSocketAddress(int port) { return new InetSocketAddress(port); } protected int getPort(SocketAddress address) { return ((InetSocketAddress) address).getPort(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/DatagramTrafficControlTest.javamina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/DatagramTrafficControlTest.j0000644000175000017500000000372411002320020033323 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.InetSocketAddress; import java.net.SocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandler; import org.apache.mina.transport.AbstractTrafficControlTest; /** * Tests suspending and resuming reads and writes for the * {@link org.apache.mina.common.TransportType#DATAGRAM} transport type. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Id: DatagramTrafficControlTest.java 555855 2007-07-13 03:19:00Z trustin $ */ public class DatagramTrafficControlTest extends AbstractTrafficControlTest { public DatagramTrafficControlTest() { super(new DatagramAcceptor()); } protected ConnectFuture connect(int port, IoHandler handler) throws Exception { IoConnector connector = new DatagramConnector(); SocketAddress addr = new InetSocketAddress("localhost", port); return connector.connect(addr, handler); } protected SocketAddress createServerSocketAddress(int port) { return new InetSocketAddress(port); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/DatagramConnectorTest.java0000644000175000017500000000310711002320020033021 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.transport.AbstractConnectorTest; /** * Tests {@link DatagramConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class DatagramConnectorTest extends AbstractConnectorTest { protected IoAcceptor createAcceptor() { return new DatagramAcceptor(); } protected IoConnector createConnector() { return new DatagramConnector(); } public void testConnectFutureFailureTiming() throws Exception { // Skip the test; Datagram connection can be made even if there's no // server at the endpoint. } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/SocketTrafficControlTest.javamina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/SocketTrafficControlTest.jav0000644000175000017500000000371011002320020033355 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.InetSocketAddress; import java.net.SocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandler; import org.apache.mina.transport.AbstractTrafficControlTest; /** * Tests suspending and resuming reads and writes for the * {@link org.apache.mina.common.TransportType#SOCKET} transport type. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Id: SocketTrafficControlTest.java 555855 2007-07-13 03:19:00Z trustin $ */ public class SocketTrafficControlTest extends AbstractTrafficControlTest { public SocketTrafficControlTest() { super(new SocketAcceptor()); } protected ConnectFuture connect(int port, IoHandler handler) throws Exception { IoConnector connector = new SocketConnector(); SocketAddress addr = new InetSocketAddress("localhost", port); return connector.connect(addr, handler); } protected SocketAddress createServerSocketAddress(int port) { return new InetSocketAddress(port); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/SocketConnectorTest.java0000644000175000017500000000260311002320020032531 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.transport.AbstractConnectorTest; /** * Tests {@link SocketConnector}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class SocketConnectorTest extends AbstractConnectorTest { protected IoAcceptor createAcceptor() { return new SocketAcceptor(); } protected IoConnector createConnector() { return new SocketConnector(); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/transport/socket/nio/DatagramRecyclerTest.java0000644000175000017500000001634711002320020032651 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.transport.socket.nio; import java.net.InetSocketAddress; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.ExpiringSessionRecycler; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.util.AvailablePortFinder; /** * Tests if datagram sessions are recycled properly. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 436993 $, $Date: 2006-08-26 07:36:56 +0900 (토, 26 8월 2006) $ */ public class DatagramRecyclerTest extends TestCase { private final IoAcceptor acceptor = new DatagramAcceptor(); private final IoConnector connector = new DatagramConnector(); public DatagramRecyclerTest() { } public void testDatagramRecycler() throws Exception { int port = AvailablePortFinder.getNextAvailable(1024); DatagramAcceptorConfig config = new DatagramAcceptorConfig(); ExpiringSessionRecycler recycler = new ExpiringSessionRecycler(1, 1); config.setSessionRecycler(recycler); MockHandler acceptorHandler = new MockHandler(); MockHandler connectorHandler = new MockHandler(); acceptor.bind(new InetSocketAddress(port), acceptorHandler, config); try { ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), connectorHandler, config); future.join(); // Write whatever to trigger the acceptor. future.getSession().write(ByteBuffer.allocate(1)).join(); // Wait until the connection is closed. future.getSession().getCloseFuture().join(3000); Assert.assertTrue(future.getSession().getCloseFuture().isClosed()); acceptorHandler.session.getCloseFuture().join(3000); Assert.assertTrue(acceptorHandler.session.getCloseFuture() .isClosed()); Thread.sleep(1000); Assert.assertEquals("CROPSECL", connectorHandler.result.toString()); Assert.assertEquals("CROPRECL", acceptorHandler.result.toString()); } finally { acceptor.unbind(new InetSocketAddress(port)); } } public void testCloseRequest() throws Exception { int port = AvailablePortFinder.getNextAvailable(1024); DatagramAcceptorConfig config = new DatagramAcceptorConfig(); ExpiringSessionRecycler recycler = new ExpiringSessionRecycler(10, 1); config.setSessionRecycler(recycler); MockHandler acceptorHandler = new MockHandler(); MockHandler connectorHandler = new MockHandler(); acceptor.bind(new InetSocketAddress(port), acceptorHandler, config); try { ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), connectorHandler, config); future.join(); // Write whatever to trigger the acceptor. future.getSession().write(ByteBuffer.allocate(1)).join(); // Make sure the connection is closed before recycler closes it. while (acceptorHandler.session == null) { Thread.yield(); } acceptorHandler.session.close(); Assert.assertTrue( acceptorHandler.session.getCloseFuture().join(3000)); IoSession oldSession = acceptorHandler.session; // Wait until all events are processed and clear the state. long startTime = System.currentTimeMillis(); while (acceptorHandler.result.length() < 8) { Thread.yield(); if (System.currentTimeMillis() - startTime > 5000) { throw new Exception(); } } acceptorHandler.result.setLength(0); acceptorHandler.session = null; // Write whatever to trigger the acceptor again. future.getSession().write(ByteBuffer.allocate(1)).join(); // Make sure the connection is closed before recycler closes it. while (acceptorHandler.session == null) { Thread.yield(); } acceptorHandler.session.close(); Assert.assertTrue( acceptorHandler.session.getCloseFuture().join(3000)); future.getSession().close().join(); Assert.assertNotSame(oldSession, acceptorHandler.session); } finally { acceptor.unbind(new InetSocketAddress(port)); } } private class MockHandler extends IoHandlerAdapter { public volatile IoSession session; public final StringBuffer result = new StringBuffer(); @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { this.session = session; result.append("CA"); } @Override public void messageReceived(IoSession session, Object message) throws Exception { this.session = session; result.append("RE"); } @Override public void messageSent(IoSession session, Object message) throws Exception { this.session = session; result.append("SE"); } @Override public void sessionClosed(IoSession session) throws Exception { this.session = session; result.append("CL"); } @Override public void sessionCreated(IoSession session) throws Exception { this.session = session; result.append("CR"); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { this.session = session; result.append("ID"); } @Override public void sessionOpened(IoSession session) throws Exception { this.session = session; result.append("OP"); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/0000755000175000017500000000000011044712500023117 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/IoFilterChainTest.java0000644000175000017500000003120311002320016027270 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.net.SocketAddress; import java.util.Iterator; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.IoFilterChain.Entry; import org.apache.mina.common.support.AbstractIoFilterChain; import org.apache.mina.common.support.BaseIoSession; /** * Tests {@link AbstractIoFilterChain}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoFilterChainTest extends TestCase { private IoFilterChainImpl chain; private IoSession session; private String result; public void setUp() { chain = new IoFilterChainImpl(); session = new TestSession(); result = ""; } public void tearDown() { } public void testAdd() throws Exception { chain.addFirst("A", new EventOrderTestFilter('A')); chain.addLast("B", new EventOrderTestFilter('A')); chain.addFirst("C", new EventOrderTestFilter('A')); chain.addLast("D", new EventOrderTestFilter('A')); chain.addBefore("B", "E", new EventOrderTestFilter('A')); chain.addBefore("C", "F", new EventOrderTestFilter('A')); chain.addAfter("B", "G", new EventOrderTestFilter('A')); chain.addAfter("D", "H", new EventOrderTestFilter('A')); String actual = ""; for (Iterator i = chain.getAll().iterator(); i.hasNext();) { Entry e = (Entry) i.next(); actual += e.getName(); } Assert.assertEquals("FCAEBGDH", actual); } public void testGet() throws Exception { IoFilter filterA = new IoFilterAdapter(); IoFilter filterB = new IoFilterAdapter(); IoFilter filterC = new IoFilterAdapter(); IoFilter filterD = new IoFilterAdapter(); chain.addFirst("A", filterA); chain.addLast("B", filterB); chain.addBefore("B", "C", filterC); chain.addAfter("A", "D", filterD); Assert.assertSame(filterA, chain.get("A")); Assert.assertSame(filterB, chain.get("B")); Assert.assertSame(filterC, chain.get("C")); Assert.assertSame(filterD, chain.get("D")); } public void testRemove() throws Exception { chain.addLast("A", new EventOrderTestFilter('A')); chain.addLast("B", new EventOrderTestFilter('A')); chain.addLast("C", new EventOrderTestFilter('A')); chain.addLast("D", new EventOrderTestFilter('A')); chain.addLast("E", new EventOrderTestFilter('A')); chain.remove("A"); chain.remove("E"); chain.remove("C"); chain.remove("B"); chain.remove("D"); Assert.assertEquals(0, chain.getAll().size()); } public void testClear() throws Exception { chain.addLast("A", new EventOrderTestFilter('A')); chain.addLast("B", new EventOrderTestFilter('A')); chain.addLast("C", new EventOrderTestFilter('A')); chain.addLast("D", new EventOrderTestFilter('A')); chain.addLast("E", new EventOrderTestFilter('A')); chain.clear(); Assert.assertEquals(0, chain.getAll().size()); } public void testToString() throws Exception { // When the chain is empty Assert.assertEquals("{ empty }", chain.toString()); // When there's one filter chain.addLast("A", new IoFilterAdapter() { public String toString() { return "B"; } }); Assert.assertEquals("{ (A:B) }", chain.toString()); // When there are two chain.addLast("C", new IoFilterAdapter() { public String toString() { return "D"; } }); Assert.assertEquals("{ (A:B), (C:D) }", chain.toString()); } public void testDefault() { run("HS0 HSO HMR HMS HSI HEC HSC"); } public void testChained() throws Exception { chain.addLast("A", new EventOrderTestFilter('A')); chain.addLast("B", new EventOrderTestFilter('B')); run("AS0 BS0 HS0" + "ASO BSO HSO" + "AMR BMR HMR" + "BFW AFW AMS BMS HMS" + "ASI BSI HSI" + "AEC BEC HEC" + "ASC BSC HSC"); } public void testAddRemove() throws Exception { IoFilter filter = new AddRemoveTestFilter(); chain.addFirst("A", filter); assertEquals("ADDED", result); chain.remove("A"); assertEquals("ADDEDREMOVED", result); } private void run(String expectedResult) { chain.fireSessionCreated(session); chain.fireSessionOpened(session); chain.fireMessageReceived(session, new Object()); chain.fireFilterWrite(session, new WriteRequest(new Object())); chain.fireSessionIdle(session, IdleStatus.READER_IDLE); chain.fireExceptionCaught(session, new Exception()); chain.fireSessionClosed(session); result = formatResult(result); expectedResult = formatResult(expectedResult); System.out.println("Expected: " + expectedResult); System.out.println("Actual: " + result); Assert.assertEquals(expectedResult, result); } private String formatResult(String result) { result = result.replaceAll("\\s", ""); StringBuffer buf = new StringBuffer(result.length() * 4 / 3); for (int i = 0; i < result.length(); i++) { buf.append(result.charAt(i)); if (i % 3 == 2) { buf.append(' '); } } return buf.toString(); } private class TestSession extends BaseIoSession implements IoSession { private IoHandler handler = new IoHandlerAdapter() { public void sessionCreated(IoSession session) { result += "HS0"; } public void sessionOpened(IoSession session) { result += "HSO"; } public void sessionClosed(IoSession session) { result += "HSC"; } public void sessionIdle(IoSession session, IdleStatus status) { result += "HSI"; } public void exceptionCaught(IoSession session, Throwable cause) { result += "HEC"; if (cause.getClass() != Exception.class) { cause.printStackTrace(System.out); } } public void messageReceived(IoSession session, Object message) { result += "HMR"; } public void messageSent(IoSession session, Object message) { result += "HMS"; } }; public IoHandler getHandler() { return handler; } public CloseFuture close() { return null; } public TransportType getTransportType() { return TransportType.VM_PIPE; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public IoFilterChain getFilterChain() { return new AbstractIoFilterChain(this) { protected void doWrite(IoSession session, WriteRequest writeRequest) { } protected void doClose(IoSession session) { } }; } public int getScheduledWriteRequests() { return 0; } protected void updateTrafficMask() { } public boolean isClosing() { return false; } public IoService getService() { return null; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } public IoServiceConfig getServiceConfig() { return null; } } private class EventOrderTestFilter extends IoFilterAdapter { private final char id; private EventOrderTestFilter(char id) { this.id = id; } public void sessionCreated(NextFilter nextFilter, IoSession session) { result += id + "S0"; nextFilter.sessionCreated(session); } public void sessionOpened(NextFilter nextFilter, IoSession session) { result += id + "SO"; nextFilter.sessionOpened(session); } public void sessionClosed(NextFilter nextFilter, IoSession session) { result += id + "SC"; nextFilter.sessionClosed(session); } public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) { result += id + "SI"; nextFilter.sessionIdle(session, status); } public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) { result += id + "EC"; nextFilter.exceptionCaught(session, cause); } public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) { result += id + "FW"; nextFilter.filterWrite(session, writeRequest); } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) { result += id + "MR"; nextFilter.messageReceived(session, message); } public void messageSent(NextFilter nextFilter, IoSession session, Object message) { result += id + "MS"; nextFilter.messageSent(session, message); } public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.filterClose(session); } } private class AddRemoveTestFilter extends IoFilterAdapter { public void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) { result += "ADDED"; } public void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) { result += "REMOVED"; } } private static class IoFilterChainImpl extends AbstractIoFilterChain { protected IoFilterChainImpl() { super(new BaseIoSession() { protected void updateTrafficMask() { } public IoService getService() { return null; } public IoHandler getHandler() { return null; } public IoFilterChain getFilterChain() { return null; } public TransportType getTransportType() { return null; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public int getScheduledWriteRequests() { return 0; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } public IoServiceConfig getServiceConfig() { return null; } }); } protected void doWrite(IoSession session, WriteRequest writeRequest) { fireMessageSent(session, writeRequest); } protected void doClose(IoSession session) { } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/ByteBufferTest.java0000644000175000017500000006255511002320016026663 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.nio.BufferOverflowException; import java.nio.ByteOrder; import java.nio.ReadOnlyBufferException; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.ArrayList; import java.util.Date; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; /** * Tests {@link ByteBuffer}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 595517 $, $Date: 2007-11-16 10:31:56 +0900 (Fri, 16 Nov 2007) $ */ public class ByteBufferTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(ByteBufferTest.class); } @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testAllocate() throws Exception { for (int i = 10; i < 1048576 * 2; i = i * 11 / 10) // increase by 10% { ByteBuffer buf = ByteBuffer.allocate(i); Assert.assertEquals(0, buf.position()); Assert.assertEquals(buf.capacity(), buf.remaining()); Assert.assertTrue(buf.capacity() >= i); Assert.assertTrue(buf.capacity() < i * 2); } } public void testRelease() throws Exception { for (int i = 10; i < 1048576 * 2; i = i * 11 / 10) // increase by 10% { ByteBuffer buf = ByteBuffer.allocate(i); Assert.assertEquals(0, buf.position()); Assert.assertEquals(buf.capacity(), buf.remaining()); Assert.assertTrue(buf.capacity() >= i); Assert.assertTrue(buf.capacity() < i * 2); buf.release(); } } public void testLeakageDetection() throws Exception { ByteBuffer buf = ByteBuffer.allocate(1024); buf.release(); try { buf.release(); Assert.fail("Releasing a buffer twice should fail."); } catch (IllegalStateException e) { } } public void testAcquireRelease() throws Exception { ByteBuffer buf = ByteBuffer.allocate(1024); buf.acquire(); buf.release(); buf.acquire(); buf.acquire(); buf.release(); buf.release(); buf.release(); try { buf.release(); Assert.fail("Releasing a buffer twice should fail."); } catch (IllegalStateException e) { } } public void testAutoExpand() throws Exception { ByteBuffer buf = ByteBuffer.allocate(1); buf.put((byte) 0); try { buf.put((byte) 0); Assert.fail(); } catch (BufferOverflowException e) { // ignore } buf.setAutoExpand(true); buf.put((byte) 0); Assert.assertEquals(2, buf.position()); Assert.assertEquals(2, buf.limit()); Assert.assertEquals(2, buf.capacity()); buf.setAutoExpand(false); try { buf.put(3, (byte) 0); Assert.fail(); } catch (IndexOutOfBoundsException e) { // ignore } buf.setAutoExpand(true); buf.put(3, (byte) 0); Assert.assertEquals(2, buf.position()); Assert.assertEquals(4, buf.limit()); Assert.assertEquals(4, buf.capacity()); } public void testAutoExpandMark() throws Exception { ByteBuffer buf = ByteBuffer.allocate(4).setAutoExpand(true); buf.put((byte) 0); buf.put((byte) 0); buf.put((byte) 0); // Position should be 3 when we reset this buffer. buf.mark(); // Overflow it buf.put((byte) 0); buf.put((byte) 0); Assert.assertEquals(5, buf.position()); buf.reset(); Assert.assertEquals(3, buf.position()); } public void testPooledProperty() throws Exception { ByteBuffer buf = ByteBuffer.allocate(16); java.nio.ByteBuffer nioBuf = buf.buf(); buf.release(); buf = ByteBuffer.allocate(16); Assert.assertSame(nioBuf, buf.buf()); buf.setPooled(false); buf.release(); Assert.assertNotSame(nioBuf, ByteBuffer.allocate(16).buf()); } public void testGetString() throws Exception { ByteBuffer buf = ByteBuffer.allocate(16); CharsetDecoder decoder; Charset charset = Charset.forName("UTF-8"); buf.clear(); buf.putString("hello", charset.newEncoder()); buf.put((byte) 0); buf.flip(); Assert.assertEquals("hello", buf.getString(charset.newDecoder())); buf.clear(); buf.putString("hello", charset.newEncoder()); buf.flip(); Assert.assertEquals("hello", buf.getString(charset.newDecoder())); decoder = Charset.forName("ISO-8859-1").newDecoder(); buf.clear(); buf.put((byte) 'A'); buf.put((byte) 'B'); buf.put((byte) 'C'); buf.put((byte) 0); buf.position(0); Assert.assertEquals("ABC", buf.getString(decoder)); Assert.assertEquals(4, buf.position()); buf.position(0); buf.limit(1); Assert.assertEquals("A", buf.getString(decoder)); Assert.assertEquals(1, buf.position()); buf.clear(); Assert.assertEquals("ABC", buf.getString(10, decoder)); Assert.assertEquals(10, buf.position()); buf.clear(); Assert.assertEquals("A", buf.getString(1, decoder)); Assert.assertEquals(1, buf.position()); // Test a trailing garbage buf.clear(); buf.put((byte) 'A'); buf.put((byte) 'B'); buf.put((byte) 0); buf.put((byte) 'C'); buf.position(0); Assert.assertEquals("AB", buf.getString(4, decoder)); Assert.assertEquals(4, buf.position()); buf.clear(); buf.fillAndReset(buf.limit()); decoder = Charset.forName("UTF-16").newDecoder(); buf.put((byte) 0); buf.put((byte) 'A'); buf.put((byte) 0); buf.put((byte) 'B'); buf.put((byte) 0); buf.put((byte) 'C'); buf.put((byte) 0); buf.put((byte) 0); buf.position(0); Assert.assertEquals("ABC", buf.getString(decoder)); Assert.assertEquals(8, buf.position()); buf.position(0); buf.limit(2); Assert.assertEquals("A", buf.getString(decoder)); Assert.assertEquals(2, buf.position()); buf.position(0); buf.limit(3); Assert.assertEquals("A", buf.getString(decoder)); Assert.assertEquals(2, buf.position()); buf.clear(); Assert.assertEquals("ABC", buf.getString(10, decoder)); Assert.assertEquals(10, buf.position()); buf.clear(); Assert.assertEquals("A", buf.getString(2, decoder)); Assert.assertEquals(2, buf.position()); buf.clear(); try { buf.getString(1, decoder); Assert.fail(); } catch (IllegalArgumentException e) { // ignore } // Test getting strings from an empty buffer. buf.clear(); buf.limit(0); Assert.assertEquals("", buf.getString(decoder)); Assert.assertEquals("", buf.getString(2, decoder)); // Test getting strings from non-empty buffer which is filled with 0x00 buf.clear(); buf.putInt(0); buf.clear(); buf.limit(4); Assert.assertEquals("", buf.getString(decoder)); Assert.assertEquals(2, buf.position()); Assert.assertEquals(4, buf.limit()); buf.position(0); Assert.assertEquals("", buf.getString(2, decoder)); Assert.assertEquals(2, buf.position()); Assert.assertEquals(4, buf.limit()); } public void testGetStringWithFailure() throws Exception { String test = "\u30b3\u30e1\u30f3\u30c8\u7de8\u96c6"; ByteBuffer buffer = ByteBuffer.wrap(test.getBytes("Shift_JIS")); // Make sure the limit doesn't change when an exception arose. int oldLimit = buffer.limit(); int oldPos = buffer.position(); try { buffer.getString(3, Charset.forName("ASCII").newDecoder()); Assert.fail(); } catch (Exception e) { Assert.assertEquals(oldLimit, buffer.limit()); Assert.assertEquals(oldPos, buffer.position()); } try { buffer.getString(Charset.forName("ASCII").newDecoder()); Assert.fail(); } catch (Exception e) { Assert.assertEquals(oldLimit, buffer.limit()); Assert.assertEquals(oldPos, buffer.position()); } } public void testPutString() throws Exception { CharsetEncoder encoder; ByteBuffer buf = ByteBuffer.allocate(16); encoder = Charset.forName("ISO-8859-1").newEncoder(); buf.putString("ABC", encoder); Assert.assertEquals(3, buf.position()); buf.clear(); Assert.assertEquals('A', buf.get(0)); Assert.assertEquals('B', buf.get(1)); Assert.assertEquals('C', buf.get(2)); buf.putString("D", 5, encoder); Assert.assertEquals(5, buf.position()); buf.clear(); Assert.assertEquals('D', buf.get(0)); Assert.assertEquals(0, buf.get(1)); buf.putString("EFG", 2, encoder); Assert.assertEquals(2, buf.position()); buf.clear(); Assert.assertEquals('E', buf.get(0)); Assert.assertEquals('F', buf.get(1)); Assert.assertEquals('C', buf.get(2)); // C may not be overwritten // UTF-16: We specify byte order to omit BOM. encoder = Charset.forName("UTF-16BE").newEncoder(); buf.clear(); buf.putString("ABC", encoder); Assert.assertEquals(6, buf.position()); buf.clear(); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals('A', buf.get(1)); Assert.assertEquals(0, buf.get(2)); Assert.assertEquals('B', buf.get(3)); Assert.assertEquals(0, buf.get(4)); Assert.assertEquals('C', buf.get(5)); buf.putString("D", 10, encoder); Assert.assertEquals(10, buf.position()); buf.clear(); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals('D', buf.get(1)); Assert.assertEquals(0, buf.get(2)); Assert.assertEquals(0, buf.get(3)); buf.putString("EFG", 4, encoder); Assert.assertEquals(4, buf.position()); buf.clear(); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals('E', buf.get(1)); Assert.assertEquals(0, buf.get(2)); Assert.assertEquals('F', buf.get(3)); Assert.assertEquals(0, buf.get(4)); // C may not be overwritten Assert.assertEquals('C', buf.get(5)); // C may not be overwritten // Test putting an emptry string buf.putString("", encoder); Assert.assertEquals(0, buf.position()); buf.putString("", 4, encoder); Assert.assertEquals(4, buf.position()); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals(0, buf.get(1)); } public void testGetPrefixedString() throws Exception { ByteBuffer buf = ByteBuffer.allocate(16); CharsetEncoder encoder; CharsetDecoder decoder; encoder = Charset.forName("ISO-8859-1").newEncoder(); decoder = Charset.forName("ISO-8859-1").newDecoder(); buf.putShort((short) 3); buf.putString("ABCD", encoder); buf.clear(); Assert.assertEquals("ABC", buf.getPrefixedString(decoder)); } public void testPutPrefixedString() throws Exception { CharsetEncoder encoder; ByteBuffer buf = ByteBuffer.allocate(16); buf.fillAndReset(buf.remaining()); encoder = Charset.forName("ISO-8859-1").newEncoder(); // Without autoExpand buf.putPrefixedString("ABC", encoder); Assert.assertEquals(5, buf.position()); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals(3, buf.get(1)); Assert.assertEquals('A', buf.get(2)); Assert.assertEquals('B', buf.get(3)); Assert.assertEquals('C', buf.get(4)); buf.clear(); try { buf.putPrefixedString("123456789012345", encoder); Assert.fail(); } catch (BufferOverflowException e) { // OK } // With autoExpand buf.clear(); buf.setAutoExpand(true); buf.putPrefixedString("123456789012345", encoder); Assert.assertEquals(17, buf.position()); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals(15, buf.get(1)); Assert.assertEquals('1', buf.get(2)); Assert.assertEquals('2', buf.get(3)); Assert.assertEquals('3', buf.get(4)); Assert.assertEquals('4', buf.get(5)); Assert.assertEquals('5', buf.get(6)); Assert.assertEquals('6', buf.get(7)); Assert.assertEquals('7', buf.get(8)); Assert.assertEquals('8', buf.get(9)); Assert.assertEquals('9', buf.get(10)); Assert.assertEquals('0', buf.get(11)); Assert.assertEquals('1', buf.get(12)); Assert.assertEquals('2', buf.get(13)); Assert.assertEquals('3', buf.get(14)); Assert.assertEquals('4', buf.get(15)); Assert.assertEquals('5', buf.get(16)); } public void testPutPrefixedStringWithPrefixLength() throws Exception { CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder(); ByteBuffer buf = ByteBuffer.allocate(16).sweep().setAutoExpand(true); buf.putPrefixedString("A", 1, encoder); Assert.assertEquals(2, buf.position()); Assert.assertEquals(1, buf.get(0)); Assert.assertEquals('A', buf.get(1)); buf.sweep(); buf.putPrefixedString("A", 2, encoder); Assert.assertEquals(3, buf.position()); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals(1, buf.get(1)); Assert.assertEquals('A', buf.get(2)); buf.sweep(); buf.putPrefixedString("A", 4, encoder); Assert.assertEquals(5, buf.position()); Assert.assertEquals(0, buf.get(0)); Assert.assertEquals(0, buf.get(1)); Assert.assertEquals(0, buf.get(2)); Assert.assertEquals(1, buf.get(3)); Assert.assertEquals('A', buf.get(4)); } public void testPutPrefixedStringWithPadding() throws Exception { CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder(); ByteBuffer buf = ByteBuffer.allocate(16).sweep().setAutoExpand(true); buf.putPrefixedString("A", 1, 2, (byte) 32, encoder); Assert.assertEquals(3, buf.position()); Assert.assertEquals(2, buf.get(0)); Assert.assertEquals('A', buf.get(1)); Assert.assertEquals(' ', buf.get(2)); buf.sweep(); buf.putPrefixedString("A", 1, 4, (byte) 32, encoder); Assert.assertEquals(5, buf.position()); Assert.assertEquals(4, buf.get(0)); Assert.assertEquals('A', buf.get(1)); Assert.assertEquals(' ', buf.get(2)); Assert.assertEquals(' ', buf.get(3)); Assert.assertEquals(' ', buf.get(4)); } public void testWideUtf8Characters() throws Exception { Runnable r = new Runnable() { public void run() { ByteBuffer buffer = ByteBuffer.allocate(1); buffer.setAutoExpand(true); Charset charset = Charset.forName("UTF-8"); CharsetEncoder encoder = charset.newEncoder(); for (int i = 0; i < 5; i++) { try { buffer.putString("\u89d2", encoder); } catch (CharacterCodingException e) { fail(e.getMessage()); } } } }; Thread t = new Thread(r); t.setDaemon(true); t.start(); for (int i = 0; i < 50; i++) { Thread.sleep(100); if (!t.isAlive()) { break; } } if (t.isAlive()) { t.interrupt(); fail("Went into endless loop trying to encode character"); } } public void testObjectSerialization() throws Exception { ByteBuffer buf = ByteBuffer.allocate(16); buf.setAutoExpand(true); List o = new ArrayList(); o.add(new Date()); o.add(long.class); // Test writing an object. buf.putObject(o); // Test reading an object. buf.clear(); Object o2 = buf.getObject(); Assert.assertEquals(o, o2); // This assertion is just to make sure that deserialization occurred. Assert.assertNotSame(o, o2); } public void testSweepWithZeros() throws Exception { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(0xdeadbeef); buf.clear(); Assert.assertEquals(0xdeadbeef, buf.getInt()); Assert.assertEquals(4, buf.position()); Assert.assertEquals(4, buf.limit()); buf.sweep(); Assert.assertEquals(0, buf.position()); Assert.assertEquals(4, buf.limit()); Assert.assertEquals(0x0, buf.getInt()); } public void testSweepNonZeros() throws Exception { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(0xdeadbeef); buf.clear(); Assert.assertEquals(0xdeadbeef, buf.getInt()); Assert.assertEquals(4, buf.position()); Assert.assertEquals(4, buf.limit()); buf.sweep((byte) 0x45); Assert.assertEquals(0, buf.position()); Assert.assertEquals(4, buf.limit()); Assert.assertEquals(0x45454545, buf.getInt()); } public void testWrapNioBuffer() throws Exception { java.nio.ByteBuffer nioBuf = java.nio.ByteBuffer.allocate(10); nioBuf.position(3); nioBuf.limit(7); ByteBuffer buf = ByteBuffer.wrap(nioBuf); Assert.assertEquals(3, buf.position()); Assert.assertEquals(7, buf.limit()); Assert.assertEquals(10, buf.capacity()); } public void testWrapSubArray() throws Exception { byte[] array = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ByteBuffer buf = ByteBuffer.wrap(array, 3, 4); Assert.assertEquals(3, buf.position()); Assert.assertEquals(7, buf.limit()); Assert.assertEquals(10, buf.capacity()); buf.clear(); Assert.assertEquals(0, buf.position()); Assert.assertEquals(10, buf.limit()); Assert.assertEquals(10, buf.capacity()); } public void testPoolExpiration() throws Exception { PooledByteBufferAllocator allocator = (PooledByteBufferAllocator) ByteBuffer .getAllocator(); // Make a buffer pooled. ByteBuffer buf = ByteBuffer.allocate(16); buf.release(); // Let everything flushed. allocator.setTimeout(1); Thread.sleep(2000); // Make sure old buffers are flushed. Assert.assertNotSame(buf, ByteBuffer.allocate(16)); // Make sure new buffers are not flushed. allocator.setTimeout(10); buf = ByteBuffer.allocate(16); buf.release(); Thread.sleep(2000); Assert.assertSame(buf.buf(), ByteBuffer.allocate(16).buf()); // Return to the default settings allocator.setTimeout(60); } public void testAllocatorDisposal() throws Exception { PooledByteBufferAllocator allocator = (PooledByteBufferAllocator) ByteBuffer .getAllocator(); // dispose() should fail because the allocator is in use. try { allocator.dispose(); Assert.fail(); } catch (IllegalStateException e) { // OK } // Change the allocator. ByteBuffer.setAllocator(new PooledByteBufferAllocator()); // Dispose the old allocator. allocator.dispose(); // Allocation request to the disposed allocator should fail. try { allocator.allocate(16, true); Assert.fail(); } catch (IllegalStateException e) { // OK } } public void testDuplicate() throws Exception { java.nio.ByteBuffer nioBuf; ByteBuffer original; ByteBuffer duplicate; // Test if the buffer is duplicated correctly. original = ByteBuffer.allocate(16).sweep(); nioBuf = original.buf(); original.position(4); original.limit(10); duplicate = original.duplicate(); original.put(4, (byte) 127); Assert.assertEquals(4, duplicate.position()); Assert.assertEquals(10, duplicate.limit()); Assert.assertEquals(16, duplicate.capacity()); Assert.assertNotSame(original.buf(), duplicate.buf()); Assert.assertEquals(127, duplicate.get(4)); original.release(); duplicate.release(); //// Check if pooled correctly. original = ByteBuffer.allocate(16); Assert.assertSame(nioBuf, original.buf()); original.release(); // Try to release duplicate first. original = ByteBuffer.allocate(16); duplicate = original.duplicate(); duplicate.release(); original.release(); //// Check if pooled correctly. original = ByteBuffer.allocate(16); Assert.assertSame(nioBuf, original.buf()); original.release(); // Test a duplicate of a duplicate. original = ByteBuffer.allocate(16); duplicate = original.duplicate(); ByteBuffer anotherDuplicate = duplicate.duplicate(); anotherDuplicate.release(); original.release(); duplicate.release(); try { duplicate.release(); Assert.fail(); } catch (IllegalStateException e) { // OK } try { anotherDuplicate.release(); Assert.fail(); } catch (IllegalStateException e) { // OK } //// Check if pooled correctly. original = ByteBuffer.allocate(16); Assert.assertSame(nioBuf, original.buf()); original.release(); // Try to expand. try { original = ByteBuffer.allocate(16); duplicate = original.duplicate(); duplicate.setAutoExpand(true); duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder()); Assert.fail(); } catch (IllegalStateException e) { // OK } } public void testSlice() throws Exception { ByteBuffer original; ByteBuffer slice; // Test if the buffer is sliced correctly. original = ByteBuffer.allocate(16).sweep(); original.position(4); original.limit(10); slice = original.slice(); original.put(4, (byte) 127); Assert.assertEquals(0, slice.position()); Assert.assertEquals(6, slice.limit()); Assert.assertEquals(6, slice.capacity()); Assert.assertNotSame(original.buf(), slice.buf()); Assert.assertEquals(127, slice.get(0)); original.release(); slice.release(); } public void testReadOnlyBuffer() throws Exception { ByteBuffer original; ByteBuffer duplicate; // Test if the buffer is duplicated correctly. original = ByteBuffer.allocate(16).sweep(); original.position(4); original.limit(10); duplicate = original.asReadOnlyBuffer(); original.put(4, (byte) 127); Assert.assertEquals(4, duplicate.position()); Assert.assertEquals(10, duplicate.limit()); Assert.assertEquals(16, duplicate.capacity()); Assert.assertNotSame(original.buf(), duplicate.buf()); Assert.assertEquals(127, duplicate.get(4)); original.release(); duplicate.release(); // Try to expand. try { original = ByteBuffer.allocate(16); duplicate = original.asReadOnlyBuffer(); duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder()); Assert.fail(); } catch (ReadOnlyBufferException e) { // OK } } public void testGetUnsigned() throws Exception { ByteBuffer buf = ByteBuffer.allocate(16); buf.put((byte) 0xA4); buf.put((byte) 0xD0); buf.put((byte) 0xB3); buf.put((byte) 0xCD); buf.flip(); buf.order(ByteOrder.LITTLE_ENDIAN); buf.mark(); Assert.assertEquals(0xA4, buf.getUnsigned()); buf.reset(); Assert.assertEquals(0xD0A4, buf.getUnsignedShort()); buf.reset(); Assert.assertEquals(0xCDB3D0A4L, buf.getUnsignedInt()); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/TransportTypeTest.java0000644000175000017500000000422611002320016027453 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import junit.framework.Assert; import junit.framework.TestCase; /** * Tests {@link TransportType}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class TransportTypeTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(TransportTypeTest.class); } public void testRegistration() { TransportType myType = new TransportType( new String[] { "a", "b", "c" }, true); Assert.assertSame(myType, TransportType.getInstance("a")); Assert.assertSame(myType, TransportType.getInstance("A")); Assert.assertSame(myType, TransportType.getInstance("b")); Assert.assertSame(myType, TransportType.getInstance("B")); Assert.assertSame(myType, TransportType.getInstance("c")); Assert.assertSame(myType, TransportType.getInstance("C")); try { TransportType.getInstance("unknown"); Assert.fail(); } catch (IllegalArgumentException e) { // ignore } try { new TransportType(new String[] { "A" }, false); Assert.fail(); } catch (IllegalArgumentException e) { // ignore } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/support/0000755000175000017500000000000011044712500024633 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/support/FutureTest.java0000644000175000017500000002054111002320016027601 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.io.IOException; import java.net.SocketAddress; import junit.framework.TestCase; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoFuture; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; /** * Tests {@link IoFuture} implementations. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class FutureTest extends TestCase { public void testCloseFuture() throws Exception { DefaultCloseFuture future = new DefaultCloseFuture(null); assertFalse(future.isReady()); assertFalse(future.isClosed()); TestThread thread = new TestThread(future); thread.start(); future.setClosed(); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isClosed()); } public void testConnectFuture() throws Exception { DefaultConnectFuture future = new DefaultConnectFuture(); assertFalse(future.isReady()); assertFalse(future.isConnected()); assertNull(future.getSession()); TestThread thread = new TestThread(future); thread.start(); IoSession session = new BaseIoSession() { public IoHandler getHandler() { return null; } public IoFilterChain getFilterChain() { return null; } public TransportType getTransportType() { return null; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public int getScheduledWriteRequests() { return 0; } @Override protected void updateTrafficMask() { } @Override public boolean isClosing() { return false; } public IoService getService() { return null; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } public IoServiceConfig getServiceConfig() { return null; } }; future.setSession(session); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isConnected()); assertEquals(session, future.getSession()); future = new DefaultConnectFuture(); thread = new TestThread(future); thread.start(); future.setException(new IOException()); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertFalse(future.isConnected()); try { future.getSession(); fail("IOException should be thrown."); } catch (Exception e) { } } public void testWriteFuture() throws Exception { DefaultWriteFuture future = new DefaultWriteFuture(null); assertFalse(future.isReady()); assertFalse(future.isWritten()); TestThread thread = new TestThread(future); thread.start(); future.setWritten(true); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isWritten()); future = new DefaultWriteFuture(null); thread = new TestThread(future); thread.start(); future.setWritten(false); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertFalse(future.isWritten()); } public void testAddListener() throws Exception { DefaultCloseFuture future = new DefaultCloseFuture(null); assertFalse(future.isReady()); assertFalse(future.isClosed()); TestListener listener1 = new TestListener(); TestListener listener2 = new TestListener(); future.addListener(listener1); future.addListener(listener2); TestThread thread = new TestThread(future); thread.start(); future.setClosed(); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isClosed()); assertSame(future, listener1.notifiedFuture); assertSame(future, listener2.notifiedFuture); } public void testLateAddListener() throws Exception { DefaultCloseFuture future = new DefaultCloseFuture(null); assertFalse(future.isReady()); assertFalse(future.isClosed()); TestThread thread = new TestThread(future); thread.start(); future.setClosed(); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isClosed()); TestListener listener = new TestListener(); future.addListener(listener); assertSame(future, listener.notifiedFuture); } public void testRemoveListener1() throws Exception { DefaultCloseFuture future = new DefaultCloseFuture(null); assertFalse(future.isReady()); assertFalse(future.isClosed()); TestListener listener1 = new TestListener(); TestListener listener2 = new TestListener(); future.addListener(listener1); future.addListener(listener2); future.removeListener(listener1); TestThread thread = new TestThread(future); thread.start(); future.setClosed(); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isClosed()); assertSame(null, listener1.notifiedFuture); assertSame(future, listener2.notifiedFuture); } public void testRemoveListener2() throws Exception { DefaultCloseFuture future = new DefaultCloseFuture(null); assertFalse(future.isReady()); assertFalse(future.isClosed()); TestListener listener1 = new TestListener(); TestListener listener2 = new TestListener(); future.addListener(listener1); future.addListener(listener2); future.removeListener(listener2); TestThread thread = new TestThread(future); thread.start(); future.setClosed(); thread.join(); assertTrue(thread.success); assertTrue(future.isReady()); assertTrue(future.isClosed()); assertSame(future, listener1.notifiedFuture); assertSame(null, listener2.notifiedFuture); } private static class TestThread extends Thread { private final IoFuture future; private boolean success; TestThread(IoFuture future) { this.future = future; } @Override public void run() { success = future.join(10000); } } private static class TestListener implements IoFutureListener { private IoFuture notifiedFuture; public void operationComplete(IoFuture future) { this.notifiedFuture = future; } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/support/IoServiceListenerSupportTest.java0000644000175000017500000002663211002320016033331 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common.support; import java.net.InetSocketAddress; import java.net.SocketAddress; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoServiceListener; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.easymock.MockControl; /** * Tests {@link IoServiceListenerSupport}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoServiceListenerSupportTest extends TestCase { private static final SocketAddress ADDRESS = new InetSocketAddress(8080); public void testServiceLifecycle() throws Exception { IoServiceListenerSupport support = new IoServiceListenerSupport(); MockControl listenerControl = MockControl .createStrictControl(IoServiceListener.class); IoServiceListener listener = (IoServiceListener) listenerControl .getMock(); // Test activation listener.serviceActivated(null, ADDRESS, null, null); listenerControl.replay(); support.add(listener); support.fireServiceActivated(null, ADDRESS, null, null); listenerControl.verify(); Assert.assertEquals(1, support.getManagedServiceAddresses().size()); Assert.assertTrue(support.getManagedServiceAddresses() .contains(ADDRESS)); // Test deactivation & other side effects listenerControl.reset(); listener.serviceDeactivated(null, ADDRESS, null, null); listenerControl.replay(); //// Activate more than once support.fireServiceActivated(null, ADDRESS, null, null); //// Deactivate support.fireServiceDeactivated(null, ADDRESS, null, null); //// Deactivate more than once support.fireServiceDeactivated(null, ADDRESS, null, null); listenerControl.verify(); Assert.assertEquals(0, support.getManagedServiceAddresses().size()); Assert.assertFalse(support.getManagedServiceAddresses().contains( ADDRESS)); } public void testSessionLifecycle() throws Exception { IoServiceListenerSupport support = new IoServiceListenerSupport(); TestSession session = new TestSession(ADDRESS); MockControl chainControl = MockControl .createStrictControl(IoFilterChain.class); IoFilterChain chain = (IoFilterChain) chainControl.getMock(); session.setFilterChain(chain); MockControl listenerControl = MockControl .createStrictControl(IoServiceListener.class); IoServiceListener listener = (IoServiceListener) listenerControl .getMock(); // Test creation listener.sessionCreated(session); chain.fireSessionCreated(session); chain.fireSessionOpened(session); listenerControl.replay(); chainControl.replay(); support.add(listener); support.fireSessionCreated(session); listenerControl.verify(); chainControl.verify(); Assert.assertEquals(1, support.getManagedSessions(ADDRESS).size()); Assert .assertTrue(support.getManagedSessions(ADDRESS).contains( session)); // Test destruction & other side effects listenerControl.reset(); chainControl.reset(); chain.fireSessionClosed(session); listener.sessionDestroyed(session); listenerControl.replay(); //// Activate more than once support.fireSessionCreated(session); //// Deactivate support.fireSessionDestroyed(session); //// Deactivate more than once support.fireSessionDestroyed(session); listenerControl.verify(); Assert.assertFalse(session.isClosing()); Assert.assertEquals(0, support.getManagedSessions(ADDRESS).size()); Assert.assertFalse(support.getManagedSessions(ADDRESS) .contains(session)); } public void testDisconnectOnUnbind() throws Exception { final IoServiceListenerSupport support = new IoServiceListenerSupport(); MockControl acceptorControl = MockControl .createStrictControl(IoAcceptor.class); IoAcceptor acceptor = (IoAcceptor) acceptorControl.getMock(); final TestSession session = new TestSession(acceptor, ADDRESS); MockControl configControl = MockControl .createStrictControl(IoAcceptorConfig.class); IoAcceptorConfig config = (IoAcceptorConfig) configControl.getMock(); MockControl chainControl = MockControl .createStrictControl(IoFilterChain.class); IoFilterChain chain = (IoFilterChain) chainControl.getMock(); session.setFilterChain(chain); MockControl listenerControl = MockControl .createStrictControl(IoServiceListener.class); IoServiceListener listener = (IoServiceListener) listenerControl .getMock(); // Activate a service and create a session. listener.serviceActivated(acceptor, ADDRESS, null, config); listener.sessionCreated(session); chain.fireSessionCreated(session); chain.fireSessionOpened(session); listenerControl.replay(); chainControl.replay(); support.add(listener); support.fireServiceActivated(acceptor, ADDRESS, null, config); support.fireSessionCreated(session); listenerControl.verify(); chainControl.verify(); // Deactivate a service and make sure the session is closed & destroyed. listenerControl.reset(); chainControl.reset(); listener.serviceDeactivated(acceptor, ADDRESS, null, config); configControl.expectAndReturn(config.isDisconnectOnUnbind(), true); listener.sessionDestroyed(session); chain.fireSessionClosed(session); listenerControl.replay(); configControl.replay(); chainControl.replay(); new Thread() { // Emulate I/O service @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } support.fireSessionDestroyed(session); } }.start(); support.fireServiceDeactivated(acceptor, ADDRESS, null, config); Thread.sleep(1000); listenerControl.verify(); configControl.verify(); chainControl.verify(); Assert.assertTrue(session.isClosing()); Assert.assertEquals(0, support.getManagedSessions(ADDRESS).size()); Assert.assertFalse(support.getManagedSessions(ADDRESS) .contains(session)); } public void testConnectorActivation() throws Exception { IoServiceListenerSupport support = new IoServiceListenerSupport(); MockControl connectorControl = MockControl .createStrictControl(IoConnector.class); IoConnector connector = (IoConnector) connectorControl.getMock(); final TestSession session = new TestSession(connector, ADDRESS); MockControl chainControl = MockControl .createStrictControl(IoFilterChain.class); IoFilterChain chain = (IoFilterChain) chainControl.getMock(); session.setFilterChain(chain); MockControl listenerControl = MockControl .createStrictControl(IoServiceListener.class); IoServiceListener listener = (IoServiceListener) listenerControl .getMock(); // Creating a session should activate a service automatically. listener.serviceActivated(connector, ADDRESS, null, null); listener.sessionCreated(session); chain.fireSessionCreated(session); chain.fireSessionOpened(session); listenerControl.replay(); chainControl.replay(); support.add(listener); support.fireSessionCreated(session); listenerControl.verify(); chainControl.verify(); // Destroying a session should deactivate a service automatically. listenerControl.reset(); chainControl.reset(); listener.sessionDestroyed(session); chain.fireSessionClosed(session); listener.serviceDeactivated(connector, ADDRESS, null, null); listenerControl.replay(); chainControl.replay(); support.fireSessionDestroyed(session); listenerControl.verify(); chainControl.verify(); Assert.assertEquals(0, support.getManagedSessions(ADDRESS).size()); Assert.assertFalse(support.getManagedSessions(ADDRESS) .contains(session)); } private static class TestSession extends BaseIoSession { private final IoService service; private final SocketAddress serviceAddress; private IoFilterChain filterChain; TestSession(SocketAddress serviceAddress) { this(null, serviceAddress); } TestSession(IoService service, SocketAddress serviceAddress) { this.service = service; this.serviceAddress = serviceAddress; } @Override protected void updateTrafficMask() { } public IoSessionConfig getConfig() { return null; } public IoFilterChain getFilterChain() { return filterChain; } public void setFilterChain(IoFilterChain filterChain) { this.filterChain = filterChain; } public IoHandler getHandler() { return null; } public SocketAddress getLocalAddress() { return null; } public SocketAddress getRemoteAddress() { return null; } public int getScheduledWriteBytes() { return 0; } public int getScheduledWriteRequests() { return 0; } public IoService getService() { return service; } public SocketAddress getServiceAddress() { return serviceAddress; } public IoServiceConfig getServiceConfig() { return null; } public TransportType getTransportType() { return null; } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/common/DefaultIoFilterChainBuilderTest.java0000644000175000017500000001131211002320016032103 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.common; import java.util.Iterator; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.IoFilterChain.Entry; /** * Tests {@link DefaultIoFilterChainBuilder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class DefaultIoFilterChainBuilderTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(DefaultIoFilterChainBuilderTest.class); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } public void testAdd() throws Exception { DefaultIoFilterChainBuilder builder = new DefaultIoFilterChainBuilder(); builder.addFirst("A", new IoFilterAdapter()); builder.addLast("B", new IoFilterAdapter()); builder.addFirst("C", new IoFilterAdapter()); builder.addLast("D", new IoFilterAdapter()); builder.addBefore("B", "E", new IoFilterAdapter()); builder.addBefore("C", "F", new IoFilterAdapter()); builder.addAfter("B", "G", new IoFilterAdapter()); builder.addAfter("D", "H", new IoFilterAdapter()); String actual = ""; for (Iterator i = builder.getAll().iterator(); i.hasNext();) { Entry e = (Entry) i.next(); actual += e.getName(); } Assert.assertEquals("FCAEBGDH", actual); } public void testGet() throws Exception { DefaultIoFilterChainBuilder builder = new DefaultIoFilterChainBuilder(); IoFilter filterA = new IoFilterAdapter(); IoFilter filterB = new IoFilterAdapter(); IoFilter filterC = new IoFilterAdapter(); IoFilter filterD = new IoFilterAdapter(); builder.addFirst("A", filterA); builder.addLast("B", filterB); builder.addBefore("B", "C", filterC); builder.addAfter("A", "D", filterD); Assert.assertSame(filterA, builder.get("A")); Assert.assertSame(filterB, builder.get("B")); Assert.assertSame(filterC, builder.get("C")); Assert.assertSame(filterD, builder.get("D")); } public void testRemove() throws Exception { DefaultIoFilterChainBuilder builder = new DefaultIoFilterChainBuilder(); builder.addLast("A", new IoFilterAdapter()); builder.addLast("B", new IoFilterAdapter()); builder.addLast("C", new IoFilterAdapter()); builder.addLast("D", new IoFilterAdapter()); builder.addLast("E", new IoFilterAdapter()); builder.remove("A"); builder.remove("E"); builder.remove("C"); builder.remove("B"); builder.remove("D"); Assert.assertEquals(0, builder.getAll().size()); } public void testClear() throws Exception { DefaultIoFilterChainBuilder builder = new DefaultIoFilterChainBuilder(); builder.addLast("A", new IoFilterAdapter()); builder.addLast("B", new IoFilterAdapter()); builder.addLast("C", new IoFilterAdapter()); builder.addLast("D", new IoFilterAdapter()); builder.addLast("E", new IoFilterAdapter()); builder.clear(); Assert.assertEquals(0, builder.getAll().size()); } public void testToString() { DefaultIoFilterChainBuilder builder = new DefaultIoFilterChainBuilder(); // When the chain is empty Assert.assertEquals("{ empty }", builder.toString()); // When there's one filter builder.addLast("A", new IoFilterAdapter() { public String toString() { return "B"; } }); Assert.assertEquals("{ (A:B) }", builder.toString()); // When there are two builder.addLast("C", new IoFilterAdapter() { public String toString() { return "D"; } }); Assert.assertEquals("{ (A:B), (C:D) }", builder.toString()); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/handler/0000755000175000017500000000000011002320020023226 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/handler/chain/0000755000175000017500000000000011044712500024326 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/handler/chain/ChainedIoHandlerTest.java0000644000175000017500000000724611002320020031145 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.chain; import java.net.SocketAddress; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoService; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.support.BaseIoSession; /** * A test case for {@link ChainedIoHandler}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ChainedIoHandlerTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(ChainedIoHandlerTest.class); } public void testChainedCommand() throws Exception { IoHandlerChain chain = new IoHandlerChain(); StringBuffer buf = new StringBuffer(); chain.addLast("A", new TestCommand(buf, 'A')); chain.addLast("B", new TestCommand(buf, 'B')); chain.addLast("C", new TestCommand(buf, 'C')); new ChainedIoHandler(chain).messageReceived(new BaseIoSession() { protected void updateTrafficMask() { } public IoService getService() { return null; } public IoServiceConfig getServiceConfig() { return null; } public IoHandler getHandler() { return null; } public IoFilterChain getFilterChain() { return null; } public TransportType getTransportType() { return null; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public int getScheduledWriteRequests() { return 0; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } }, null); Assert.assertEquals("ABC", buf.toString()); } private class TestCommand implements IoHandlerCommand { private final StringBuffer buf; private final char ch; private TestCommand(StringBuffer buf, char ch) { this.buf = buf; this.ch = ch; } public void execute(NextCommand next, IoSession session, Object message) throws Exception { buf.append(ch); next.execute(session, message); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/handler/demux/0000755000175000017500000000000011044712500024366 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/handler/demux/DemuxingIoHandlerTest.java0000644000175000017500000001671411002320020031432 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.handler.demux; import junit.framework.TestCase; import org.apache.mina.common.IoSession; import org.apache.mina.handler.demux.DemuxingIoHandler; import org.apache.mina.handler.demux.MessageHandler; import org.easymock.MockControl; /** * Tests {@link org.apache.mina.handler.demux.DemuxingIoHandler}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class DemuxingIoHandlerTest extends TestCase { MockControl mockHandler1; MockControl mockHandler2; MockControl mockHandler3; MessageHandler handler1; MessageHandler handler2; MessageHandler handler3; IoSession session; Object[] msg; @SuppressWarnings("unchecked") protected void setUp() throws Exception { super.setUp(); /* * Create the messages. */ msg = new Object[9]; msg[0] = new C1(); msg[1] = new C2(); msg[2] = new C3(); msg[3] = new C1(); msg[4] = new C2(); msg[5] = new C3(); msg[6] = new C1(); msg[7] = new C2(); msg[8] = new C3(); /* * Create mocks. */ mockHandler1 = MockControl.createControl(MessageHandler.class); mockHandler2 = MockControl.createControl(MessageHandler.class); mockHandler3 = MockControl.createControl(MessageHandler.class); handler1 = (MessageHandler) mockHandler1.getMock(); handler2 = (MessageHandler) mockHandler2.getMock(); handler3 = (MessageHandler) mockHandler3.getMock(); session = (IoSession) MockControl.createControl(IoSession.class) .getMock(); } @SuppressWarnings("unchecked") public void testFindHandlerByClass() throws Exception { /* * Record expectations. */ handler1.messageReceived(session, msg[0]); handler1.messageReceived(session, msg[1]); handler1.messageReceived(session, msg[2]); handler1.messageReceived(session, msg[3]); handler2.messageReceived(session, msg[4]); handler2.messageReceived(session, msg[5]); handler1.messageReceived(session, msg[6]); handler2.messageReceived(session, msg[7]); handler3.messageReceived(session, msg[8]); /* * Replay. */ mockHandler1.replay(); mockHandler2.replay(); mockHandler3.replay(); DemuxingIoHandler ioHandler = new DemuxingIoHandler(); /* * First round. All messages should be handled by handler1 */ ioHandler.addMessageHandler(C1.class, (MessageHandler) mockHandler1 .getMock()); ioHandler.messageReceived(session, msg[0]); ioHandler.messageReceived(session, msg[1]); ioHandler.messageReceived(session, msg[2]); /* * Second round. C1 messages should be handled by handler1. C2 and C3 * messages should be handled by handler2. */ ioHandler.addMessageHandler(C2.class, (MessageHandler) mockHandler2 .getMock()); ioHandler.messageReceived(session, msg[3]); ioHandler.messageReceived(session, msg[4]); ioHandler.messageReceived(session, msg[5]); /* * Third round. C1 messages should be handled by handler1, C2 by * handler2 and C3 by handler3. */ ioHandler.addMessageHandler(C3.class, (MessageHandler) mockHandler3 .getMock()); ioHandler.messageReceived(session, msg[6]); ioHandler.messageReceived(session, msg[7]); ioHandler.messageReceived(session, msg[8]); /* * Verify. */ mockHandler1.verify(); mockHandler2.verify(); mockHandler3.verify(); } @SuppressWarnings("unchecked") public void testFindHandlerByInterface() throws Exception { /* * Record expectations. */ handler1.messageReceived(session, msg[0]); handler1.messageReceived(session, msg[1]); handler1.messageReceived(session, msg[2]); handler1.messageReceived(session, msg[3]); handler2.messageReceived(session, msg[4]); handler1.messageReceived(session, msg[5]); handler3.messageReceived(session, msg[6]); handler2.messageReceived(session, msg[7]); handler3.messageReceived(session, msg[8]); /* * Replay. */ mockHandler1.replay(); mockHandler2.replay(); mockHandler3.replay(); DemuxingIoHandler ioHandler = new DemuxingIoHandler(); /* * First round. All messages should be handled by handler1 */ ioHandler.addMessageHandler(I4.class, (MessageHandler) mockHandler1 .getMock()); ioHandler.messageReceived(session, msg[0]); ioHandler.messageReceived(session, msg[1]); ioHandler.messageReceived(session, msg[2]); /* * Second round. C1 and C3 messages should be handled by handler1. C2 * messages should be handled by handler2. */ ioHandler.addMessageHandler(I6.class, (MessageHandler) mockHandler2 .getMock()); ioHandler.messageReceived(session, msg[3]); ioHandler.messageReceived(session, msg[4]); ioHandler.messageReceived(session, msg[5]); /* * Third round. C1 and C3 messages should be handled by handler3. C2 * messages should be handled by handler2. */ ioHandler.addMessageHandler(I3.class, (MessageHandler) mockHandler3 .getMock()); ioHandler.messageReceived(session, msg[6]); ioHandler.messageReceived(session, msg[7]); ioHandler.messageReceived(session, msg[8]); /* * Verify. */ mockHandler1.verify(); mockHandler2.verify(); mockHandler3.verify(); } /* * Define some interfaces and classes used when testing the findHandler * method. This is what the hierarchy looks like: * * C3 - I7 - I9 * | | /\ * | I8 I3 I4 * | * C2 - I5 - I6 * | * C1 - I1 - I2 - I4 * | * I3 */ public interface I1 { } public interface I2 extends I3 { } public interface I3 { } public interface I4 { } public static class C1 implements I1, I2, I4 { } public interface I5 { } public interface I6 { } public static class C2 extends C1 implements I5, I6 { } public interface I7 extends I8 { } public interface I8 { } public interface I9 extends I3, I4 { } public static class C3 extends C2 implements I7, I9 { } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/0000755000175000017500000000000011044712500023114 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/StreamWriteFilterTest.java0000644000175000017500000004535311002320016030234 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.MessageDigest; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.concurrent.CountDownLatch; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.support.DefaultWriteFuture; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.apache.mina.transport.socket.nio.SocketConnector; import org.apache.mina.util.AvailablePortFinder; import org.easymock.AbstractMatcher; import org.easymock.MockControl; import junit.framework.TestCase; /** * Tests {@link StreamWriteFilter}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class StreamWriteFilterTest extends TestCase { MockControl mockSession; MockControl mockNextFilter; IoSession session; NextFilter nextFilter; @Override protected void setUp() throws Exception { super.setUp(); /* * Create the mocks. */ mockSession = MockControl.createControl(IoSession.class); mockNextFilter = MockControl.createControl(NextFilter.class); session = (IoSession) mockSession.getMock(); nextFilter = (NextFilter) mockNextFilter.getMock(); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(null); } public void testWriteEmptyStream() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); InputStream stream = new ByteArrayInputStream(new byte[0]); WriteRequest writeRequest = new WriteRequest(stream, new DummyWriteFuture()); /* * Record expectations */ nextFilter.messageSent(session, stream); /* * Replay. */ mockNextFilter.replay(); mockSession.replay(); filter.filterWrite(nextFilter, session, writeRequest); /* * Verify. */ mockNextFilter.verify(); mockSession.verify(); assertTrue(writeRequest.getFuture().isWritten()); } /** * Tests that the filter just passes objects which aren't InputStreams * through to the next filter. */ public void testWriteNonStreamMessage() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); Object message = new Object(); WriteRequest writeRequest = new WriteRequest(message, new DummyWriteFuture()); /* * Record expectations */ nextFilter.filterWrite(session, writeRequest); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(null); nextFilter.messageSent(session, message); /* * Replay. */ mockNextFilter.replay(); mockSession.replay(); filter.filterWrite(nextFilter, session, writeRequest); filter.messageSent(nextFilter, session, message); /* * Verify. */ mockNextFilter.verify(); mockSession.verify(); } /** * Tests when the contents of the stream fits into one write buffer. */ public void testWriteSingleBufferStream() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); byte[] data = new byte[] { 1, 2, 3, 4 }; InputStream stream = new ByteArrayInputStream(data); WriteRequest writeRequest = new WriteRequest(stream, new DummyWriteFuture()); /* * Record expectations */ session.setAttribute(StreamWriteFilter.CURRENT_STREAM, stream); mockSession.setReturnValue(null); session.setAttribute(StreamWriteFilter.INITIAL_WRITE_FUTURE, writeRequest.getFuture()); mockSession.setReturnValue(null); nextFilter .filterWrite(session, new WriteRequest(ByteBuffer.wrap(data))); mockNextFilter.setMatcher(new WriteRequestMatcher()); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.removeAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.removeAttribute(StreamWriteFilter.INITIAL_WRITE_FUTURE); mockSession.setReturnValue(writeRequest.getFuture()); session.removeAttribute(StreamWriteFilter.WRITE_REQUEST_QUEUE); mockSession.setReturnValue(null); nextFilter.messageSent(session, stream); /* * Replay. */ mockNextFilter.replay(); mockSession.replay(); filter.filterWrite(nextFilter, session, writeRequest); filter.messageSent(nextFilter, session, data); /* * Verify. */ mockNextFilter.verify(); mockSession.verify(); assertTrue(writeRequest.getFuture().isWritten()); } /** * Tests when the contents of the stream doesn't fit into one write buffer. */ public void testWriteSeveralBuffersStream() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); filter.setWriteBufferSize(4); byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; byte[] chunk1 = new byte[] { 1, 2, 3, 4 }; byte[] chunk2 = new byte[] { 5, 6, 7, 8 }; byte[] chunk3 = new byte[] { 9, 10 }; InputStream stream = new ByteArrayInputStream(data); WriteRequest writeRequest = new WriteRequest(stream, new DummyWriteFuture()); /* * Record expectations */ session.setAttribute(StreamWriteFilter.CURRENT_STREAM, stream); mockSession.setReturnValue(null); session.setAttribute(StreamWriteFilter.INITIAL_WRITE_FUTURE, writeRequest.getFuture()); mockSession.setReturnValue(null); nextFilter.filterWrite(session, new WriteRequest(ByteBuffer .wrap(chunk1))); mockNextFilter.setMatcher(new WriteRequestMatcher()); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); nextFilter.filterWrite(session, new WriteRequest(ByteBuffer .wrap(chunk2))); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); nextFilter.filterWrite(session, new WriteRequest(ByteBuffer .wrap(chunk3))); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.removeAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.removeAttribute(StreamWriteFilter.INITIAL_WRITE_FUTURE); mockSession.setReturnValue(writeRequest.getFuture()); session.removeAttribute(StreamWriteFilter.WRITE_REQUEST_QUEUE); mockSession.setReturnValue(null); nextFilter.messageSent(session, stream); /* * Replay. */ mockNextFilter.replay(); mockSession.replay(); filter.filterWrite(nextFilter, session, writeRequest); filter.messageSent(nextFilter, session, chunk1); filter.messageSent(nextFilter, session, chunk2); filter.messageSent(nextFilter, session, chunk3); /* * Verify. */ mockNextFilter.verify(); mockSession.verify(); assertTrue(writeRequest.getFuture().isWritten()); } public void testWriteWhileWriteInProgress() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); Queue queue = new LinkedList(); InputStream stream = new ByteArrayInputStream(new byte[5]); /* * Record expectations */ mockSession.reset(); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.getAttribute(StreamWriteFilter.WRITE_REQUEST_QUEUE); mockSession.setReturnValue(queue); /* * Replay. */ mockNextFilter.replay(); mockSession.replay(); WriteRequest wr = new WriteRequest(new Object(), new DummyWriteFuture()); filter.filterWrite(nextFilter, session, wr); assertEquals(1, queue.size()); assertSame(wr, queue.poll()); /* * Verify. */ mockNextFilter.verify(); mockSession.verify(); } public void testWritesWriteRequestQueueWhenFinished() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); WriteRequest wrs[] = new WriteRequest[] { new WriteRequest(new Object(), new DummyWriteFuture()), new WriteRequest(new Object(), new DummyWriteFuture()), new WriteRequest(new Object(), new DummyWriteFuture()) }; Queue queue = new LinkedList(); queue.add(wrs[0]); queue.add(wrs[1]); queue.add(wrs[2]); InputStream stream = new ByteArrayInputStream(new byte[0]); /* * Record expectations */ mockSession.reset(); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.removeAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(stream); session.removeAttribute(StreamWriteFilter.INITIAL_WRITE_FUTURE); mockSession.setReturnValue(new DefaultWriteFuture(session)); session.removeAttribute(StreamWriteFilter.WRITE_REQUEST_QUEUE); mockSession.setReturnValue(queue); nextFilter.filterWrite(session, wrs[0]); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(null); nextFilter.filterWrite(session, wrs[1]); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(null); nextFilter.filterWrite(session, wrs[2]); session.getAttribute(StreamWriteFilter.CURRENT_STREAM); mockSession.setReturnValue(null); nextFilter.messageSent(session, stream); /* * Replay. */ mockNextFilter.replay(); mockSession.replay(); filter.messageSent(nextFilter, session, new Object()); assertEquals(0, queue.size()); /* * Verify. */ mockNextFilter.verify(); mockSession.verify(); } /** * Tests that {@link StreamWriteFilter#setWriteBufferSize(int)} checks the * specified size. */ public void testSetWriteBufferSize() throws Exception { StreamWriteFilter filter = new StreamWriteFilter(); try { filter.setWriteBufferSize(0); fail("0 writeBuferSize specified. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { filter.setWriteBufferSize(-100); fail("Negative writeBuferSize specified. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } filter.setWriteBufferSize(1); assertEquals(1, filter.getWriteBufferSize()); filter.setWriteBufferSize(1024); assertEquals(1024, filter.getWriteBufferSize()); } public void testWriteUsingSocketTransport() throws Exception { IoAcceptor acceptor = new SocketAcceptor(); ((SocketAcceptorConfig) acceptor.getDefaultConfig()) .setReuseAddress(true); SocketAddress address = new InetSocketAddress("localhost", AvailablePortFinder.getNextAvailable()); IoConnector connector = new SocketConnector(); FixedRandomInputStream stream = new FixedRandomInputStream( 4 * 1024 * 1024); SenderHandler sender = new SenderHandler(stream); ReceiverHandler receiver = new ReceiverHandler(stream.size); acceptor.bind(address, sender); connector.connect(address, receiver); sender.latch.await(); receiver.latch.await(); acceptor.unbind(address); assertEquals(stream.bytesRead, receiver.bytesRead); assertEquals(stream.size, receiver.bytesRead); byte[] expectedMd5 = stream.digest.digest(); byte[] actualMd5 = receiver.digest.digest(); assertEquals(expectedMd5.length, actualMd5.length); for (int i = 0; i < expectedMd5.length; i++) { assertEquals(expectedMd5[i], actualMd5[i]); } } private static class FixedRandomInputStream extends InputStream { long size; long bytesRead = 0; Random random = new Random(); MessageDigest digest; FixedRandomInputStream(long size) throws Exception { this.size = size; digest = MessageDigest.getInstance("MD5"); } @Override public int read() throws IOException { if (isAllWritten()) return -1; bytesRead++; byte b = (byte) random.nextInt(255); digest.update(b); return b; } public long getBytesRead() { return bytesRead; } public long getSize() { return size; } public boolean isAllWritten() { return bytesRead >= size; } } private static class SenderHandler extends IoHandlerAdapter { final CountDownLatch latch = new CountDownLatch( 1 ); InputStream inputStream; StreamWriteFilter streamWriteFilter = new StreamWriteFilter(); SenderHandler(InputStream inputStream) { this.inputStream = inputStream; } @Override public void sessionCreated(IoSession session) throws Exception { super.sessionCreated(session); session.getFilterChain().addLast("codec", streamWriteFilter); } @Override public void sessionOpened(IoSession session) throws Exception { session.write(inputStream); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { latch.countDown(); } @Override public void sessionClosed(IoSession session) throws Exception { latch.countDown(); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { latch.countDown(); } @Override public void messageSent(IoSession session, Object message) throws Exception { if (message == inputStream) { latch.countDown(); } } } private static class ReceiverHandler extends IoHandlerAdapter { final CountDownLatch latch = new CountDownLatch( 1 ); long bytesRead = 0; long size = 0; MessageDigest digest; ReceiverHandler(long size) throws Exception { this.size = size; digest = MessageDigest.getInstance("MD5"); } @Override public void sessionCreated(IoSession session) throws Exception { super.sessionCreated(session); session.setIdleTime(IdleStatus.READER_IDLE, 5); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { session.close(); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { latch.countDown(); } @Override public void sessionClosed(IoSession session) throws Exception { latch.countDown(); } @Override public void messageReceived(IoSession session, Object message) throws Exception { ByteBuffer buf = (ByteBuffer) message; while (buf.hasRemaining()) { digest.update(buf.get()); bytesRead++; } if (bytesRead >= size) { session.close(); } } } public static class WriteRequestMatcher extends AbstractMatcher { @Override protected boolean argumentMatches(Object expected, Object actual) { if (expected instanceof WriteRequest && actual instanceof WriteRequest) { WriteRequest w1 = (WriteRequest) expected; WriteRequest w2 = (WriteRequest) actual; return w1.getMessage().equals(w2.getMessage()) && w1.getFuture().isWritten() == w2.getFuture() .isWritten(); } return super.argumentMatches(expected, actual); } } private static class DummyWriteFuture implements WriteFuture { private boolean written; public boolean isWritten() { return written; } public void setWritten(boolean written) { this.written = written; } public IoSession getSession() { return null; } public Object getLock() { return this; } public void join() { } public boolean join(long timeoutInMillis) { return true; } public boolean isReady() { return true; } public void addListener(IoFutureListener listener) { } public void removeListener(IoFutureListener listener) { } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/executor/0000755000175000017500000000000011044712500024752 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/executor/ExecutorFilterRegressionTest.javamina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/executor/ExecutorFilterRegressionTest.java0000644000175000017500000001343211002320016033454 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.executor; import java.net.SocketAddress; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.CloseFuture; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.BaseIoSession; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ExecutorFilterRegressionTest extends TestCase { private ExecutorFilter filter; public ExecutorFilterRegressionTest() { } public void setUp() throws Exception { filter = new ExecutorFilter(); } public void tearDown() throws Exception { ((ThreadPoolExecutor) filter.getExecutor()).shutdown(); filter = null; } public void testEventOrder() throws Throwable { final EventOrderChecker nextFilter = new EventOrderChecker(); final EventOrderCounter[] sessions = new EventOrderCounter[] { new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), new EventOrderCounter(), }; final int loop = 1000000; final int end = sessions.length - 1; final ExecutorFilter filter = this.filter; ((ThreadPoolExecutor) filter.getExecutor()).setKeepAliveTime(3, TimeUnit.SECONDS); for (int i = 0; i < loop; i++) { Integer objI = new Integer(i); for (int j = end; j >= 0; j--) { filter.messageReceived(nextFilter, sessions[j], objI); } if (nextFilter.throwable != null) { throw nextFilter.throwable; } } Thread.sleep(1000); for (int i = end; i >= 0; i--) { Assert.assertEquals(loop - 1, sessions[i].lastCount.intValue()); } } private static class EventOrderCounter extends BaseIoSession { private Integer lastCount = null; public synchronized void setLastCount(Integer newCount) { if (lastCount != null) { Assert.assertEquals(lastCount.intValue() + 1, newCount .intValue()); } lastCount = newCount; } public IoHandler getHandler() { return null; } public IoFilterChain getFilterChain() { return null; } public CloseFuture close() { return null; } public TransportType getTransportType() { return null; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public int getScheduledWriteRequests() { return 0; } protected void updateTrafficMask() { } public boolean isClosing() { return false; } public IoService getService() { return null; } public IoServiceConfig getServiceConfig() { return null; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } } private static class EventOrderChecker implements NextFilter { private Throwable throwable; public void sessionOpened(IoSession session) { } public void sessionClosed(IoSession session) { } public void sessionIdle(IoSession session, IdleStatus status) { } public void exceptionCaught(IoSession session, Throwable cause) { } public void messageReceived(IoSession session, Object message) { try { ((EventOrderCounter) session).setLastCount((Integer) message); } catch (Throwable t) { if (this.throwable == null) { this.throwable = t; } } } public void messageSent(IoSession session, Object message) { } public void filterWrite(IoSession session, WriteRequest writeRequest) { } public void filterClose(IoSession session) { } public void sessionCreated(IoSession session) { } } public static void main(String[] args) { junit.textui.TestRunner.run(ExecutorFilterRegressionTest.class); } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/0000755000175000017500000000000011044712500024171 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/CumulativeProtocolDecoderTest.java0000644000175000017500000001425411002320016033017 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.CloseFuture; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoService; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.support.BaseIoSession; /** * Tests {@link CumulativeProtocolDecoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class CumulativeProtocolDecoderTest extends TestCase { private final IoSession session = new IoSessionImpl(); private ByteBuffer buf; private IntegerDecoder decoder; private IntegerDecoderOutput output; public static void main(String[] args) { junit.textui.TestRunner.run(CumulativeProtocolDecoderTest.class); } protected void setUp() throws Exception { buf = ByteBuffer.allocate(16); decoder = new IntegerDecoder(); output = new IntegerDecoderOutput(); } protected void tearDown() throws Exception { decoder.dispose(session); } public void testCumulation() throws Exception { buf.put((byte) 0); buf.flip(); decoder.decode(session, buf, output); Assert.assertEquals(0, output.getValues().size()); Assert.assertEquals(buf.limit(), buf.position()); buf.clear(); buf.put((byte) 0); buf.put((byte) 0); buf.put((byte) 1); buf.flip(); decoder.decode(session, buf, output); Assert.assertEquals(1, output.getValues().size()); Assert.assertEquals(new Integer(1), output.getValues().get(0)); Assert.assertEquals(buf.limit(), buf.position()); } public void testRepeatitiveDecode() throws Exception { for (int i = 0; i < 4; i++) { buf.putInt(i); } buf.flip(); decoder.decode(session, buf, output); Assert.assertEquals(4, output.getValues().size()); Assert.assertEquals(buf.limit(), buf.position()); List expected = new ArrayList(); for (int i = 0; i < 4; i++) { expected.add(new Integer(i)); } Assert.assertEquals(expected, output.getValues()); } public void testWrongImplementationDetection() throws Exception { try { new WrongDecoder().decode(session, buf, output); Assert.fail(); } catch (IllegalStateException e) { // OK } } private static class IntegerDecoder extends CumulativeProtocolDecoder { protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { Assert.assertTrue(in.hasRemaining()); if (in.remaining() < 4) return false; out.write(new Integer(in.getInt())); return true; } public void dispose() throws Exception { } } private static class IntegerDecoderOutput implements ProtocolDecoderOutput { private List values = new ArrayList(); public void write(Object message) { values.add(message); } public List getValues() { return values; } public void clear() { values.clear(); } public void flush() { } } private static class WrongDecoder extends CumulativeProtocolDecoder { protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { return true; } public void dispose() throws Exception { } } private static class IoSessionImpl extends BaseIoSession implements IoSession { public IoHandler getHandler() { return null; } public ProtocolEncoder getEncoder() { return null; } public ProtocolDecoder getDecoder() { return null; } public CloseFuture close() { return null; } public TransportType getTransportType() { return TransportType.SOCKET; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public IoFilterChain getFilterChain() { return null; } public int getScheduledWriteRequests() { return 0; } protected void updateTrafficMask() { } public boolean isClosing() { return false; } public IoService getService() { return null; } public IoServiceConfig getServiceConfig() { return null; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/textline/0000755000175000017500000000000011044712500026025 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/textline/TextLineDecoderTest.java0000644000175000017500000003334611002320016032552 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.textline; import java.net.SocketAddress; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.LinkedList; import java.util.Queue; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.BufferDataException; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * Tests {@link TextLineDecoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 585065 $, $Date: 2007-10-16 16:38:13 +0900 (Tue, 16 Oct 2007) $ */ public class TextLineDecoderTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(TextLineDecoderTest.class); } public void testNormalDecode() throws Exception { TextLineDecoder decoder = new TextLineDecoder(Charset.forName("UTF-8"), LineDelimiter.WINDOWS); CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); IoSession session = new DummySession(); TestDecoderOutput out = new TestDecoderOutput(); ByteBuffer in = ByteBuffer.allocate(16); // Test one decode and one output in.putString("ABC\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("ABC", out.getMessageQueue().poll()); // Test two decode and one output in.clear(); in.putString("DEF", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("GHI\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("DEFGHI", out.getMessageQueue().poll()); // Test one decode and two output in.clear(); in.putString("JKL\r\nMNO\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(2, out.getMessageQueue().size()); Assert.assertEquals("JKL", out.getMessageQueue().poll()); Assert.assertEquals("MNO", out.getMessageQueue().poll()); // Test splitted long delimiter decoder = new TextLineDecoder(Charset.forName("UTF-8"), new LineDelimiter("\n\n\n")); in.clear(); in.putString("PQR\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("PQR", out.getMessageQueue().poll()); // Test splitted long delimiter which produces two output decoder = new TextLineDecoder(Charset.forName("UTF-8"), new LineDelimiter("\n\n\n")); in.clear(); in.putString("PQR\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\nSTU\n\n\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(2, out.getMessageQueue().size()); Assert.assertEquals("PQR", out.getMessageQueue().poll()); Assert.assertEquals("STU", out.getMessageQueue().poll()); // Test splitted long delimiter mixed with partial non-delimiter. decoder = new TextLineDecoder(Charset.forName("UTF-8"), new LineDelimiter("\n\n\n")); in.clear(); in.putString("PQR\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("X\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\n\nSTU\n\n\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(2, out.getMessageQueue().size()); Assert.assertEquals("PQR\nX", out.getMessageQueue().poll()); Assert.assertEquals("STU", out.getMessageQueue().poll()); } public void testAutoDecode() throws Exception { TextLineDecoder decoder = new TextLineDecoder(Charset.forName("UTF-8"), LineDelimiter.AUTO); CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); IoSession session = new DummySession(); TestDecoderOutput out = new TestDecoderOutput(); ByteBuffer in = ByteBuffer.allocate(16); // Test one decode and one output in.putString("ABC\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("ABC", out.getMessageQueue().poll()); // Test two decode and one output in.clear(); in.putString("DEF", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("GHI\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("DEFGHI", out.getMessageQueue().poll()); // Test one decode and two output in.clear(); in.putString("JKL\r\nMNO\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(2, out.getMessageQueue().size()); Assert.assertEquals("JKL", out.getMessageQueue().poll()); Assert.assertEquals("MNO", out.getMessageQueue().poll()); // Test multiple '\n's in.clear(); in.putString("\n\n\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(3, out.getMessageQueue().size()); Assert.assertEquals("", out.getMessageQueue().poll()); Assert.assertEquals("", out.getMessageQueue().poll()); Assert.assertEquals("", out.getMessageQueue().poll()); // Test splitted long delimiter (\r\r\n) in.clear(); in.putString("PQR\r", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\r", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("PQR", out.getMessageQueue().poll()); // Test splitted long delimiter (\r\r\n) which produces two output in.clear(); in.putString("PQR\r", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\r", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\nSTU\r\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(2, out.getMessageQueue().size()); Assert.assertEquals("PQR", out.getMessageQueue().poll()); Assert.assertEquals("STU", out.getMessageQueue().poll()); // Test splitted long delimiter mixed with partial non-delimiter. in.clear(); in.putString("PQR\r", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("X\r", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear(); in.putString("\r\nSTU\r\r\n", encoder); in.flip(); decoder.decode(session, in, out); Assert.assertEquals(2, out.getMessageQueue().size()); Assert.assertEquals("PQR\rX", out.getMessageQueue().poll()); Assert.assertEquals("STU", out.getMessageQueue().poll()); } public void testOverflow() throws Exception { TextLineDecoder decoder = new TextLineDecoder(Charset.forName("UTF-8"), LineDelimiter.AUTO); decoder.setMaxLineLength(3); CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); IoSession session = new DummySession(); TestDecoderOutput out = new TestDecoderOutput(); ByteBuffer in = ByteBuffer.allocate(16); // Make sure the overflow exception is not thrown until // the delimiter is encountered. in.putString("A", encoder).flip().mark(); decoder.decode(session, in.reset().mark(), out); Assert.assertEquals(0, out.getMessageQueue().size()); decoder.decode(session, in.reset().mark(), out); Assert.assertEquals(0, out.getMessageQueue().size()); decoder.decode(session, in.reset().mark(), out); Assert.assertEquals(0, out.getMessageQueue().size()); decoder.decode(session, in.reset().mark(), out); Assert.assertEquals(0, out.getMessageQueue().size()); in.clear().putString("A\r\nB\r\n", encoder).flip(); try { decoder.decode(session, in, out); Assert.fail(); } catch (BufferDataException e) { // Success! } decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("B", out.getMessageQueue().poll()); // Make sure OOM is not thrown. long oldFreeMemory = Runtime.getRuntime().freeMemory(); in = ByteBuffer.allocate(1048576 * 16).mark(); for (int i = 0; i < 10; i ++) { decoder.decode(session, in.reset().mark(), out); Assert.assertEquals(0, out.getMessageQueue().size()); // Memory consumption should be minimal. Assert.assertTrue(Runtime.getRuntime().freeMemory() - oldFreeMemory < 1048576); } in.clear().putString("C\r\nD\r\n", encoder).flip(); try { decoder.decode(session, in, out); Assert.fail(); } catch (BufferDataException e) { // Success! } decoder.decode(session, in, out); Assert.assertEquals(1, out.getMessageQueue().size()); Assert.assertEquals("D", out.getMessageQueue().poll()); // Memory consumption should be minimal. Assert.assertTrue(Runtime.getRuntime().freeMemory() - oldFreeMemory < 1048576); } private static class DummySession extends BaseIoSession { @Override protected void updateTrafficMask() { } public IoService getService() { return null; } public IoServiceConfig getServiceConfig() { return null; } public IoHandler getHandler() { return null; } public IoFilterChain getFilterChain() { return null; } public TransportType getTransportType() { return null; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public int getScheduledWriteRequests() { return 0; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } } private static class TestDecoderOutput implements ProtocolDecoderOutput { private Queue messageQueue = new LinkedList(); public void write(Object message) { messageQueue.add(message); } public Queue getMessageQueue() { return messageQueue; } public void flush() { } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/textline/TextLineEncoderTest.java0000644000175000017500000000735011002320016032560 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.textline; import java.net.SocketAddress; import java.nio.charset.Charset; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoService; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.filter.codec.support.SimpleProtocolEncoderOutput; /** * Tests {@link TextLineEncoder}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class TextLineEncoderTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(TextLineEncoderTest.class); } public void testEncode() throws Exception { TextLineEncoder encoder = new TextLineEncoder(Charset.forName("UTF-8"), LineDelimiter.WINDOWS); IoSession session = new DummySession(); SimpleProtocolEncoderOutput out = new SimpleProtocolEncoderOutput() { @Override protected WriteFuture doFlush(ByteBuffer buf) { return null; } }; encoder.encode(session, "ABC", out); Assert.assertEquals(1, out.getBufferQueue().size()); ByteBuffer buf = out.getBufferQueue().poll(); Assert.assertEquals(5, buf.remaining()); Assert.assertEquals('A', buf.get()); Assert.assertEquals('B', buf.get()); Assert.assertEquals('C', buf.get()); Assert.assertEquals('\r', buf.get()); Assert.assertEquals('\n', buf.get()); } private static class DummySession extends BaseIoSession { @Override protected void updateTrafficMask() { } public IoService getService() { return null; } public IoServiceConfig getServiceConfig() { return null; } public IoHandler getHandler() { return null; } public IoFilterChain getFilterChain() { return null; } public TransportType getTransportType() { return null; } public SocketAddress getRemoteAddress() { return null; } public SocketAddress getLocalAddress() { return null; } public int getScheduledWriteRequests() { return 0; } public IoSessionConfig getConfig() { return null; } public SocketAddress getServiceAddress() { return null; } public int getScheduledWriteBytes() { return 0; } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/serialization/0000755000175000017500000000000011044712500027046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/serialization/ObjectSerializationTest.javamina-1.1.7.dfsg/core/src/test/java/org/apache/mina/filter/codec/serialization/ObjectSerializationTes0000644000175000017500000001205011002320016033376 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.serialization; import java.io.ByteArrayOutputStream; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.support.SimpleProtocolEncoderOutput; /** * Tests object serialization codec and streams. * * @author The Apache MINA Project Team (dev@mina.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ObjectSerializationTest extends TestCase { public void testEncoder() throws Exception { final String expected = "1234"; IoSession session = new MockIoSession(); SimpleProtocolEncoderOutput out = new SimpleProtocolEncoderOutput() { protected WriteFuture doFlush(ByteBuffer buf) { return null; } }; ProtocolEncoder encoder = new ObjectSerializationEncoder(); encoder.encode(session, expected, out); Assert.assertEquals(1, out.getBufferQueue().size()); ByteBuffer buf = out.getBufferQueue().poll(); testDecoderAndInputStream(expected, buf); } public void testOutputStream() throws Exception { final String expected = "1234"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectSerializationOutputStream osos = new ObjectSerializationOutputStream( baos); osos.writeObject(expected); osos.flush(); testDecoderAndInputStream(expected, ByteBuffer.wrap(baos.toByteArray())); } private void testDecoderAndInputStream(String expected, ByteBuffer in) throws Exception { // Test InputStream ObjectSerializationInputStream osis = new ObjectSerializationInputStream( in.duplicate().asInputStream()); Object actual = osis.readObject(); assertEquals(expected, actual); // Test ProtocolDecoder ProtocolDecoder decoder = new ObjectSerializationDecoder(); MockProtocolDecoderOutput decoderOut = new MockProtocolDecoderOutput(); IoSession session = new MockIoSession(); decoder.decode(session, in.duplicate(), decoderOut); Assert.assertEquals(expected, decoderOut.result.get(0)); Assert.assertEquals(1, decoderOut.result.size()); } private static class MockIoSession extends BaseIoSession { protected void updateTrafficMask() { } public IoSessionConfig getConfig() { return null; } public IoFilterChain getFilterChain() { return null; } public IoHandler getHandler() { return null; } public SocketAddress getLocalAddress() { return null; } public SocketAddress getRemoteAddress() { return null; } public int getScheduledWriteBytes() { return 0; } public int getScheduledWriteRequests() { return 0; } public IoService getService() { return null; } public SocketAddress getServiceAddress() { return null; } public IoServiceConfig getServiceConfig() { return null; } public TransportType getTransportType() { return null; } } private static class MockProtocolDecoderOutput implements ProtocolDecoderOutput { private List result = new ArrayList(); public void flush() { } public void write(Object message) { result.add(message); } } } mina-1.1.7.dfsg/core/src/test/java/org/apache/mina/util/0000755000175000017500000000000011044712500022604 5ustar drazzibdrazzibmina-1.1.7.dfsg/core/src/test/java/org/apache/mina/util/IoFilterImpl.java0000644000175000017500000000324711002320020025776 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.util; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; /** * Bogus implementation of {@link IoFilter} to test * {@link IoFilterChain}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoFilterImpl extends IoFilterAdapter { private final char c; public IoFilterImpl(char c) { this.c = c; } public int hashCode() { return c; } public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof IoFilterImpl)) return false; return this.c == ((IoFilterImpl) o).c; } public String toString() { return "" + c; } }mina-1.1.7.dfsg/LICENSE.txt0000644000175000017500000002415711002320032015075 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/integration-jmx/0000755000175000017500000000000011044712500016373 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/pom.xml0000644000175000017500000000176011002320011017676 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-integration-jmx Apache MINA JMX integration jar org.apache.mina mina-core ${pom.version} compile mina-1.1.7.dfsg/integration-jmx/src/0000755000175000017500000000000011002320011017144 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/0000755000175000017500000000000011002320011020070 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/resources/0000755000175000017500000000000011002320011022102 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/resources/META-INF/0000755000175000017500000000000011044712500023260 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320011026177 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/integration-jmx/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320011025076 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/integration-jmx/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320011026117 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/integration-jmx/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320011024770 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/integration-jmx/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320011030315 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/integration-jmx/src/main/java/0000755000175000017500000000000011002320011021011 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/java/org/0000755000175000017500000000000011002320011021600 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/0000755000175000017500000000000011002320011023021 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/0000755000175000017500000000000011002320011023745 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/0000755000175000017500000000000011002320011026270 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/0000755000175000017500000000000011044712500027104 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/package.html0000644000175000017500000000404011002320011031345 0ustar drazzibdrazzib JMX (Java Management eXtension) integration.

Monitoring Your MINA Services and Sessions

Monitoring an IoService

acceptor = new SocketAcceptor();
       
try
{
    IoServiceManager iosm = new IoServiceManager(acceptor);
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();  
    ObjectName name = new ObjectName( "com.acme.test:type=IoServiceManager,name=MyMINAServer" );
    mbs.registerMBean( iosm, name );
}
catch( JMException e )
{
    logger.error( "JMX Exception: ", e );
}

Monitoring an IoSession

Each session is registered to MBean server individually.
acceptor.addListener( new IoServiceListener()
{
    public void serviceActivated( IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config )
    {
    }

    public void serviceDeactivated( IoService service, SocketAddress serviceAddress, IoHandler handler, IoServiceConfig config )
    {
    }

    public void sessionCreated( IoSession session )
    {
        try
        {
            IoSessionManager sessMgr = new IoSessionManager( session );
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();  
            ObjectName name = new ObjectName( "com.acme.test.session:type=IoSessionManager,name=" + session.getRemoteAddress().toString().replace( ':', '/' ) );
            mbs.registerMBean( sessMgr, name );
        }
        catch( JMException e )
        {
            logger.error( "JMX Exception: ", e );
        }      
    }

    public void sessionDestroyed( IoSession session )
    {
        try
        {
            ObjectName name = new ObjectName( "com.acme.test.session:type=IoSessionManager,name=" + session.getRemoteAddress().toString().replace( ':', '/' ) );
            ManagementFactory.getPlatformMBeanServer().unregisterMBean( name );
        }
        catch( JMException e )
        {
            logger.error( "JMX Exception: ", e );
        }      
    }
});
mina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/IoSessionManager.java0000644000175000017500000001135311002320011033142 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.jmx; import java.util.Date; import java.util.List; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.management.IoSessionStat; import org.apache.mina.management.StatCollector; /** * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoSessionManager implements IoSessionManagerMBean { private IoSession session; /** * create the session manager * @param session the MINA's session to manage */ public IoSessionManager(IoSession session) { this.session = session; } public boolean isConnected() { return session.isConnected(); } public long getReadBytes() { return session.getReadBytes(); } public long getWrittenBytes() { return session.getWrittenBytes(); } public long getReadMessages() { return session.getReadMessages(); } public long getWrittenMessages() { return session.getWrittenMessages(); } public void close() throws InterruptedException { session.close().join(); } public Date getCreationTime() { return new Date(session.getCreationTime()); } public Date getLastIoTime() { return new Date(session.getLastIoTime()); } public Date getLastReadTime() { return new Date(session.getLastReadTime()); } public Date getLastWriteTime() { return new Date(session.getLastWriteTime()); } public String[] getInstalledFilters() { List filters = session.getFilterChain().getAll(); String[] res = new String[filters.size()]; for (int i = 0; i < res.length; i++) { res[i] = ((IoFilterChain.Entry) filters.get(i)).getName(); } return res; } public void addLastLoggingFilter() { LoggingFilter f = new LoggingFilter(); session.getFilterChain().addLast("LoggerLast", f); } public void removeLastLoggingFilter() { session.getFilterChain().remove("LoggerLast"); } public void addFirstLoggingFilter() { LoggingFilter f = new LoggingFilter(); session.getFilterChain().addFirst("LoggerFirst", f); } public void removeFirstLoggingFilter() { session.getFilterChain().remove("LoggerFirst"); } // IDLE monitoring public long getReadIdleTime() { return session.getIdleTimeInMillis(IdleStatus.READER_IDLE); } public long getWriteIdleTime() { return session.getIdleTimeInMillis(IdleStatus.WRITER_IDLE); } public long getBothIdleTime() { return session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE); } public float getByteReadThroughtput() { IoSessionStat stats = (IoSessionStat) session .getAttribute(StatCollector.KEY); if (stats == null) return Float.NaN; else return stats.getByteReadThroughput(); } public float getByteWrittenThroughtput() { IoSessionStat stats = (IoSessionStat) session .getAttribute(StatCollector.KEY); if (stats == null) return Float.NaN; else return stats.getByteWrittenThroughput(); } public float getMessageReadThroughtput() { IoSessionStat stats = (IoSessionStat) session .getAttribute(StatCollector.KEY); if (stats == null) return Float.NaN; else return stats.getMessageReadThroughput(); } public float getMessageWrittenThroughtput() { IoSessionStat stats = (IoSessionStat) session .getAttribute(StatCollector.KEY); if (stats == null) return Float.NaN; else return stats.getMessageWrittenThroughput(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/IoSessionManagerMBean.javamina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/IoSessionManagerMBean.0000644000175000017500000001060711002320011033204 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.jmx; import java.util.Date; /** * MBean interface for the session manager, it's used for instrumenting IoSession * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoSessionManagerMBean { /** * is the session is connected * @return connection status */ public boolean isConnected(); /** * bytes read from the beginning * @return total of bytes read */ public long getReadBytes(); /** * bytes written from the beginning * @return total of bytes written */ public long getWrittenBytes(); /** * PDU decoded from the beginning. Only revelent if a ProtocolCodecFilter is installed. * @return Number of read messages */ public long getReadMessages(); /** * PDU encoded from the beginning. Only revelent if a ProtocolCodecFilter is installed. * @return Number of written messages */ public long getWrittenMessages(); /** * close the session */ public void close() throws InterruptedException; /** * when the session was created * @return the date of session creation */ public Date getCreationTime(); /** * last time the session processed an IO * @return date of last IO */ public Date getLastIoTime(); /** * last time the session processed a write * @return date of last write */ public Date getLastWriteTime(); /** * last time the session processed an read * @return date of last read */ public Date getLastReadTime(); /** * get the list of filters installed in the filter chain * @return array of filter names */ public String[] getInstalledFilters(); /** * add a logging filter at end of the chain */ public void addLastLoggingFilter(); /** * remove the logging filter at end of the chain */ public void removeLastLoggingFilter(); /** * add a logging filter at begining of the chain */ public void addFirstLoggingFilter(); /** * remove the logging filter at begining of the chain */ public void removeFirstLoggingFilter(); /** * read and write IDLE time * @return idle time in milli-seconds */ public long getBothIdleTime(); /** * read IDLE time * @return read idle time in milli-seconds */ public long getReadIdleTime(); /** * write IDLE time * @return write idle time in milli-seconds */ public long getWriteIdleTime(); /** * get the read bytes per second throughput * works only if a stat collector is inspecting this session, * @return read bytes per seconds */ public float getByteReadThroughtput(); /** * get the written bytes per second throughput * works only if a stat collector is inspecting this session, * @return written bytes per seconds */ public float getByteWrittenThroughtput(); /** * get the read messages per second throughput * works only if a stat collector is inspecting this session, and only if a ProtocolDecoderFilter is used * @return read messages per seconds */ public float getMessageReadThroughtput(); /** * get the written messages per second throughput * works only if a stat collector is inspecting this session, and only if a ProtocolDecoderFilter is used * @return written messages per seconds */ public float getMessageWrittenThroughtput(); }mina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/IoServiceManager.java0000644000175000017500000000724611002320011033125 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.jmx; import java.net.SocketAddress; import java.util.Iterator; import org.apache.mina.common.IoService; import org.apache.mina.common.IoSession; import org.apache.mina.management.StatCollector; /** * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoServiceManager implements IoServiceManagerMBean { private IoService service; private StatCollector collector = null; public IoServiceManager(IoService service) { this.service = service; } public int getManagedSessionCount() { int count = 0; for (Iterator iter = service.getManagedServiceAddresses().iterator(); iter .hasNext();) { SocketAddress element = (SocketAddress) iter.next(); count += service.getManagedSessions(element).size(); } return count; } public void startCollectingStats(int millisecondsPolling) { if (collector != null && collector.isRunning()) { throw new RuntimeException("Already collecting stats"); } collector = new StatCollector(service, millisecondsPolling); collector.start(); } public void stopCollectingStats() { if (collector != null && collector.isRunning()) collector.stop(); } public float getTotalByteReadThroughput() { return collector.getBytesReadThroughput(); } public float getTotalByteWrittenThroughput() { return collector.getBytesWrittenThroughput(); } public float getTotalMessageReadThroughput() { return collector.getMsgReadThroughput(); } public float getTotalMessageWrittenThroughput() { return collector.getMsgWrittenThroughput(); } public float getAverageByteReadThroughput() { return collector.getBytesReadThroughput() / collector.getSessionCount(); } public float getAverageByteWrittenThroughput() { return collector.getBytesWrittenThroughput() / collector.getSessionCount(); } public float getAverageMessageReadThroughput() { return collector.getMsgReadThroughput() / collector.getSessionCount(); } public float getAverageMessageWrittenThroughput() { return collector.getMsgWrittenThroughput() / collector.getSessionCount(); } public void closeAllSessions() { for (Iterator iter = service.getManagedServiceAddresses().iterator(); iter .hasNext();) { SocketAddress element = (SocketAddress) iter.next(); for (Iterator iter2 = service.getManagedSessions(element) .iterator(); iter2.hasNext();) { IoSession session = (IoSession) iter2.next(); session.close(); } } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/IoServiceManagerMBean.javamina-1.1.7.dfsg/integration-jmx/src/main/java/org/apache/mina/integration/jmx/IoServiceManagerMBean.0000644000175000017500000000562511002320011033165 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.jmx; /** * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public interface IoServiceManagerMBean { /** * amount of session currently managed * @return session count */ int getManagedSessionCount(); /** * start collecting throughput statistics for all the managed sessions * @param millisecondsPolling polling time in milliseconds like 5000 for computing throughput every 5 seconds */ void startCollectingStats(int millisecondsPolling); /** * stop collecting throughput statistics */ void stopCollectingStats(); /** * bytes read per seconds sum of all the managed sessions * @return bytes per seconds */ float getTotalByteReadThroughput(); /** * bytes written per seconds sum for all the managed sessions * @return bytes per seconds */ float getTotalByteWrittenThroughput(); /** * messages read per seconds sum of all the managed sessions * @return messages per seconds */ float getTotalMessageReadThroughput(); /** * messages written per seconds sum for all the managed sessions * @return messages per seconds */ float getTotalMessageWrittenThroughput(); /** * average bytes read per seconds for all the managed sessions * @return bytes per seconds */ float getAverageByteReadThroughput(); /** * average bytes written per seconds for all the managed sessions * @return bytes per seconds */ float getAverageByteWrittenThroughput(); /** * average messages read per seconds for all the managed sessions * @return messages per seconds */ float getAverageMessageReadThroughput(); /** * average messages written per seconds for all the managed sessions * @return messages per seconds */ float getAverageMessageWrittenThroughput(); /** * close all the managed sessions */ void closeAllSessions(); }mina-1.1.7.dfsg/integration-spring/0000755000175000017500000000000011044712500017077 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/pom.xml0000644000175000017500000000340111002320014020377 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-integration-spring Apache MINA Spring Integration jar org.apache.mina mina-filter-ssl ${pom.version} compile org.slf4j slf4j-simple 1.4.3 test org.springframework spring-beans 2.0.6 org.springframework spring-core 2.0.6 easymock easymock 1.2_Java1.3 test easymock easymockclassextension 1.1 test commons-net commons-net 1.4.1 test mina-1.1.7.dfsg/integration-spring/src/0000755000175000017500000000000011002320012017651 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/0000755000175000017500000000000011002320013020576 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/resources/0000755000175000017500000000000011002320013022610 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/resources/META-INF/0000755000175000017500000000000011044712500023764 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320014026706 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/integration-spring/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320014025605 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/integration-spring/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320014026626 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/integration-spring/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320014025477 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/integration-spring/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320014031024 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/integration-spring/src/main/java/0000755000175000017500000000000011002320012021516 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/java/org/0000755000175000017500000000000011002320012022305 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/0000755000175000017500000000000011002320012023526 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/0000755000175000017500000000000011002320012024452 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/0000755000175000017500000000000011002320012026775 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/0000755000175000017500000000000011044712500030314 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ExecutorThreadModelFactoryBean.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ExecutorThreadMo0000644000175000017500000000610211002320013033444 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import org.apache.mina.common.ExecutorThreadModel; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; import java.util.concurrent.Executor; /** * Spring {@link FactoryBean} which makes it possible to set up a MINA * {@link ExecutorThreadModel} using Spring. The serviceName * property must be set using {@link #setServiceName(String)}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class ExecutorThreadModelFactoryBean implements FactoryBean, InitializingBean { private String serviceName = null; private Executor executor = null; /** * Sets the {@link Executor} to use. If not set a default {@link Executor} * will be used by the {@link ExecutorThreadModel} created by this * factory bean. * * @param executor the executor. * @throws IllegalArgumentException if the specified value is * null. */ public void setExecutor(Executor executor) { Assert.notNull(executor, "Property 'executor' may not be null"); this.executor = executor; } /** * Sets the name of the service as used in the call to * {@link ExecutorThreadModel#getInstance(String)}. This property is * required. * * @param executor the executor. * @throws IllegalArgumentException if the specified value is * null. */ public void setServiceName(String serviceName) { Assert.notNull(serviceName, "Property 'serviceName' may not be null"); this.serviceName = serviceName; } public Class getObjectType() { return ExecutorThreadModel.class; } public Object getObject() throws Exception { ExecutorThreadModel model = ExecutorThreadModel .getInstance(serviceName); if (executor != null) { model.setExecutor(executor); } return model; } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { Assert.notNull(serviceName, "Property 'serviceName' may not be null"); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ThreadPoolExecutorFactoryBean.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ThreadPoolExecut0000644000175000017500000001127611002320013033451 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.AbstractFactoryBean; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Spring {@link FactoryBean} which enables the configuration of * {@link ThreadPoolExecutor} instances using Spring. Most of this code * has been copied from the ThreadPoolTaskExecutor class * available in Spring 2.0. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class ThreadPoolExecutorFactoryBean extends AbstractFactoryBean { private int corePoolSize = 1; private int maxPoolSize = Integer.MAX_VALUE; private int keepAliveSeconds = 60; private int queueCapacity = Integer.MAX_VALUE; private ThreadFactory threadFactory = Executors.defaultThreadFactory(); private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy(); /** * Set the ThreadPoolExecutor's core pool size. Default is 1. */ public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } /** * Set the ThreadPoolExecutor's maximum pool size. Default is * Integer.MAX_VALUE. */ public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } /** * Set the ThreadPoolExecutor's keep alive seconds. Default is 60. */ public void setKeepAliveSeconds(int keepAliveSeconds) { this.keepAliveSeconds = keepAliveSeconds; } /** * Set the capacity for the ThreadPoolExecutor's BlockingQueue. Default is * Integer.MAX_VALUE. *

* Any positive value will lead to a LinkedBlockingQueue instance; any other * value will lead to a SynchronousQueue instance. * * @see LinkedBlockingQueue * @see SynchronousQueue */ public void setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; } /** * Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool. * Default is the ThreadPoolExecutor's default thread factory. * * @see Executors#defaultThreadFactory() */ public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = (threadFactory != null ? threadFactory : Executors .defaultThreadFactory()); } /** * Set the RejectedExecutionHandler to use for the ThreadPoolExecutor. * Default is the ThreadPoolExecutor's default abort policy. * * @see ThreadPoolExecutor.AbortPolicy */ public void setRejectedExecutionHandler( RejectedExecutionHandler rejectedExecutionHandler) { this.rejectedExecutionHandler = (rejectedExecutionHandler != null ? rejectedExecutionHandler : new ThreadPoolExecutor.AbortPolicy()); } protected Object createInstance() throws Exception { BlockingQueue queue = null; if (queueCapacity > 0) { queue = new LinkedBlockingQueue(queueCapacity); } else { queue = new SynchronousQueue(); } return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS, queue, threadFactory, rejectedExecutionHandler); } protected void destroyInstance(Object o) throws Exception { ThreadPoolExecutor executor = (ThreadPoolExecutor) o; executor.shutdown(); } public Class getObjectType() { return ThreadPoolExecutor.class; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/IoAcceptorFactoryBean.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/IoAcceptorFactor0000644000175000017500000001500011002320013033406 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.net.SocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * Spring {@link FactoryBean} which enables the bindings of an {@link IoAcceptor} * to be configured using Spring. Example of usage: *

* *

 *   <!-- This makes it possible to specify java.net.SocketAddress values 
 *        (e.g. :80 below) as Strings.
 *        They will be converted into java.net.InetSocketAddress objects by Spring.  -->
 *   <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
 *     <property name="customEditors">
 *       <map>
 *         <entry key="java.net.SocketAddress">
 *           <bean class="org.apache.mina.integration.spring.InetSocketAddressEditor"/>
 *         </entry>
 *       </map>
 *     </property>
 *   </bean>
 * 
 *   <!-- The IoHandler implementation -->
 *   <bean id="httpHandler" class="com.example.MyHttpHandler">
 *     ...
 *   </bean>
 *     
 *   <bean id="filterChainBuilder" 
 *         class="org.apache.mina.integration.spring.DefaultIoFilterChainBuilderFactoryBean">
 *     <property name="filters">
 *       <list>
 *         <bean class="org.apache.mina.filter.LoggingFilter"/>
 *       </list>
 *     </property>
 *   </bean>
 *
 *  <!-- By default MINA uses an ExecutorThreadModel. This demonstrates how to 
 *          use your own with some non default settings. The threadModel will 
 *          be set on the SocketAcceptorConfig defined below. To configure a 
 *          ExecutorFilter directly you will have to use the ThreadModel.MANUAL 
 *          ThreadModel instead. -->
 *   <bean id="threadModel" class="org.apache.mina.integration.spring.ExecutorThreadModelFactoryBean">
 *     <property name="serviceName" value="HttpService"/>
 *     <property name="executor">
 *       <bean class="org.apache.mina.integration.spring.ThreadPoolExecutorFactoryBean">
 *         <property name="corePoolSize" value="2"/>
 *         <property name="maxPoolSize" value="10"/>
 *         <property name="keepAliveSeconds" value="30"/>
 *       </bean>
 *     </property>
 *   </bean>
 *
 *   <bean id="ioAcceptor" class="org.apache.mina.integration.spring.IoAcceptorFactoryBean">
 *     <property name="target">
 *       <bean class="org.apache.mina.transport.socket.nio.SocketAcceptor"/>
 *     </property>
 *     <property name="bindings">
 *       <list>
 *         <bean class="org.apache.mina.integration.spring.Binding">
 *           <property name="address" value=":80"/>
 *           <property name="handler" ref="httpHandler"/>
 *           <property name="serviceConfig">
 *             <bean class="org.apache.mina.transport.socket.nio.SocketAcceptorConfig">
 *               <property name="filterChainBuilder" ref="filterChainBuilder"/>
 *               <property name="reuseAddress" value="true"/>
 *               <property name="threadModel" ref="threadModel"/> 
 *             </bean>
 *           </property>
 *         </bean>
 *       </list>
 *     </property>
 *   </bean>
 * 
* *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoAcceptorFactoryBean implements FactoryBean, InitializingBean, DisposableBean { private Binding[] bindings = new Binding[0]; private IoAcceptor target; /** * Sets the {@link IoAcceptor} to be configured using this factory bean. * * @param target the target {@link IoAcceptor}. */ public void setTarget(IoAcceptor target) { this.target = target; } /** * Sets the bindings to be used by the {@link IoAcceptor} configured by this * factory bean. * * @param bindings the bindings. * @throws IllegalArgumentException if the specified value is * null. * @see IoAcceptor#bind(SocketAddress, IoHandler) * @see IoAcceptor#bind(SocketAddress, IoHandler, IoServiceConfig) * @see Binding */ public void setBindings(Binding[] bindings) { Assert.notNull(bindings, "Property 'bindings' may not be null"); this.bindings = bindings; } public Object getObject() throws Exception { return target; } public Class getObjectType() { return IoAcceptor.class; } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { Assert.notNull(target, "Property 'target' may not be null"); /* * Bind all. */ for (int i = 0; i < bindings.length; i++) { Binding b = bindings[i]; if (b.getServiceConfig() != null) { target.bind(b.getAddress(), b.getHandler(), b .getServiceConfig()); } else { target.bind(b.getAddress(), b.getHandler()); } } } public void destroy() throws Exception { for (int i = 0; i < bindings.length; i++) { Binding b = bindings[i]; try { target.unbind(b.getAddress()); } catch (Exception ignored) { } } } } mina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/package.html0000644000175000017500000000031511002320013032560 0ustar drazzibdrazzib SpringFramework-specific classes for integration ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/InetAddressEditor.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/InetAddressEdito0000644000175000017500000000413311002320013033416 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.beans.PropertyEditorSupport; import java.net.InetAddress; import java.net.UnknownHostException; /** * Java Bean {@link java.beans.PropertyEditor} which converts Strings into * {@link InetAddress} objects. This may be used together with Spring to be able * to set {@link InetAddress} bean properties, e.g. * {@link org.apache.mina.filter.BlacklistFilter#setBlacklist(InetAddress[])}. * Simply calls {@link InetAddress#getByName(java.lang.String)} when * converting from a String. *

* Use Spring's CustomEditorConfigurer to use this property editor in a Spring * configuration file. See chapter 3.14 of the Spring Reference Documentation * for more info. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Revision: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see java.net.InetAddress */ public class InetAddressEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { try { setValue(InetAddress.getByName(text)); } catch (UnknownHostException uhe) { IllegalArgumentException iae = new IllegalArgumentException(); iae.initCause(uhe); } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/VmPipeAddressEditor.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/VmPipeAddressEdi0000644000175000017500000000442111002320013033354 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.beans.PropertyEditorSupport; import java.net.SocketAddress; import org.apache.mina.transport.vmpipe.VmPipeAddress; import org.springframework.util.Assert; /** * Java Bean {@link java.beans.PropertyEditor} which converts Strings into * {@link VmPipeAddress} objects. Valid values specify an integer port number * optionally prefixed with a ':'. E.g.: :80, 22. *

* Use Spring's CustomEditorConfigurer to use this property editor in a Spring * configuration file. See chapter 3.14 of the Spring Reference Documentation * for more info. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Revision: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see org.apache.mina.transport.vmpipe.VmPipeAddress */ public class VmPipeAddressEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { setValue(parseSocketAddress(text)); } private SocketAddress parseSocketAddress(String s) { Assert.notNull(s, "null SocketAddress string"); s = s.trim(); if (s.startsWith(":")) { s = s.substring(1); } try { return new VmPipeAddress(Integer.parseInt(s.trim())); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Illegal vm pipe address: " + s); } } } mina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/0000755000175000017500000000000011044712500031115 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/package.htmlmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/package.html0000644000175000017500000000032111002320013033356 0ustar drazzibdrazzib SpringFramework-specific classes for SSL integration ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/SSLContextFactoryBean.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/SSLContextFa0000644000175000017500000003332111002320013033303 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring.ssl; import java.security.KeyStore; import java.security.SecureRandom; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.ManagerFactoryParameters; import org.springframework.beans.factory.config.AbstractFactoryBean; import org.springframework.util.Assert; /** * Spring {@link org.springframework.beans.factory.FactoryBean} implementation * which makes it possible to configure {@link javax.net.ssl.SSLContext} * instances using Spring. *

* If no properties are set the returned {@link javax.net.ssl.SSLContext} will * be equivalent to what the following creates: *

 *      SSLContext c = SSLContext.getInstance( "TLS" );
 *      c.init( null, null, null );
 * 
*

*

* Use the properties prefixed with keyManagerFactory to control * the creation of the {@link javax.net.ssl.KeyManager} to be used. *

*

* Use the properties prefixed with trustManagerFactory to control * the creation of the {@link javax.net.ssl.TrustManagerFactory} to be used. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SSLContextFactoryBean extends AbstractFactoryBean { private String protocol = "TLS"; private String provider = null; private SecureRandom secureRandom = null; private KeyStore keyManagerFactoryKeyStore = null; private char[] keyManagerFactoryKeyStorePassword = null; private KeyManagerFactory keyManagerFactory = null; private String keyManagerFactoryAlgorithm = null; private String keyManagerFactoryProvider = null; private boolean keyManagerFactoryAlgorithmUseDefault = false; private KeyStore trustManagerFactoryKeyStore = null; private TrustManagerFactory trustManagerFactory = null; private String trustManagerFactoryAlgorithm = null; private String trustManagerFactoryProvider = null; private boolean trustManagerFactoryAlgorithmUseDefault = false; private ManagerFactoryParameters trustManagerFactoryParameters = null; protected Object createInstance() throws Exception { KeyManagerFactory kmf = this.keyManagerFactory; TrustManagerFactory tmf = this.trustManagerFactory; if (kmf == null) { String algorithm = keyManagerFactoryAlgorithm; if (algorithm == null && keyManagerFactoryAlgorithmUseDefault) { algorithm = KeyManagerFactory.getDefaultAlgorithm(); } if (algorithm != null) { if (keyManagerFactoryProvider == null) { kmf = KeyManagerFactory.getInstance(algorithm); } else { kmf = KeyManagerFactory.getInstance(algorithm, keyManagerFactoryProvider); } } } if (tmf == null) { String algorithm = trustManagerFactoryAlgorithm; if (algorithm == null && trustManagerFactoryAlgorithmUseDefault) { algorithm = TrustManagerFactory.getDefaultAlgorithm(); } if (algorithm != null) { if (trustManagerFactoryProvider == null) { tmf = TrustManagerFactory.getInstance(algorithm); } else { tmf = TrustManagerFactory.getInstance(algorithm, trustManagerFactoryProvider); } } } KeyManager[] keyManagers = null; if (kmf != null) { kmf.init(keyManagerFactoryKeyStore, keyManagerFactoryKeyStorePassword); keyManagers = kmf.getKeyManagers(); } TrustManager[] trustManagers = null; if (tmf != null) { if (trustManagerFactoryParameters != null) { tmf.init(trustManagerFactoryParameters); } else { tmf.init(trustManagerFactoryKeyStore); } trustManagers = tmf.getTrustManagers(); } SSLContext context = null; if (provider == null) { context = SSLContext.getInstance(protocol); } else { context = SSLContext.getInstance(protocol, provider); } context.init(keyManagers, trustManagers, secureRandom); return context; } public Class getObjectType() { return SSLContext.class; } /** * Sets the protocol to use when creating the {@link SSLContext}. The * default is TLS. * * @param protocol the name of the protocol. * @throws IllegalArgumentException if the specified value is * null. */ public void setProtocol(String protocol) { Assert.notNull(protocol, "Property 'protocol' may not be null"); this.protocol = protocol; } /** * If this is set to true while no {@link KeyManagerFactory} * has been set using {@link #setKeyManagerFactory(KeyManagerFactory)} and * no algorithm has been set using * {@link #setKeyManagerFactoryAlgorithm(String)} the default algorithm * return by {@link KeyManagerFactory#getDefaultAlgorithm()} will be used. * * @param useDefault true or false. */ public void setKeyManagerFactoryAlgorithmUseDefault(boolean useDefault) { this.keyManagerFactoryAlgorithmUseDefault = useDefault; } /** * If this is set to true while no {@link TrustManagerFactory} * has been set using {@link #setTrustManagerFactory(TrustManagerFactory)} and * no algorithm has been set using * {@link #setTrustManagerFactoryAlgorithm(String)} the default algorithm * return by {@link TrustManagerFactory#getDefaultAlgorithm()} will be used. * * @param useDefault true or false. */ public void setTrustManagerFactoryAlgorithmUseDefault(boolean useDefault) { this.trustManagerFactoryAlgorithmUseDefault = useDefault; } /** * Sets the {@link KeyManagerFactory} to use. If this is set the properties * which are used by this factory bean to create a {@link KeyManagerFactory} * will all be ignored. * * @param factory the factory. */ public void setKeyManagerFactory(KeyManagerFactory factory) { this.keyManagerFactory = factory; } /** * Sets the algorithm to use when creating the {@link KeyManagerFactory} * using {@link KeyManagerFactory#getInstance(java.lang.String)} or * {@link KeyManagerFactory#getInstance(java.lang.String, java.lang.String)}. *

* This property will be ignored if a {@link KeyManagerFactory} has been * set directly using {@link #setKeyManagerFactory(KeyManagerFactory)}. *

*

* If this property isn't set while no {@link KeyManagerFactory} has been * set using {@link #setKeyManagerFactory(KeyManagerFactory)} and * {@link #setKeyManagerFactoryAlgorithmUseDefault(boolean)} has been set to * true the value returned * by {@link KeyManagerFactory#getDefaultAlgorithm()} will be used instead. *

* * @param algorithm the algorithm to use. */ public void setKeyManagerFactoryAlgorithm(String algorithm) { this.keyManagerFactoryAlgorithm = algorithm; } /** * Sets the provider to use when creating the {@link KeyManagerFactory} * using * {@link KeyManagerFactory#getInstance(java.lang.String, java.lang.String)}. *

* This property will be ignored if a {@link KeyManagerFactory} has been * set directly using {@link #setKeyManagerFactory(KeyManagerFactory)}. *

*

* If this property isn't set and no {@link KeyManagerFactory} has been set * using {@link #setKeyManagerFactory(KeyManagerFactory)} * {@link KeyManagerFactory#getInstance(java.lang.String)} will be used * to create the {@link KeyManagerFactory}. *

* * @param provider the name of the provider. */ public void setKeyManagerFactoryProvider(String provider) { this.keyManagerFactoryProvider = provider; } /** * Sets the {@link KeyStore} which will be used in the call to * {@link KeyManagerFactory#init(java.security.KeyStore, char[])} when * the {@link SSLContext} is created. * * @param keyStore the key store. */ public void setKeyManagerFactoryKeyStore(KeyStore keyStore) { this.keyManagerFactoryKeyStore = keyStore; } /** * Sets the password which will be used in the call to * {@link KeyManagerFactory#init(java.security.KeyStore, char[])} when * the {@link SSLContext} is created. * * @param password the password. Use null to disable password. */ public void setKeyManagerFactoryKeyStorePassword(String password) { if (password != null) { this.keyManagerFactoryKeyStorePassword = password.toCharArray(); } else { this.keyManagerFactoryKeyStorePassword = null; } } /** * Sets the {@link TrustManagerFactory} to use. If this is set the properties * which are used by this factory bean to create a {@link TrustManagerFactory} * will all be ignored. * * @param factory the factory. */ public void setTrustManagerFactory(TrustManagerFactory factory) { this.trustManagerFactory = factory; } /** * Sets the algorithm to use when creating the {@link TrustManagerFactory} * using {@link TrustManagerFactory#getInstance(java.lang.String)} or * {@link TrustManagerFactory#getInstance(java.lang.String, java.lang.String)}. *

* This property will be ignored if a {@link TrustManagerFactory} has been * set directly using {@link #setTrustManagerFactory(TrustManagerFactory)}. *

*

* If this property isn't set while no {@link TrustManagerFactory} has been * set using {@link #setTrustManagerFactory(TrustManagerFactory)} and * {@link #setTrustManagerFactoryAlgorithmUseDefault(boolean)} has been set to * true the value returned * by {@link TrustManagerFactory#getDefaultAlgorithm()} will be used instead. *

* * @param algorithm the algorithm to use. */ public void setTrustManagerFactoryAlgorithm(String algorithm) { this.trustManagerFactoryAlgorithm = algorithm; } /** * Sets the {@link KeyStore} which will be used in the call to * {@link TrustManagerFactory#init(java.security.KeyStore)} when * the {@link SSLContext} is created. *

* This property will be ignored if {@link ManagerFactoryParameters} has been * set directly using {@link #setTrustManagerFactoryParameters(ManagerFactoryParameters)}. *

* * @param keyStore the key store. */ public void setTrustManagerFactoryKeyStore(KeyStore keyStore) { this.trustManagerFactoryKeyStore = keyStore; } /** * Sets the {@link ManagerFactoryParameters} which will be used in the call to * {@link TrustManagerFactory#init(javax.net.ssl.ManagerFactoryParameters)} when * the {@link SSLContext} is created. * * @param parameters describing provider-specific trust material. */ public void setTrustManagerFactoryParameters( ManagerFactoryParameters parameters) { this.trustManagerFactoryParameters = parameters; } /** * Sets the provider to use when creating the {@link TrustManagerFactory} * using * {@link TrustManagerFactory#getInstance(java.lang.String, java.lang.String)}. *

* This property will be ignored if a {@link TrustManagerFactory} has been * set directly using {@link #setTrustManagerFactory(TrustManagerFactory)}. *

*

* If this property isn't set and no {@link TrustManagerFactory} has been set * using {@link #setTrustManagerFactory(TrustManagerFactory)} * {@link TrustManagerFactory#getInstance(java.lang.String)} will be used * to create the {@link TrustManagerFactory}. *

* * @param provider the name of the provider. */ public void setTrustManagerFactoryProvider(String provider) { this.trustManagerFactoryProvider = provider; } /** * Sets the {@link SecureRandom} to use when initializing the * {@link SSLContext}. The JVM's default will be used if this isn't set. * * @param secureRandom the {@link SecureRandom} or null if the * JVM's default should be used. * @see SSLContext#init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], java.security.SecureRandom) */ public void setSecureRandom(SecureRandom secureRandom) { this.secureRandom = secureRandom; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/BogusTrustManagerFactory.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/BogusTrustMa0000644000175000017500000000573311002320013033433 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring.ssl; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Provider; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactorySpi; import javax.net.ssl.X509TrustManager; /** * Bogus {@link javax.net.ssl.TrustManagerFactory} which creates * {@link javax.net.ssl.X509TrustManager} trusting everything. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class BogusTrustManagerFactory extends TrustManagerFactory { public BogusTrustManagerFactory() { super(new BogusTrustManagerFactorySpi(), new Provider("MinaBogus", 1.0, "") { private static final long serialVersionUID = -4024169055312053827L; }, "MinaBogus"); } private static final X509TrustManager X509 = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; private static final TrustManager[] X509_MANAGERS = new TrustManager[] { X509 }; private static class BogusTrustManagerFactorySpi extends TrustManagerFactorySpi { protected TrustManager[] engineGetTrustManagers() { return X509_MANAGERS; } protected void engineInit(KeyStore keystore) throws KeyStoreException { // noop } protected void engineInit( ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException { // noop } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/KeyStoreFactoryBean.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/ssl/KeyStoreFact0000644000175000017500000001117411002320013033373 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring.ssl; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import org.springframework.beans.factory.config.AbstractFactoryBean; import org.springframework.core.io.Resource; import org.springframework.util.Assert; /** * Spring {@link org.springframework.beans.factory.FactoryBean} implementation * which makes it possible to configure {@link java.security.KeyStore} instances * using Spring. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class KeyStoreFactoryBean extends AbstractFactoryBean { private String type = "JKS"; private String provider = null; private char[] password = null; private File file = null; private Resource resource = null; /** * Creates a new {@link KeyStore}. This method will be called * by the base class when Spring creates a bean using this FactoryBean. * * @return the {@link KeyStore} instance. */ protected Object createInstance() throws Exception { if (file == null && resource == null) { throw new IllegalArgumentException("Required property missing. " + "Either 'file' or 'resource' have to be specified"); } KeyStore ks = null; if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } InputStream is = null; if (file != null) { is = new BufferedInputStream(new FileInputStream(file)); } else { is = resource.getInputStream(); } try { ks.load(is, password); } finally { try { is.close(); } catch (IOException ignored) { } } return ks; } public Class getObjectType() { return KeyStore.class; } /** * Sets the file which contains the key store. Either this * property or {@link #setProvider(String)} have to be set. * * @param file the file to load the key store from. */ public void setFile(File file) { this.file = file; } /** * Sets the key store password. If this value is null no * password will be used to check the integrity of the key store. * * @param password the password or null if no password is * needed. */ public void setPassword(String password) { if (password != null) { this.password = password.toCharArray(); } else { this.password = null; } } /** * Sets the name of the provider to use when creating the key store. The * default is to use the platform default provider. * * @param provider the name of the provider, e.g. SUN. */ public void setProvider(String provider) { this.provider = provider; } /** * Sets a Spring {@link Resource} which contains the key store. Either this * property or {@link #setFile(File)} have to be set. * * @param resource the resource to load the key store from. */ public void setResource(Resource resource) { this.resource = resource; } /** * Sets the type of key store to create. The default is to create a * JKS key store. * * @param type the type to use when creating the key store. * @throws IllegalArgumentException if the specified value is * null. */ public void setType(String type) { Assert.notNull(type, "Property 'type' may not be null"); this.type = type; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/InetSocketAddressEditor.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/InetSocketAddres0000644000175000017500000000526511002320013033426 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.beans.PropertyEditorSupport; import java.net.InetSocketAddress; import java.net.SocketAddress; import org.springframework.util.Assert; /** * Java Bean {@link java.beans.PropertyEditor} which converts Strings into * {@link InetSocketAddress} objects. Valid values include a hostname or ip * address and a port number separated by a ':'. If the hostname or ip address * is omitted the wildcard address will be used. E.g.: * google.com:80, :22, 192.168.0.1:110. *

* Use Spring's CustomEditorConfigurer to use this property editor in a Spring * configuration file. See chapter 3.14 of the Spring Reference Documentation * for more info. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Revision: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see java.net.InetSocketAddress */ public class InetSocketAddressEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { setValue(parseSocketAddress(text)); } private SocketAddress parseSocketAddress(String s) { Assert.notNull(s, "null SocketAddress string"); s = s.trim(); int colonIndex = s.indexOf(":"); if (colonIndex > 0) { String host = s.substring(0, colonIndex); int port = parsePort(s.substring(colonIndex + 1)); return new InetSocketAddress(host, port); } else { int port = parsePort(s.substring(colonIndex + 1)); return new InetSocketAddress(port); } } private int parsePort(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Illegal port number: " + s); } } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/DefaultIoFilterChainBuilderFactoryBean.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/DefaultIoFilterC0000644000175000017500000001167011002320013033355 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.util.List; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoFilter; import org.springframework.beans.factory.config.AbstractFactoryBean; import org.springframework.util.Assert; /** * Spring {@link org.springframework.beans.factory.FactoryBean} * which creates {@link DefaultIoFilterChainBuilder} instances. This * factory bean makes it possible to configure the filters to be added to all the * sessions created by an {@link org.apache.mina.common.IoAcceptor} * or {@link org.apache.mina.common.IoConnector} using Spring. *

* The filters may be set up in two ways. By creating * {@link IoFilterMapping} objects which associate a name with an {@link IoFilter} * instance and set them using {@link #setFilterMappings(IoFilterMapping[])} or * by using {@link #setFilters(IoFilter[])} directly which assigns automatically * generated names to each {@link IoFilter}. Use the * {@link #setFilterNamePrefix(String)} method to set the prefix used for * auto generated names. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DefaultIoFilterChainBuilderFactoryBean extends AbstractFactoryBean { private IoFilterMapping[] filterMappings = new IoFilterMapping[0]; private String prefix = "filter"; protected Object createInstance() throws Exception { DefaultIoFilterChainBuilder builder = new DefaultIoFilterChainBuilder(); for (int i = 0; i < filterMappings.length; i++) { String name = filterMappings[i].getName(); if (name == null) { name = prefix + i; } builder.addLast(name, filterMappings[i].getFilter()); } return builder; } public Class getObjectType() { return DefaultIoFilterChainBuilder.class; } /** * Sets the prefix used to create the names for automatically named filters * added using {@link #setFilters(IoFilter[])}. The default prefix is * filter. * * @param prefix the prefix. * @throws IllegalArgumentException if the specified value is * null. */ public void setFilterNamePrefix(String prefix) { Assert.notNull(prefix, "Property 'filterNamePrefix' may not be null"); this.prefix = prefix; } /** * Sets a number of filters which will be added to the filter * chain created by this factory bean. The specified list must contain either * {@link IoFilter} or {@link IoFilterMapping} objects. Filters which * haven't been wrapped in {@link IoFilterMapping} objects will be assigned * automatically generated names (<filterNamePrefix>0, * <filterNamePrefix>1, etc). * * @param filters the list of {@link IoFilter} and/or * {@link IoFilterMapping} objects. * @throws IllegalArgumentException if the specified value is * null or contains objects of the wrong type. * @see #setFilterNamePrefix(String) */ public void setFilters(List filters) { Assert.notNull(filters, "Property 'filters' may not be null"); IoFilterMapping[] filterMappings = new IoFilterMapping[filters.size()]; for (int i = 0; i < filterMappings.length; i++) { Object o = filters.get(i); if (o instanceof IoFilterMapping) { filterMappings[i] = (IoFilterMapping) o; } else if (o instanceof IoFilter) { filterMappings[i] = new IoFilterMapping(); filterMappings[i].setFilter((IoFilter) o); } else { throw new IllegalArgumentException( "List may only contain " + "IoFilter or IoFilterMapping objects. Found object of " + "type " + o.getClass().getName() + " at position " + i + "."); } } this.filterMappings = filterMappings; } } mina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/Binding.java0000644000175000017500000001226411002320013032522 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.net.SocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceConfig; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * Defines an address to {@link IoHandler} binding. * This is used when specifying the addresses to accept new connections on when * creating {@link org.apache.mina.common.IoAcceptor} objects using * {@link IoAcceptorFactoryBean}. *

* Note that the address property is of {@link java.net.SocketAddress} * type. Use {@link InetSocketAddressEditor} or {@link VmPipeAddressEditor} in * your Spring configuration file to simply the creation of * {@link java.net.SocketAddress} instances using Spring. *

*

* This class also allows for an optional service configuration using * {@link #setServiceConfig(IoServiceConfig)} to be specified. If the binding * specifies an {@link IoServiceConfig} {@link IoAcceptorFactoryBean} will * use {@link IoAcceptor#bind(SocketAddress, IoHandler, IoServiceConfig)} instead * of {@link IoAcceptor#bind(SocketAddress, IoHandler)} when binding. The * {@link IoServiceConfig} object lets you specify transport specific * confiuration options and define port specific filters. This makes it possible * to specify different filters depending on the port the client is connecting * on (e.g. using an {@link org.apache.mina.filter.SSLFilter} when connecting * on port 443 but not on port 80). *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Binding implements InitializingBean { private SocketAddress address = null; private IoHandler handler = null; private IoServiceConfig serviceConfig = null; /** * Creates a new empty instance. */ public Binding() { } /** * Creates a new instance using the specified values. * * @param address the address. * @param handler the handler. * @throws IllegalArgumentException if the any of the specified values are * null. */ public Binding(SocketAddress address, IoHandler handler) { setAddress(address); setHandler(handler); } /** * Creates a new instance using the specified values. * * @param address the address. * @param handler the handler. * @param serviceConfig the service configuration. * @throws IllegalArgumentException if the any of the specified values are * null. */ public Binding(SocketAddress address, IoHandler handler, IoServiceConfig serviceConfig) { setAddress(address); setHandler(handler); setServiceConfig(serviceConfig); } /** * Returns the address the handler of this object will be bound to. * * @return the address. */ public SocketAddress getAddress() { return address; } /** * Sets the address the handler of this object will be bound to. * * @param address the address. * @throws IllegalArgumentException if the specified value is * null. */ public void setAddress(SocketAddress address) { Assert.notNull(address, "Property 'address' may not be null"); this.address = address; } /** * Returns the handler of this binding object. * * @return the handler. */ public IoHandler getHandler() { return handler; } /** * Sets the handler of this binding object. * * @param handler the handler. * @throws IllegalArgumentException if the specified value is * null. */ public void setHandler(IoHandler handler) { Assert.notNull(handler, "Property 'handler' may not be null"); this.handler = handler; } public IoServiceConfig getServiceConfig() { return serviceConfig; } public void setServiceConfig(IoServiceConfig serviceConfig) { this.serviceConfig = serviceConfig; } public void afterPropertiesSet() throws Exception { Assert.notNull(address, "Property 'address' may not be null"); Assert.notNull(handler, "Property 'handler' may not be null"); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/IoFilterMapping.javamina-1.1.7.dfsg/integration-spring/src/main/java/org/apache/mina/integration/spring/IoFilterMapping.0000644000175000017500000001010311002320013033325 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import org.apache.mina.common.IoFilter; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * Associates a name with an {@link IoFilter}. This makes it possible to configure * named filters using Spring. *

* Use this class when you want to configure the * filters added to the filter chain of all sessions created from a particular * {@link org.apache.mina.common.IoService} created using one of the * {@link org.apache.mina.integration.spring.IoAcceptorFactoryBean} * sub-classes but you don't want the names to be generated automatically. *

*

* This class can also be used when creating {@link Binding} objects. This lets * one configure per-port filters. These filters will only be added to the * filter chain of sessions for incoming connections on the port specified by * the {@link Binding}. Note that {@link Binding} can also be configured to * generate filter names automatically. In that case you add the {@link IoFilter} * instances directly to the {@link Binding}. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ * * @see org.apache.mina.integration.spring.IoAcceptorFactoryBean * @see org.apache.mina.integration.spring.Binding */ public class IoFilterMapping implements InitializingBean { private String name = null; private IoFilter filter = null; /** * Creates a new empty instance. */ public IoFilterMapping() { } /** * Creates a new instance using the specified name and filter. * * @param name the name. * @param filter the filter. * @throws IllegalArgumentException if any of the arguments are * null. */ public IoFilterMapping(String name, IoFilter filter) { Assert.notNull(name, "Argument 'name' may not be null"); Assert.notNull(filter, "Argument 'filter' may not be null"); this.name = name; this.filter = filter; } /** * Returns the filter of this mapping. * * @return the filter. */ public IoFilter getFilter() { return filter; } /** * Returns the name associated with the filter. * * @return the name. */ public String getName() { return name; } /** * Sets the filter of this mapping. * * @param filter the filter. * @throws IllegalArgumentException if the specified value is * null. */ public void setFilter(IoFilter filter) { Assert.notNull(filter, "Argument 'filter' may not be null"); this.filter = filter; } /** * Sets the name associated with the filter. * * @param name the name. * @throws IllegalArgumentException if the specified value is * null. */ public void setName(String name) { Assert.notNull(name, "Argument 'name' may not be null"); this.name = name; } public void afterPropertiesSet() throws Exception { Assert.notNull(name, "Argument 'name' may not be null"); Assert.notNull(filter, "Argument 'filter' may not be null"); } } mina-1.1.7.dfsg/integration-spring/src/test/0000755000175000017500000000000011002320012020630 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/0000755000175000017500000000000011002320012022642 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/org/0000755000175000017500000000000011002320012023431 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/0000755000175000017500000000000011002320012024652 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/mina/0000755000175000017500000000000011002320012025576 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/mina/integration/0000755000175000017500000000000011002320012030121 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/mina/integration/spring/0000755000175000017500000000000011002320012031423 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/mina/integration/spring/ssl/0000755000175000017500000000000011044712500032241 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/mina/integration/spring/ssl/keystore.certmina-1.1.7.dfsg/integration-spring/src/test/resources/org/apache/mina/integration/spring/ssl/keystor0000644000175000017500000000165111002320012033652 0ustar drazzibdrazzibbogus}Ė00 +*|a-##A֧o".FRy ֔Їf`BKZMiPо˖(-SXH:"3|'%Ne\5 IK82EW sa!F[ˈy (Ahic9+|&D[)O7؏D!ݥ ߰1ÛaE8DNc˸ꇖ(؄N v}Ѐq1YbiYAJkjK9TNe\0ܘ-R'X.50900rB,pS0  *H 0n1 0 USE10U Stockholm10U Stockholm10U  Bogus Inc10 U XXX CA10U bogus.com0 050307151635Z 150305151635Z0n1 0 USE10U Stockholm10U Stockholm10U  Bogus Inc10 U XXX CA10U bogus.com0[0  *H J0G@Z & |+mJ;X|jv>JHmK'6LAx3i o0  *H AI@Ba?>2n(9OdmiJE 5 @y |[:k#Ŧ];e8mina-1.1.7.dfsg/integration-spring/src/test/java/0000755000175000017500000000000011002320012021551 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/java/org/0000755000175000017500000000000011002320012022340 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/0000755000175000017500000000000011002320012023561 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/0000755000175000017500000000000011002320012024505 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/0000755000175000017500000000000011002320012027030 5ustar drazzibdrazzibmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/0000755000175000017500000000000011044712500030347 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/DefaultIoFilterChainBuilderFactoryBeanTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/DefaultIoFilterC0000644000175000017500000000761511002320012033413 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.util.Arrays; import java.util.LinkedList; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterChain; import org.easymock.MockControl; import junit.framework.TestCase; /** * Tests {@link DefaultIoFilterChainBuilderFactoryBean}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class DefaultIoFilterChainBuilderFactoryBeanTest extends TestCase { MockControl mockChain; IoFilterChain chain; IoFilter[] filters; protected void setUp() throws Exception { super.setUp(); mockChain = MockControl.createControl(IoFilterChain.class); chain = (IoFilterChain) mockChain.getMock(); filters = new IoFilter[] { (IoFilter) MockControl.createControl(IoFilter.class).getMock(), (IoFilter) MockControl.createControl(IoFilter.class).getMock(), (IoFilter) MockControl.createControl(IoFilter.class).getMock() }; } public void testUnnamedFilters() throws Exception { chain.addLast("prefix0", filters[0]); chain.addLast("prefix1", filters[1]); chain.addLast("prefix2", filters[2]); mockChain.replay(); DefaultIoFilterChainBuilderFactoryBean factory = new DefaultIoFilterChainBuilderFactoryBean(); factory.setFilters(Arrays.asList(filters)); factory.setFilterNamePrefix("prefix"); DefaultIoFilterChainBuilder builder = (DefaultIoFilterChainBuilder) factory .createInstance(); builder.buildFilterChain(chain); mockChain.verify(); } @SuppressWarnings("unchecked") public void testIllegalObjectsInFilterList() throws Exception { LinkedList mappings = new LinkedList(); mappings.add(new IoFilterMapping("f0", filters[0])); mappings.add(new Object()); DefaultIoFilterChainBuilderFactoryBean factory = new DefaultIoFilterChainBuilderFactoryBean(); try { factory.setFilters(mappings); fail("Illegal object in list of filters. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } } @SuppressWarnings("unchecked") public void testNamedAndUnnamedFilters() throws Exception { LinkedList mappings = new LinkedList(); mappings.add(new IoFilterMapping("f0", filters[0])); mappings.add(filters[1]); mappings.add(new IoFilterMapping("f2", filters[2])); chain.addLast("f0", filters[0]); chain.addLast("filter1", filters[1]); chain.addLast("f2", filters[2]); mockChain.replay(); DefaultIoFilterChainBuilderFactoryBean factory = new DefaultIoFilterChainBuilderFactoryBean(); factory.setFilters(mappings); DefaultIoFilterChainBuilder builder = (DefaultIoFilterChainBuilder) factory .createInstance(); builder.buildFilterChain(chain); mockChain.verify(); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/IoAcceptorFactoryBeanTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/IoAcceptorFactor0000644000175000017500000000731211002320012033447 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.net.InetSocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoServiceConfig; import org.easymock.MockControl; import junit.framework.TestCase; /** * Tests {@link IoAcceptorFactoryBean}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoAcceptorFactoryBeanTest extends TestCase { public void testBindUnbind() throws Exception { IoHandler handler1 = new IoHandlerAdapter(); IoHandler handler2 = new IoHandlerAdapter(); IoHandler handler3 = new IoHandlerAdapter(); IoServiceConfig config1 = (IoServiceConfig) MockControl.createControl( IoServiceConfig.class).getMock(); IoServiceConfig config2 = (IoServiceConfig) MockControl.createControl( IoServiceConfig.class).getMock(); MockControl mockIoAcceptor = MockControl .createControl(IoAcceptor.class); IoAcceptor acceptor = (IoAcceptor) mockIoAcceptor.getMock(); acceptor.bind(new InetSocketAddress(80), handler1, config1); acceptor.bind(new InetSocketAddress("192.168.0.1", 22), handler2, config2); acceptor.bind(new InetSocketAddress("10.0.0.1", 9876), handler3); acceptor.unbind(new InetSocketAddress(80)); acceptor.unbind(new InetSocketAddress("192.168.0.1", 22)); acceptor.unbind(new InetSocketAddress("10.0.0.1", 9876)); mockIoAcceptor.replay(); IoAcceptorFactoryBean factory = new IoAcceptorFactoryBean(); factory.setTarget(acceptor); factory .setBindings(new Binding[] { new Binding(new InetSocketAddress(80), handler1, config1), new Binding(new InetSocketAddress("192.168.0.1", 22), handler2, config2), new Binding(new InetSocketAddress("10.0.0.1", 9876), handler3) }); factory.afterPropertiesSet(); factory.destroy(); mockIoAcceptor.verify(); } public void testIsSingleton() throws Exception { assertTrue(new IoAcceptorFactoryBean().isSingleton()); } public void testGetObjectType() throws Exception { assertEquals(IoAcceptor.class, new IoAcceptorFactoryBean() .getObjectType()); } public void testGetObject() throws Exception { IoAcceptor acceptor = (IoAcceptor) MockControl.createControl( IoAcceptor.class).getMock(); IoAcceptorFactoryBean factory = new IoAcceptorFactoryBean(); factory.setTarget(acceptor); assertEquals(acceptor, factory.getObject()); } } mina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/ssl/0000755000175000017500000000000011044712500031150 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/ssl/KeyStoreFactoryBeanTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/ssl/KeyStoreFact0000644000175000017500000000517611002320012033432 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring.ssl; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.KeyStore; import junit.framework.TestCase; import org.springframework.core.io.ClassPathResource; /** * Tests {@link org.apache.mina.integration.spring.ssl.KeyStoreFactoryBean}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class KeyStoreFactoryBeanTest extends TestCase { public void testCreateInstanceFromResource() throws Exception { // Test using default for now. KeyStoreFactoryBean factory = new KeyStoreFactoryBean(); factory.setResource(new ClassPathResource("keystore.cert", getClass())); factory.setPassword("boguspw"); KeyStore ks = (KeyStore) factory.createInstance(); ks.getCertificate("bogus"); ks.getKey("bogus", "boguspw".toCharArray()); } public void testCreateInstanceFromFile() throws Exception { // Copy the keystore from the class path to a temporary file. File file = File.createTempFile("keystoretest ", null); file.deleteOnExit(); InputStream in = getClass().getResourceAsStream("keystore.cert"); OutputStream out = new FileOutputStream(file); int b; while ((b = in.read()) != -1) { out.write(b); } in.close(); out.close(); // Test using default for now. KeyStoreFactoryBean factory = new KeyStoreFactoryBean(); factory.setFile(file); factory.setPassword("boguspw"); KeyStore ks = (KeyStore) factory.createInstance(); ks.getCertificate("bogus"); ks.getKey("bogus", "boguspw".toCharArray()); } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/ExecutorThreadModelFactoryBeanTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/ExecutorThreadMo0000644000175000017500000000521311002320012033500 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import junit.framework.TestCase; import org.apache.mina.common.ExecutorThreadModel; import java.util.concurrent.Executor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Tests {@link ExecutorThreadModelFactoryBean}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class ExecutorThreadModelFactoryBeanTest extends TestCase { public void testSuccessfulCreationWithExecutor() throws Exception { Executor executor = new ThreadPoolExecutor(1, 10, 3600, TimeUnit.SECONDS, new SynchronousQueue()); ExecutorThreadModelFactoryBean factory = new ExecutorThreadModelFactoryBean(); factory.setServiceName("foo"); factory.setExecutor(executor); factory.afterPropertiesSet(); ExecutorThreadModel threadModel = (ExecutorThreadModel) factory .getObject(); assertSame(executor, threadModel.getExecutor()); } public void testSuccessfulCreationWithoutExecutor() throws Exception { ExecutorThreadModelFactoryBean factory = new ExecutorThreadModelFactoryBean(); factory.setServiceName("foo"); factory.afterPropertiesSet(); ExecutorThreadModel threadModel = (ExecutorThreadModel) factory .getObject(); assertTrue(threadModel.getExecutor() instanceof ThreadPoolExecutor); } public void testUnsuccessfulCreation() throws Exception { ExecutorThreadModelFactoryBean factory = new ExecutorThreadModelFactoryBean(); try { factory.afterPropertiesSet(); fail("No serviceName set. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/InetSocketAddressEditorTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/InetSocketAddres0000644000175000017500000000552211002320012033454 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.net.InetSocketAddress; import junit.framework.TestCase; /** * Tests {@link InetSocketAddressEditor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class InetSocketAddressEditorTest extends TestCase { InetSocketAddressEditor editor; protected void setUp() throws Exception { editor = new InetSocketAddressEditor(); } public void testSetAsTextWithWildcardAddress() throws Exception { editor.setAsText("1"); assertEquals(new InetSocketAddress(1), editor.getValue()); editor.setAsText(":10"); assertEquals(new InetSocketAddress(10), editor.getValue()); } public void testSetAsTextWithHostName() throws Exception { editor.setAsText("www.google.com:80"); assertEquals(new InetSocketAddress("www.google.com", 80), editor .getValue()); } public void testSetAsTextWithIpAddress() throws Exception { editor.setAsText("192.168.0.1:1000"); assertEquals(new InetSocketAddress("192.168.0.1", 1000), editor .getValue()); } public void testSetAsTextWithIllegalValues() throws Exception { try { editor.setAsText(null); fail("null string. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { editor.setAsText("bar"); fail("Illegal port number. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { editor.setAsText(":foo"); fail("Illegal port number. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { editor.setAsText("www.foo.com:yada"); fail("Illegal port number. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/InetAddressEditorTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/InetAddressEdito0000644000175000017500000000401111002320012033443 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import java.net.InetAddress; import java.net.UnknownHostException; import junit.framework.TestCase; /** * Tests {@link org.apache.mina.integration.spring.InetAddressEditor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class InetAddressEditorTest extends TestCase { InetAddressEditor editor; protected void setUp() throws Exception { editor = new InetAddressEditor(); } public void testSetAsTextWithHostName() throws Exception { try { InetAddress expected = InetAddress.getByName("www.google.com"); editor.setAsText("www.google.com"); assertEquals(expected, editor.getValue()); } catch (UnknownHostException uhe) { // No DNS. Skip the test. } editor.setAsText("localhost"); assertEquals(InetAddress.getByName("localhost"), editor.getValue()); } public void testSetAsTextWithIpAddress() throws Exception { editor.setAsText("127.0.0.1"); assertEquals(InetAddress.getByName("127.0.0.1"), editor.getValue()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/IoFilterMappingTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/IoFilterMappingT0000644000175000017500000000370311002320012033435 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import junit.framework.TestCase; import org.apache.mina.common.IoFilter; import org.easymock.MockControl; /** * Tests {@link org.apache.mina.integration.spring.IoFilterMapping}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class IoFilterMappingTest extends TestCase { public void testConstructor() throws Exception { IoFilter filter = (IoFilter) MockControl.createControl(IoFilter.class) .getMock(); try { new IoFilterMapping(null, filter); fail("null name. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { new IoFilterMapping("name", null); fail("null filter. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } IoFilterMapping mapping = new IoFilterMapping("name", filter); assertEquals("name", mapping.getName()); assertSame(filter, mapping.getFilter()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootmina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/VmPipeAddressEditorTest.javamina-1.1.7.dfsg/integration-spring/src/test/java/org/apache/mina/integration/spring/VmPipeAddressEdi0000644000175000017500000000445611002320012033416 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.integration.spring; import junit.framework.TestCase; import org.apache.mina.transport.vmpipe.VmPipeAddress; /** * Tests {@link VmPipeAddressEditor}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class VmPipeAddressEditorTest extends TestCase { VmPipeAddressEditor editor; protected void setUp() throws Exception { editor = new VmPipeAddressEditor(); } public void testSetAsTextWithLegalValues() throws Exception { editor.setAsText("1"); assertEquals(new VmPipeAddress(1), editor.getValue()); editor.setAsText(":10"); assertEquals(new VmPipeAddress(10), editor.getValue()); editor.setAsText(":100"); assertEquals(new VmPipeAddress(100), editor.getValue()); } public void testSetAsTextWithIllegalValues() throws Exception { try { editor.setAsText(null); fail("null string. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { editor.setAsText("bar"); fail("Illegal port number. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } try { editor.setAsText(":foo"); fail("Illegal port number. IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } } } mina-1.1.7.dfsg/filter-codec-netty/0000755000175000017500000000000011044712500016755 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/pom.xml0000644000175000017500000000213611002320012020257 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-filter-codec-netty Apache MINA Netty Codec Filter jar net.gleamynode netty2 1.9.2 compile org.apache.mina mina-core ${pom.version} compile org.slf4j slf4j-simple 1.4.3 test mina-1.1.7.dfsg/filter-codec-netty/src/0000755000175000017500000000000011002320012017527 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/0000755000175000017500000000000011002320012020453 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/resources/0000755000175000017500000000000011002320012022465 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/resources/META-INF/0000755000175000017500000000000011044712500023642 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320012026562 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/filter-codec-netty/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320012025461 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/filter-codec-netty/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320012026502 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/filter-codec-netty/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320012025353 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/filter-codec-netty/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320012030700 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/filter-codec-netty/src/main/java/0000755000175000017500000000000011002320012021374 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/META-INF/0000755000175000017500000000000011044712500022551 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/META-INF/MANIFEST.MF0000644000175000017500000000004711002320012024167 0ustar drazzibdrazzibManifest-Version: 1.0 Class-Path: mina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/0000755000175000017500000000000011002320012022163 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/0000755000175000017500000000000011002320012023404 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/0000755000175000017500000000000011002320012024330 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/0000755000175000017500000000000011002320012025615 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/0000755000175000017500000000000011002320012026672 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/0000755000175000017500000000000011044712500030052 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/package.html0000644000175000017500000000034111002320012032314 0ustar drazzibdrazzib Protocol codec which provides the integration with Netty2 messages. ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/NettyEncoder.javamina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/NettyEncoder.jav0000644000175000017500000000453211002320012033146 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.netty; import net.gleamynode.netty2.Message; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderException; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /** * A MINA ProtocolEncoder that encodes Netty2 {@link Message}s * into byte buffers. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class NettyEncoder implements ProtocolEncoder { /** * Creates a new instance. */ public NettyEncoder() { } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { if (!(message instanceof Message)) { throw new ProtocolEncoderException( "This encoder can decode only Netty Messages."); } for (;;) { ByteBuffer buf = ByteBuffer.allocate(8192); Message m = (Message) message; try { if (m.write(buf.buf())) { break; } } finally { buf.flip(); if (buf.hasRemaining()) { out.write(buf); } else { buf.release(); } } } } public void dispose(IoSession session) throws Exception { } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/NettyCodecFactory.javamina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/NettyCodecFactor0000644000175000017500000000376211002320012033170 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.netty; import net.gleamynode.netty2.Message; import net.gleamynode.netty2.MessageRecognizer; import org.apache.mina.filter.codec.ProtocolCodecFactory; /** * A MINA ProtocolCodecFactory that provides encoder and decoder * for Netty2 {@link Message}s and {@link MessageRecognizer}s. *

* Please note that this codec factory assumes one {@link MessageRecognizer} * can be used for multiple sessions. If not, you'll have to create your * own factory after this factory. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class NettyCodecFactory implements ProtocolCodecFactory { private static final NettyEncoder ENCODER = new NettyEncoder(); private final MessageRecognizer recognizer; public NettyCodecFactory(MessageRecognizer recognizer) { this.recognizer = recognizer; } public org.apache.mina.filter.codec.ProtocolEncoder getEncoder() { return ENCODER; } public org.apache.mina.filter.codec.ProtocolDecoder getDecoder() { return new NettyDecoder(recognizer); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootmina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/NettyDecoder.javamina-1.1.7.dfsg/filter-codec-netty/src/main/java/org/apache/mina/filter/codec/netty/NettyDecoder.jav0000644000175000017500000001111011002320012033122 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.netty; import net.gleamynode.netty2.Message; import net.gleamynode.netty2.MessageParseException; import net.gleamynode.netty2.MessageRecognizer; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderAdapter; import org.apache.mina.filter.codec.ProtocolDecoderException; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * A MINA {@link ProtocolDecoder} that decodes byte buffers into * Netty2 {@link Message}s using specified {@link MessageRecognizer}s. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class NettyDecoder extends ProtocolDecoderAdapter { private final MessageRecognizer recognizer; private java.nio.ByteBuffer readBuf = java.nio.ByteBuffer.allocate(1024); private Message readingMessage; /** * Creates a new instance with the specified {@link MessageRecognizer}. */ public NettyDecoder(MessageRecognizer recognizer) { if (recognizer == null) throw new NullPointerException(); this.recognizer = recognizer; } private void put(ByteBuffer in) { // copy to read buffer if (in.remaining() > readBuf.remaining()) expand((readBuf.position() + in.remaining()) * 3 / 2); readBuf.put(in.buf()); } private void expand(int newCapacity) { java.nio.ByteBuffer newBuf = java.nio.ByteBuffer.allocate(newCapacity); readBuf.flip(); newBuf.put(readBuf); readBuf = newBuf; } public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { put(in); Message m = readingMessage; try { for (;;) { readBuf.flip(); if (m == null) { int limit = readBuf.limit(); boolean failed = true; try { m = recognizer.recognize(readBuf); failed = false; } finally { if (failed) { // clear the read buffer if failed to recognize readBuf.clear(); break; } else { if (m == null) { readBuf.limit(readBuf.capacity()); readBuf.position(limit); break; // finish decoding } else { // reset buffer for read readBuf.limit(limit); readBuf.position(0); } } } } if (m != null) { try { if (m.read(readBuf)) { out.write(m); m = null; } else { break; } } finally { if (readBuf.hasRemaining()) { readBuf.compact(); } else { readBuf.clear(); break; } } } } } catch (MessageParseException e) { m = null; // discard reading message throw new ProtocolDecoderException("Failed to decode.", e); } finally { readingMessage = m; } } } mina-1.1.7.dfsg/filter-codec-netty/src/test/0000755000175000017500000000000011002320012020506 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-codec-netty/src/test/java/0000755000175000017500000000000011002320012021427 5ustar drazzibdrazzibmina-1.1.7.dfsg/NOTICE.txt0000644000175000017500000000151711002320032014767 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/filter-compression/0000755000175000017500000000000011044712500017100 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/LICENSE.jzlib.txt0000644000175000017500000000316111002320014022022 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/filter-compression/pom.xml0000644000175000017500000000241711002320014020406 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-filter-compression Apache MINA Stream Compression Filter jar org.apache.mina mina-core ${pom.version} compile org.slf4j slf4j-simple 1.4.3 test easymock easymock 1.2_Java1.3 test com.jcraft jzlib 1.0.7 compile mina-1.1.7.dfsg/filter-compression/src/0000755000175000017500000000000011002320014017654 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/0000755000175000017500000000000011002320014020600 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/resources/0000755000175000017500000000000011002320014022612 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/resources/META-INF/0000755000175000017500000000000011044712500023765 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320014026707 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/filter-compression/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320014025606 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/filter-compression/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320014026627 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/filter-compression/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320014025500 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/filter-compression/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320014031025 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/filter-compression/src/main/java/0000755000175000017500000000000011002320014021521 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/java/org/0000755000175000017500000000000011002320014022310 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/java/org/apache/0000755000175000017500000000000011002320014023531 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/java/org/apache/mina/0000755000175000017500000000000011002320014024455 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/java/org/apache/mina/filter/0000755000175000017500000000000011044712500025755 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/java/org/apache/mina/filter/support/0000755000175000017500000000000011044712500027471 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/main/java/org/apache/mina/filter/support/Zlib.java0000644000175000017500000001611211002320014031222 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.support; import java.io.IOException; import org.apache.mina.common.ByteBuffer; import com.jcraft.jzlib.JZlib; import com.jcraft.jzlib.ZStream; /** * A helper class for interfacing with the JZlib library. This class acts both * as a compressor and decompressor, but only as one at a time. The only * flush method supported is Z_SYNC_FLUSH also known as Z_PARTIAL_FLUSH * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 629330 $, $Date: 2008-02-20 12:18:28 +0900 (Wed, 20 Feb 2008) $ */ public class Zlib { public static final int COMPRESSION_MAX = JZlib.Z_BEST_COMPRESSION; public static final int COMPRESSION_MIN = JZlib.Z_BEST_SPEED; public static final int COMPRESSION_NONE = JZlib.Z_NO_COMPRESSION; public static final int COMPRESSION_DEFAULT = JZlib.Z_DEFAULT_COMPRESSION; public static final int MODE_DEFLATER = 1; public static final int MODE_INFLATER = 2; private int compressionLevel; private ZStream zStream = null; private int mode = -1; /** * @param compressionLevel the level of compression that should be used * @param mode the mode in which the instance will operate. Can be either * of MODE_DEFLATER or MODE_INFLATER */ public Zlib(int compressionLevel, int mode) { switch (compressionLevel) { case COMPRESSION_MAX: case COMPRESSION_MIN: case COMPRESSION_NONE: case COMPRESSION_DEFAULT: this.compressionLevel = compressionLevel; break; default: throw new IllegalArgumentException( "invalid compression level specified"); } // create a new instance of ZStream. This will be done only once. zStream = new ZStream(); switch (mode) { case MODE_DEFLATER: zStream.deflateInit(this.compressionLevel); break; case MODE_INFLATER: zStream.inflateInit(); break; default: throw new IllegalArgumentException("invalid mode specified"); } this.mode = mode; } /** * @param inBuffer the {@link ByteBuffer} to be decompressed. The contents * of the buffer are transferred into a local byte array and the buffer is * flipped and returned intact. * @return the decompressed data. If not passed to the MINA methods that * release the buffer automatically, the buffer has to be manually released * @throws IOException if the decompression of the data failed for some reason. */ public ByteBuffer inflate(ByteBuffer inBuffer) throws IOException { if (mode == MODE_DEFLATER) { throw new IllegalStateException("not initialized as INFLATER"); } byte[] inBytes = new byte[inBuffer.remaining()]; inBuffer.get(inBytes).flip(); // We could probably do this better, if we're willing to return multiple buffers // (e.g. with a callback function) byte[] outBytes = new byte[inBytes.length * 2]; ByteBuffer outBuffer = ByteBuffer.allocate(outBytes.length); outBuffer.setAutoExpand(true); zStream.next_in = inBytes; zStream.next_in_index = 0; zStream.avail_in = inBytes.length; zStream.next_out = outBytes; zStream.next_out_index = 0; zStream.avail_out = outBytes.length; int retval = 0; do { retval = zStream.inflate(JZlib.Z_SYNC_FLUSH); switch (retval) { case JZlib.Z_OK: // completed decompression, lets copy data and get out case JZlib.Z_BUF_ERROR: // need more space for output. store current output and get more outBuffer.put(outBytes, 0, zStream.next_out_index); zStream.next_out_index = 0; zStream.avail_out = outBytes.length; break; default: // unknown error outBuffer.release(); outBuffer = null; if (zStream.msg == null) throw new IOException("Unknown error. Error code : " + retval); else throw new IOException("Unknown error. Error code : " + retval + " and message : " + zStream.msg); } } while (zStream.avail_in > 0); return outBuffer.flip(); } /** * @param inBuffer the buffer to be compressed. The contents are transferred * into a local byte array and the buffer is flipped and returned intact. * @return the buffer with the compressed data. If not passed to any of the * MINA methods that automatically release the buffer, the buffer has to be * released manually. * @throws IOException if the compression of teh buffer failed for some reason */ public ByteBuffer deflate(ByteBuffer inBuffer) throws IOException { if (mode == MODE_INFLATER) { throw new IllegalStateException("not initialized as DEFLATER"); } byte[] inBytes = new byte[inBuffer.remaining()]; inBuffer.get(inBytes).flip(); // according to spec, destination buffer should be 0.1% larger // than source length plus 12 bytes. We add a single byte to safeguard // against rounds that round down to the smaller value int outLen = (int) Math.round(inBytes.length * 1.001) + 1 + 12; byte[] outBytes = new byte[outLen]; zStream.next_in = inBytes; zStream.next_in_index = 0; zStream.avail_in = inBytes.length; zStream.next_out = outBytes; zStream.next_out_index = 0; zStream.avail_out = outBytes.length; int retval = zStream.deflate(JZlib.Z_SYNC_FLUSH); if (retval != JZlib.Z_OK) { outBytes = null; inBytes = null; throw new IOException("Compression failed with return value : " + retval); } ByteBuffer outBuf = ByteBuffer .wrap(outBytes, 0, zStream.next_out_index); return outBuf; } /** * Cleans up the resources used by the compression library. */ public void cleanUp() { if (zStream != null) zStream.free(); } } mina-1.1.7.dfsg/filter-compression/src/main/java/org/apache/mina/filter/CompressionFilter.java0000644000175000017500000002252611002320014032263 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import java.io.IOException; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.filter.support.Zlib; /** * An {@link IoFilter} which compresses all data using * JZlib. * Support for the LZW (DLCZ) algorithm is also planned. *

* This filter only supports compression using the PARTIAL FLUSH method, * since that is the only method useful when doing stream level compression. *

* This filter supports compression/decompression of the input and output * channels selectively. It can also be enabled/disabled on the fly. *

* This filter does not discard the zlib objects, keeping them around for the * entire life of the filter. This is because the zlib dictionary needs to * be built up over time, which is used during compression and decompression. * Over time, as repetitive data is sent over the wire, the compression efficiency * steadily increases. *

* Note that the zlib header is written only once. It is not necessary that * the data received after processing by this filter may not be complete due * to packet fragmentation. *

* It goes without saying that the other end of this stream should also have a * compatible compressor/decompressor using the same algorithm. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 629330 $, $Date: 2008-02-20 12:18:28 +0900 (Wed, 20 Feb 2008) $ */ public class CompressionFilter extends IoFilterAdapter { /** * Max compression level. Will give the highest compression ratio, but * will also take more cpu time and is the slowest. */ public static final int COMPRESSION_MAX = Zlib.COMPRESSION_MAX; /** * Provides the best speed at the price of a low compression ratio. */ public static final int COMPRESSION_MIN = Zlib.COMPRESSION_MIN; /** * No compression done on the data. */ public static final int COMPRESSION_NONE = Zlib.COMPRESSION_NONE; /** * The default compression level used. Provides the best balance * between speed and compression */ public static final int COMPRESSION_DEFAULT = Zlib.COMPRESSION_DEFAULT; /** * A session attribute that stores the {@link Zlib} object used for compression. */ private static final String DEFLATER = CompressionFilter.class.getName() + ".Deflater"; /** * A session attribute that stores the {@link Zlib} object used for decompression. */ private static final String INFLATER = CompressionFilter.class.getName() + ".Inflater"; /** * A flag that allows you to disable compression once. */ public static final String DISABLE_COMPRESSION_ONCE = CompressionFilter.class .getName() + ".DisableCompressionOnce"; private boolean compressInbound = true; private boolean compressOutbound = true; private int compressionLevel; /** * Creates a new instance which compresses outboud data and decompresses * inbound data with default compression level. */ public CompressionFilter() { this(true, true, COMPRESSION_DEFAULT); } /** * Creates a new instance which compresses outboud data and decompresses * inbound data with the specified compressionLevel. * * @param compressionLevel the level of compression to be used. Must * be one of {@link #COMPRESSION_DEFAULT}, * {@link #COMPRESSION_MAX}, * {@link #COMPRESSION_MIN}, and * {@link #COMPRESSION_NONE}. */ public CompressionFilter(final int compressionLevel) { this(true, true, compressionLevel); } /** * Creates a new instance. * * @param compressInbound true if data read is to be decompressed * @param compressOutbound true if data written is to be compressed * @param compressionLevel the level of compression to be used. Must * be one of {@link #COMPRESSION_DEFAULT}, * {@link #COMPRESSION_MAX}, * {@link #COMPRESSION_MIN}, and * {@link #COMPRESSION_NONE}. */ public CompressionFilter(final boolean compressInbound, final boolean compressOutbound, final int compressionLevel) { this.compressionLevel = compressionLevel; this.compressInbound = compressInbound; this.compressOutbound = compressOutbound; } public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (!compressInbound || !(message instanceof ByteBuffer)) { nextFilter.messageReceived(session, message); return; } Zlib inflater = (Zlib) session.getAttribute(INFLATER); if (inflater == null) { throw new IllegalStateException(); } ByteBuffer inBuffer = (ByteBuffer) message; ByteBuffer outBuffer = inflater.inflate(inBuffer); inBuffer.release(); nextFilter.messageReceived(session, outBuffer); } /* * @see org.apache.mina.common.IoFilter#filterWrite(org.apache.mina.common.IoFilter.NextFilter, org.apache.mina.common.IoSession, org.apache.mina.common.IoFilter.WriteRequest) */ public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws IOException { if (!compressOutbound) { nextFilter.filterWrite(session, writeRequest); return; } if (session.containsAttribute(DISABLE_COMPRESSION_ONCE)) { // Remove the marker attribute because it is temporary. session.removeAttribute(DISABLE_COMPRESSION_ONCE); nextFilter.filterWrite(session, writeRequest); return; } Zlib deflater = (Zlib) session.getAttribute(DEFLATER); if (deflater == null) { throw new IllegalStateException(); } ByteBuffer inBuffer = (ByteBuffer) writeRequest.getMessage(); if (!inBuffer.hasRemaining()) { // Ignore empty buffers nextFilter.filterWrite(session, writeRequest); } else { ByteBuffer outBuf = deflater.deflate(inBuffer); inBuffer.release(); nextFilter.filterWrite(session, new WriteRequest(outBuf, writeRequest.getFuture())); } } public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { if (parent.contains(CompressionFilter.class)) { throw new IllegalStateException( "A filter chain cannot contain more than" + " one Stream Compression filter."); } Zlib deflater = new Zlib(compressionLevel, Zlib.MODE_DEFLATER); Zlib inflater = new Zlib(compressionLevel, Zlib.MODE_INFLATER); IoSession session = parent.getSession(); session.setAttribute(DEFLATER, deflater); session.setAttribute(INFLATER, inflater); } /** * Returns true if incoming data is being compressed. */ public boolean isCompressInbound() { return compressInbound; } /** * Sets if incoming data has to be compressed. */ public void setCompressInbound(boolean compressInbound) { this.compressInbound = compressInbound; } /** * Returns true if the filter is compressing data being written. */ public boolean isCompressOutbound() { return compressOutbound; } /** * Set if outgoing data has to be compressed. */ public void setCompressOutbound(boolean compressOutbound) { this.compressOutbound = compressOutbound; } public void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { super.onPostRemove(parent, name, nextFilter); IoSession session = parent.getSession(); if (session == null) { return; } Zlib inflater = (Zlib) session.getAttribute(INFLATER); Zlib deflater = (Zlib) session.getAttribute(DEFLATER); if (deflater != null) { deflater.cleanUp(); } if (inflater != null) { inflater.cleanUp(); } } } mina-1.1.7.dfsg/filter-compression/src/test/0000755000175000017500000000000011002320014020633 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/0000755000175000017500000000000011002320014021554 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/org/0000755000175000017500000000000011002320014022343 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/org/apache/0000755000175000017500000000000011002320014023564 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/org/apache/mina/0000755000175000017500000000000011002320014024510 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/org/apache/mina/filter/0000755000175000017500000000000011044712500026010 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/org/apache/mina/filter/support/0000755000175000017500000000000011044712500027524 5ustar drazzibdrazzibmina-1.1.7.dfsg/filter-compression/src/test/java/org/apache/mina/filter/support/ZlibTest.java0000644000175000017500000001136111002320014032116 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.support; import java.io.IOException; import java.nio.charset.Charset; import org.apache.mina.common.ByteBuffer; import junit.framework.TestCase; /** * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ZlibTest extends TestCase { private Zlib deflater = null; private Zlib inflater = null; protected void setUp() throws Exception { deflater = new Zlib(Zlib.COMPRESSION_MAX, Zlib.MODE_DEFLATER); inflater = new Zlib(Zlib.COMPRESSION_MAX, Zlib.MODE_INFLATER); } public void testCompression() throws Exception { String strInput = ""; // increase the count to as many as required to generate a long // string for input for (int i = 0; i < 10; i++) { strInput += "The quick brown fox jumps over the lazy dog. "; } ByteBuffer byteInput = ByteBuffer.wrap(strInput.getBytes("UTF8")); // increase the count to have the compression and decompression // done using the same instance of Zlib for (int i = 0; i < 5; i++) { ByteBuffer byteCompressed = deflater.deflate(byteInput); ByteBuffer byteUncompressed = inflater.inflate(byteCompressed); String strOutput = byteUncompressed.getString(Charset.forName( "UTF8").newDecoder()); assertTrue(strOutput.equals(strInput)); } } public void testCorruptedData() throws Exception { String strInput = "Hello World"; ByteBuffer byteInput = ByteBuffer.wrap(strInput.getBytes("UTF8")); ByteBuffer byteCompressed = deflater.deflate(byteInput); // change the contents to something else. Since this doesn't check // for integrity, it wont throw an exception byteCompressed.put(5, (byte) 0xa); ByteBuffer byteUncompressed = inflater.inflate(byteCompressed); String strOutput = byteUncompressed.getString(Charset.forName("UTF8") .newDecoder()); assertFalse(strOutput.equals(strInput)); } public void testCorruptedHeader() throws Exception { String strInput = "Hello World"; ByteBuffer byteInput = ByteBuffer.wrap(strInput.getBytes("UTF8")); ByteBuffer byteCompressed = deflater.deflate(byteInput); // write a bad value into the zlib header. Make sure that // the decompression fails byteCompressed.put(0, (byte) 0xca); try { inflater.inflate(byteCompressed); } catch (IOException e) { assertTrue(true); return; } assertTrue(false); } public void testFragments() throws Exception { String strInput = ""; for (int i = 0; i < 10; i++) { strInput += "The quick brown fox jumps over the lazy dog. "; } ByteBuffer byteInput = ByteBuffer.wrap(strInput.getBytes("UTF8")); ByteBuffer byteCompressed = null; for (int i = 0; i < 5; i++) { byteCompressed = deflater.deflate(byteInput); if (i == 0) { // decompress the first compressed output since it contains // the zlib header, which will not be generated for further // compressions done with the same instance ByteBuffer byteUncompressed = inflater.inflate(byteCompressed); String strOutput = byteUncompressed.getString(Charset.forName( "UTF8").newDecoder()); assertTrue(strOutput.equals(strInput)); } } // check if the last compressed data block can be decompressed // successfully. ByteBuffer byteUncompressed = inflater.inflate(byteCompressed); String strOutput = byteUncompressed.getString(Charset.forName("UTF8") .newDecoder()); assertTrue(strOutput.equals(strInput)); } } mina-1.1.7.dfsg/filter-compression/src/test/java/org/apache/mina/filter/CompressionFilterTest.java0000644000175000017500000002065711002320014033161 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.filter.support.Zlib; import org.apache.mina.common.IoFilter.WriteRequest; import org.easymock.MockControl; import org.easymock.AbstractMatcher; import junit.framework.TestCase; /** * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class CompressionFilterTest extends TestCase { private MockControl mockSession; private MockControl mockNextFilter; private MockControl mockIoFilterChain; private IoSession session; private NextFilter nextFilter; private IoFilterChain ioFilterChain; private CompressionFilter filter; private Zlib deflater; private Zlib inflater; private Zlib actualDeflater; private Zlib actualInflater; // the sample data to be used for testing String strCompress = "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. "; protected void setUp() { // create the necessary mock controls. mockSession = MockControl.createControl(IoSession.class); mockNextFilter = MockControl.createControl(NextFilter.class); mockIoFilterChain = MockControl.createControl(IoFilterChain.class); // set the default matcher mockNextFilter.setDefaultMatcher(new DataMatcher()); session = (IoSession) mockSession.getMock(); nextFilter = (NextFilter) mockNextFilter.getMock(); ioFilterChain = (IoFilterChain) mockIoFilterChain.getMock(); // create an instance of the filter filter = new CompressionFilter(CompressionFilter.COMPRESSION_MAX); // deflater and inflater that will be used by the filter deflater = new Zlib(Zlib.COMPRESSION_MAX, Zlib.MODE_DEFLATER); inflater = new Zlib(Zlib.COMPRESSION_MAX, Zlib.MODE_INFLATER); // create instances of the deflater and inflater to help test the output actualDeflater = new Zlib(Zlib.COMPRESSION_MAX, Zlib.MODE_DEFLATER); actualInflater = new Zlib(Zlib.COMPRESSION_MAX, Zlib.MODE_INFLATER); } public void testCompression() throws Exception { // prepare the input data ByteBuffer buf = ByteBuffer.wrap(strCompress.getBytes("UTF8")); ByteBuffer actualOutput = actualDeflater.deflate(buf); WriteRequest writeRequest = new WriteRequest(buf); // record all the mock calls ioFilterChain.contains(CompressionFilter.class); mockIoFilterChain.setReturnValue(false); ioFilterChain.getSession(); mockIoFilterChain.setReturnValue(session); session.setAttribute(CompressionFilter.class.getName() + ".Deflater", deflater); mockSession.setDefaultMatcher(new DataMatcher()); mockSession.setReturnValue(null, MockControl.ONE); session.setAttribute(CompressionFilter.class.getName() + ".Inflater", inflater); mockSession.setReturnValue(null, MockControl.ONE); session.containsAttribute(CompressionFilter.DISABLE_COMPRESSION_ONCE); mockSession.setReturnValue(false); session.getAttribute(CompressionFilter.class.getName() + ".Deflater"); mockSession.setReturnValue(deflater); nextFilter.filterWrite(session, new WriteRequest(actualOutput)); // switch to playback mode mockSession.replay(); mockIoFilterChain.replay(); mockNextFilter.replay(); // make the actual calls on the filter filter.onPreAdd(ioFilterChain, "CompressionFilter", nextFilter); filter.filterWrite(nextFilter, session, writeRequest); // verify that all the calls happened as recorded mockNextFilter.verify(); assertTrue(true); } public void testDecompression() throws Exception { // prepare the input data ByteBuffer buf = ByteBuffer.wrap(strCompress.getBytes("UTF8")); ByteBuffer byteInput = actualDeflater.deflate(buf); ByteBuffer actualOutput = actualInflater.inflate(byteInput); // record all the mock calls ioFilterChain.contains(CompressionFilter.class); mockIoFilterChain.setReturnValue(false); ioFilterChain.getSession(); mockIoFilterChain.setReturnValue(session); session.setAttribute(CompressionFilter.class.getName() + ".Deflater", deflater); mockSession.setDefaultMatcher(new DataMatcher()); mockSession.setReturnValue(null, MockControl.ONE); session.setAttribute(CompressionFilter.class.getName() + ".Inflater", inflater); mockSession.setReturnValue(null, MockControl.ONE); session.getAttribute(CompressionFilter.class.getName() + ".Inflater"); mockSession.setReturnValue(inflater); nextFilter.messageReceived(session, actualOutput); // switch to playback mode mockSession.replay(); mockIoFilterChain.replay(); mockNextFilter.replay(); // make the actual calls on the filter filter.onPreAdd(ioFilterChain, "CompressionFilter", nextFilter); filter.messageReceived(nextFilter, session, byteInput); // verify that all the calls happened as recorded mockNextFilter.verify(); assertTrue(true); } /** * A matcher used to check if the actual and expected outputs matched * * @author The Apache Directory MINA subproject (mina-dev@directory.apache.org) */ class DataMatcher extends AbstractMatcher { protected boolean argumentMatches(Object arg0, Object arg1) { // we need to only verify the ByteBuffer output if (arg0 instanceof WriteRequest) { WriteRequest expected = (WriteRequest) arg0; WriteRequest actual = (WriteRequest) arg1; ByteBuffer bExpected = (ByteBuffer) expected.getMessage(); ByteBuffer bActual = (ByteBuffer) actual.getMessage(); return bExpected.equals(bActual); } return true; } } } mina-1.1.7.dfsg/src/0000755000175000017500000000000011002320016014032 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/0000755000175000017500000000000011044712500014707 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/pom.xml0000644000175000017500000000372611002320032016221 0ustar drazzibdrazzib 4.0.0 org.apache.mina build 1.1.7 mina-example Apache MINA Examples jar org.apache.mina mina-filter-ssl ${pom.version} compile org.apache.mina mina-integration-spring ${pom.version} compile org.slf4j slf4j-log4j12 1.4.3 runtime log4j log4j 1.2.14 runtime org.springframework spring-context 2.0.6 compile org.springframework spring-support 2.0.6 compile commons-net commons-net 1.4.1 test jmock jmock 1.2.0 test mina-1.1.7.dfsg/example/todo.txt0000644000175000017500000000006711002320032016405 0ustar drazzibdrazzib o cleanup all the noise produced by example testcases mina-1.1.7.dfsg/example/src/0000755000175000017500000000000011002320032015463 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/0000755000175000017500000000000011002320032016407 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/0000755000175000017500000000000011044712500020434 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/META-INF/0000755000175000017500000000000011044712500021574 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/META-INF/LICENSE.jzlib.txt0000644000175000017500000000316111002320032024516 0ustar drazzibdrazzibJZlib 0.0.* were released under the GNU LGPL license. Later, we have switched over to a BSD-style license. ------------------------------------------------------------------------------ Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mina-1.1.7.dfsg/example/src/main/resources/META-INF/LICENSE.txt0000644000175000017500000002415711002320032023415 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/example/src/main/resources/META-INF/LICENSE.slf4j.txt0000644000175000017500000000275511002320032024436 0ustar drazzibdrazzibCopyright (c) 2004-2005 SLF4J.ORG Copyright (c) 2004-2005 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. mina-1.1.7.dfsg/example/src/main/resources/META-INF/NOTICE.txt0000644000175000017500000000151711002320032023307 0ustar drazzibdrazzibApache MINA Copyright 2007 The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). Message logging is provided by the SLF4J library package, which is open source software, written by Ceki Gülcü, and copyright by SLF4J.ORG and QOS.ch. The original software is available from http://www.slf4j.org/ Data compression support is provided by the JZLib library package, which is open source software, written by JCraft, and copyright by JCraft. The original software is available from http://www.jcraft.com/jzlib/ Spring framework is provided by the Spring framework library package, which is open source software, written by Rod Johnson et al, and copyright by Springframework.org. The original software is available from http://www.springframework.org/ mina-1.1.7.dfsg/example/src/main/resources/META-INF/LICENSE.springframework.txt0000644000175000017500000002415711002320032026634 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS mina-1.1.7.dfsg/example/src/main/resources/org/0000755000175000017500000000000011002320032021210 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/org/apache/0000755000175000017500000000000011002320032022431 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/org/apache/mina/0000755000175000017500000000000011002320032023355 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/org/apache/mina/example/0000755000175000017500000000000011002320032025010 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/org/apache/mina/example/echoserver/0000755000175000017500000000000011002320032027155 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/org/apache/mina/example/echoserver/ssl/0000755000175000017500000000000011044712500027771 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/resources/org/apache/mina/example/echoserver/ssl/bogus.cert0000644000175000017500000000165111002320032031757 0ustar drazzibdrazzibbogus}Ė00 +*|a-##A֧o".FRy ֔Їf`BKZMiPо˖(-SXH:"3|'%Ne\5 IK82EW sa!F[ˈy (Ahic9+|&D[)O7؏D!ݥ ߰1ÛaE8DNc˸ꇖ(؄N v}Ѐq1YbiYAJkjK9TNe\0ܘ-R'X.50900rB,pS0  *H 0n1 0 USE10U Stockholm10U Stockholm10U  Bogus Inc10 U XXX CA10U bogus.com0 050307151635Z 150305151635Z0n1 0 USE10U Stockholm10U Stockholm10U  Bogus Inc10 U XXX CA10U bogus.com0[0  *H J0G@Z & |+mJ;X|jv>JHmK'6LAx3i o0  *H AI@Ba?>2n(9OdmiJE 5 @y |[:k#Ŧ];e8mina-1.1.7.dfsg/example/src/main/resources/log4j.properties0000644000175000017500000000054311002320032023560 0ustar drazzibdrazzib# Please don't modify the log level until we reach to acceptable test coverage. # It's very useful when I test examples manually. log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%d{HH:mm:ss}] %p [%c] - %m%n mina-1.1.7.dfsg/example/src/main/java/0000755000175000017500000000000011002320032017330 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/META-INF/0000755000175000017500000000000011044712500020503 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/META-INF/MANIFEST.MF0000644000175000017500000000004711002320032022123 0ustar drazzibdrazzibManifest-Version: 1.0 Class-Path: mina-1.1.7.dfsg/example/src/main/java/org/0000755000175000017500000000000011002320032020117 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/0000755000175000017500000000000011002320032021340 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/0000755000175000017500000000000011002320032022264 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/0000755000175000017500000000000011002320032023717 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/0000755000175000017500000000000011044712500025103 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/package.html0000644000175000017500000000025611002320032027354 0ustar drazzibdrazzib SumUp Server and Client which sums up all ADD requests. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/Server.java0000644000175000017500000000527011002320032027205 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup; import java.net.InetSocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.example.sumup.codec.SumUpProtocolCodecFactory; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; /** * (Entry Point) Starts SumUp server. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Server { private static final int SERVER_PORT = 8080; // Set this to false to use object serialization instead of custom codec. private static final boolean USE_CUSTOM_CODEC = true; public static void main(String[] args) throws Throwable { IoAcceptor acceptor = new SocketAcceptor(); // Prepare the service configuration. SocketAcceptorConfig cfg = new SocketAcceptorConfig(); cfg.setReuseAddress(true); if (USE_CUSTOM_CODEC) { cfg.getFilterChain() .addLast( "codec", new ProtocolCodecFilter( new SumUpProtocolCodecFactory(true))); } else { cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory())); } cfg.getFilterChain().addLast("logger", new LoggingFilter()); acceptor.bind(new InetSocketAddress(SERVER_PORT), new ServerSessionHandler(), cfg); System.out.println("Listening on port " + SERVER_PORT); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/message/0000755000175000017500000000000011044712500026527 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/message/package.html0000644000175000017500000000024411002320032030775 0ustar drazzibdrazzib Protocol mmessage classes for SumUp protocol. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/message/AbstractMessage.java0000644000175000017500000000252211002320032032430 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.message; import java.io.Serializable; /** * A base message for SumUp protocol messages. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class AbstractMessage implements Serializable { private int sequence; public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/message/ResultMessage.java0000644000175000017500000000333011002320032032141 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.message; /** * RESULT message in SumUp protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ResultMessage extends AbstractMessage { private static final long serialVersionUID = 7371210248110219946L; private boolean ok; private int value; public ResultMessage() { } public boolean isOk() { return ok; } public void setOk(boolean ok) { this.ok = ok; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String toString() { if (ok) { return getSequence() + ":RESULT(" + value + ')'; } else { return getSequence() + ":RESULT(ERROR)"; } } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/message/AddMessage.java0000644000175000017500000000305011002320032031352 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.message; /** * ADD message in SumUp protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class AddMessage extends AbstractMessage { private static final long serialVersionUID = -940833727168119141L; private int value; public AddMessage() { } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String toString() { // it is a good practice to create toString() method on message classes. return getSequence() + ":ADD(" + value + ')'; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/Client.java0000644000175000017500000000742311002320032027157 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup; import java.net.InetSocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoSession; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.example.sumup.codec.SumUpProtocolCodecFactory; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.transport.socket.nio.SocketConnector; import org.apache.mina.transport.socket.nio.SocketConnectorConfig; /** * (Entry Point) Starts SumUp client. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Client { private static final String HOSTNAME = "localhost"; private static final int PORT = 8080; private static final int CONNECT_TIMEOUT = 30; // seconds // Set this to false to use object serialization instead of custom codec. private static final boolean USE_CUSTOM_CODEC = true; public static void main(String[] args) throws Throwable { if (args.length == 0) { System.out.println("Please specify the list of any integers"); return; } // prepare values to sum up int[] values = new int[args.length]; for (int i = 0; i < args.length; i++) { values[i] = Integer.parseInt(args[i]); } SocketConnector connector = new SocketConnector(); // Change the worker timeout to 1 second to make the I/O thread quit soon // when there's no connection to manage. connector.setWorkerTimeout(1); // Configure the service. SocketConnectorConfig cfg = new SocketConnectorConfig(); cfg.setConnectTimeout(CONNECT_TIMEOUT); if (USE_CUSTOM_CODEC) { cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new SumUpProtocolCodecFactory(false))); } else { cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory())); } cfg.getFilterChain().addLast("logger", new LoggingFilter()); IoSession session; for (;;) { try { ConnectFuture future = connector.connect(new InetSocketAddress( HOSTNAME, PORT), new ClientSessionHandler(values), cfg); future.join(); session = future.getSession(); break; } catch (RuntimeIOException e) { System.err.println("Failed to connect."); e.printStackTrace(); Thread.sleep(5000); } } // wait until the summation is done session.getCloseFuture().join(); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/ClientSessionHandler.java0000644000175000017500000000564011002320032032020 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AddMessage; import org.apache.mina.example.sumup.message.ResultMessage; import org.apache.mina.util.SessionLog; /** * {@link IoHandler} for SumUp client. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ClientSessionHandler extends IoHandlerAdapter { private final int[] values; private boolean finished; public ClientSessionHandler(int[] values) { this.values = values; } public boolean isFinished() { return finished; } public void sessionOpened(IoSession session) { // send summation requests for (int i = 0; i < values.length; i++) { AddMessage m = new AddMessage(); m.setSequence(i); m.setValue(values[i]); session.write(m); } } public void messageReceived(IoSession session, Object message) { // server only sends ResultMessage. otherwise, we will have to identify // its type using instanceof operator. ResultMessage rm = (ResultMessage) message; if (rm.isOk()) { // server returned OK code. // if received the result message which has the last sequence // number, // it is time to disconnect. if (rm.getSequence() == values.length - 1) { // print the sum and disconnect. SessionLog.info(session, "The sum: " + rm.getValue()); session.close(); finished = true; } } else { // seever returned error code because of overflow, etc. SessionLog.warn(session, "Server error, disconnecting..."); session.close(); finished = true; } } public void exceptionCaught(IoSession session, Throwable cause) { session.close(); } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/ServerSessionHandler.java0000644000175000017500000000621211002320032032044 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AddMessage; import org.apache.mina.example.sumup.message.ResultMessage; import org.apache.mina.util.SessionLog; /** * {@link IoHandler} for SumUp server. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ServerSessionHandler extends IoHandlerAdapter { public void sessionOpened(IoSession session) { // set idle time to 60 seconds session.setIdleTime(IdleStatus.BOTH_IDLE, 60); // initial sum is zero session.setAttachment(new Integer(0)); } public void messageReceived(IoSession session, Object message) { // client only sends AddMessage. otherwise, we will have to identify // its type using instanceof operator. AddMessage am = (AddMessage) message; // add the value to the current sum. int sum = ((Integer) session.getAttachment()).intValue(); int value = am.getValue(); long expectedSum = (long) sum + value; if (expectedSum > Integer.MAX_VALUE || expectedSum < Integer.MIN_VALUE) { // if the sum overflows or underflows, return error message ResultMessage rm = new ResultMessage(); rm.setSequence(am.getSequence()); // copy sequence rm.setOk(false); session.write(rm); } else { // sum up sum = (int) expectedSum; session.setAttachment(new Integer(sum)); // return the result message ResultMessage rm = new ResultMessage(); rm.setSequence(am.getSequence()); // copy sequence rm.setOk(true); rm.setValue(sum); session.write(rm); } } public void sessionIdle(IoSession session, IdleStatus status) { SessionLog.info(session, "Disconnecting the idle."); // disconnect an idle client session.close(); } public void exceptionCaught(IoSession session, Throwable cause) { // close the connection on exceptional situation session.close(); } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/0000755000175000017500000000000011044712500026160 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/AbstractMessageEncoder.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/AbstractMessageEncoder.jav0000644000175000017500000000425711002320032033227 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AbstractMessage; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; /** * A {@link MessageEncoder} that encodes message header and forwards * the encoding of body to a subclass. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class AbstractMessageEncoder implements MessageEncoder { private final int type; protected AbstractMessageEncoder(int type) { this.type = type; } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { AbstractMessage m = (AbstractMessage) message; ByteBuffer buf = ByteBuffer.allocate(16); buf.setAutoExpand(true); // Enable auto-expand for easier encoding // Encode a header buf.putShort((short) type); buf.putInt(m.getSequence()); // Encode a body encodeBody(session, m, buf); buf.flip(); out.write(buf); } protected abstract void encodeBody(IoSession session, AbstractMessage message, ByteBuffer out); } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/ResultMessageEncoder.java0000644000175000017500000000437311002320032033102 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AbstractMessage; import org.apache.mina.example.sumup.message.ResultMessage; import org.apache.mina.filter.codec.demux.MessageEncoder; /** * A {@link MessageEncoder} that encodes {@link ResultMessage}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ResultMessageEncoder extends AbstractMessageEncoder { private static final Set> TYPES; static { Set> types = new HashSet>(); types.add(ResultMessage.class); TYPES = Collections.unmodifiableSet(types); } public ResultMessageEncoder() { super(Constants.RESULT); } protected void encodeBody(IoSession session, AbstractMessage message, ByteBuffer out) { ResultMessage m = (ResultMessage) message; if (m.isOk()) { out.putShort((short) Constants.RESULT_OK); out.putInt(m.getValue()); } else { out.putShort((short) Constants.RESULT_ERROR); } } public Set> getMessageTypes() { return TYPES; } public void dispose() throws Exception { } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/package.html0000644000175000017500000000025011002320032030423 0ustar drazzibdrazzib Protocol codec implementation for SumUp protocol. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/AddMessageDecoder.java0000644000175000017500000000362411002320032032300 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AbstractMessage; import org.apache.mina.example.sumup.message.AddMessage; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoder; /** * A {@link MessageDecoder} that decodes {@link AddMessage}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class AddMessageDecoder extends AbstractMessageDecoder { public AddMessageDecoder() { super(Constants.ADD); } protected AbstractMessage decodeBody(IoSession session, ByteBuffer in) { if (in.remaining() < Constants.ADD_BODY_LEN) { return null; } AddMessage m = new AddMessage(); m.setValue(in.getInt()); return m; } public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/SumUpProtocolCodecFactory.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/SumUpProtocolCodecFactory.0000644000175000017500000000323111002320032033226 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory; /** * A {@link ProtocolCodecFactory} that provides a protocol codec for * SumUp protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SumUpProtocolCodecFactory extends DemuxingProtocolCodecFactory { public SumUpProtocolCodecFactory(boolean server) { if (server) { super.register(AddMessageDecoder.class); super.register(ResultMessageEncoder.class); } else // Client { super.register(AddMessageEncoder.class); super.register(ResultMessageDecoder.class); } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/Constants.java0000644000175000017500000000317411002320032030771 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; /** * Provides SumUp protocol constants. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Constants { public static final int TYPE_LEN = 2; public static final int SEQUENCE_LEN = 4; public static final int HEADER_LEN = TYPE_LEN + SEQUENCE_LEN; public static final int BODY_LEN = 12; public static final int RESULT = 0; public static final int ADD = 1; public static final int RESULT_CODE_LEN = 2; public static final int RESULT_VALUE_LEN = 4; public static final int ADD_BODY_LEN = 4; public static final int RESULT_OK = 0; public static final int RESULT_ERROR = 1; private Constants() { } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/AddMessageEncoder.java0000644000175000017500000000407211002320032032310 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AbstractMessage; import org.apache.mina.example.sumup.message.AddMessage; import org.apache.mina.filter.codec.demux.MessageEncoder; /** * A {@link MessageEncoder} that encodes {@link AddMessage}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class AddMessageEncoder extends AbstractMessageEncoder { private static final Set> TYPES; static { Set> types = new HashSet>(); types.add(AddMessage.class); TYPES = Collections.unmodifiableSet(types); } public AddMessageEncoder() { super(Constants.ADD); } protected void encodeBody(IoSession session, AbstractMessage message, ByteBuffer out) { AddMessage m = (AddMessage) message; out.putInt(m.getValue()); } public Set> getMessageTypes() { return TYPES; } public void dispose() throws Exception { } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/AbstractMessageDecoder.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/AbstractMessageDecoder.jav0000644000175000017500000000612411002320032033210 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AbstractMessage; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoder; import org.apache.mina.filter.codec.demux.MessageDecoderResult; /** * A {@link MessageDecoder} that decodes message header and forwards * the decoding of body to a subclass. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public abstract class AbstractMessageDecoder implements MessageDecoder { private final int type; private int sequence; private boolean readHeader; protected AbstractMessageDecoder(int type) { this.type = type; } public MessageDecoderResult decodable(IoSession session, ByteBuffer in) { // Return NEED_DATA if the whole header is not read yet. if (in.remaining() < Constants.HEADER_LEN) { return MessageDecoderResult.NEED_DATA; } // Return OK if type and bodyLength matches. if (type == in.getShort()) { return MessageDecoderResult.OK; } // Return NOT_OK if not matches. return MessageDecoderResult.NOT_OK; } public MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { // Try to skip header if not read. if (!readHeader) { in.getShort(); // Skip 'type'. sequence = in.getInt(); // Get 'sequence'. readHeader = true; } // Try to decode body AbstractMessage m = decodeBody(session, in); // Return NEED_DATA if the body is not fully read. if (m == null) { return MessageDecoderResult.NEED_DATA; } else { readHeader = false; // reset readHeader for the next decode } m.setSequence(sequence); out.write(m); return MessageDecoderResult.OK; } /** * @return null if the whole body is not read yet */ protected abstract AbstractMessage decodeBody(IoSession session, ByteBuffer in); } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/sumup/codec/ResultMessageDecoder.java0000644000175000017500000000473411002320032033071 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.sumup.codec; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.example.sumup.message.AbstractMessage; import org.apache.mina.example.sumup.message.ResultMessage; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoder; /** * A {@link MessageDecoder} that decodes {@link ResultMessage}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ResultMessageDecoder extends AbstractMessageDecoder { private int code; private boolean readCode; public ResultMessageDecoder() { super(Constants.RESULT); } protected AbstractMessage decodeBody(IoSession session, ByteBuffer in) { if (!readCode) { if (in.remaining() < Constants.RESULT_CODE_LEN) { return null; // Need more data. } code = in.getShort(); readCode = true; } if (code == Constants.RESULT_OK) { if (in.remaining() < Constants.RESULT_VALUE_LEN) { return null; } ResultMessage m = new ResultMessage(); m.setOk(true); m.setValue(in.getInt()); readCode = false; return m; } else { ResultMessage m = new ResultMessage(); m.setOk(false); readCode = false; return m; } } public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/0000755000175000017500000000000011002320032026125 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/stream/0000755000175000017500000000000011044712500027433 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/stream/package.html0000644000175000017500000000026211002320032031701 0ustar drazzibdrazzib A simplistic HTTP server which demonstates stream-based I/O support. ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/stream/HttpProtocolHandler.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/stream/HttpProtocolHandler.0000644000175000017500000001014311002320032033357 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.stream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import org.apache.mina.common.IoSession; import org.apache.mina.handler.StreamIoHandler; /** * A simplistic HTTP protocol handler that replies back the URL and headers * which a client requested. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class HttpProtocolHandler extends StreamIoHandler { protected void processStreamIo(IoSession session, InputStream in, OutputStream out) { // You *MUST* execute stream I/O logic in a separate thread. new Worker(in, out).start(); } private static class Worker extends Thread { private final InputStream in; private final OutputStream out; public Worker(InputStream in, OutputStream out) { setDaemon(true); this.in = in; this.out = out; } public void run() { String url; Map headers = new TreeMap(); BufferedReader in = new BufferedReader(new InputStreamReader( this.in)); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(this.out))); try { // Get request URL. url = in.readLine().split(" ")[1]; // Read header String line; while ((line = in.readLine()) != null && !line.equals("")) { String[] tokens = line.split(": "); headers.put(tokens[0], tokens[1]); } // Write header out.println("HTTP/1.0 200 OK"); out.println("Content-Type: text/html"); out.println("Server: MINA Example"); out.println(); // Write content out.println(""); out.println("

Request Summary for: " + url + "

"); out .println(""); Iterator it = headers.entrySet().iterator(); while (it.hasNext()) { Entry e = (Entry) it.next(); out.println(""); } out.println("
KeyValue
" + e.getKey() + "" + e.getValue() + "
"); for (int i = 0; i < 1024; i++) { out.println("this is line: " + i + "
"); } out.println(""); } catch (Exception e) { e.printStackTrace(); } finally { out.flush(); out.close(); try { in.close(); } catch (IOException e) { } } } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/stream/Main.java0000644000175000017500000000515311002320032031153 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.stream; import java.net.InetSocketAddress; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; import org.apache.mina.filter.SSLFilter; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.apache.mina.transport.socket.nio.SocketSessionConfig; /** * (Entry point) HTTP server * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Main { /** Choose your favorite port number. */ private static final int PORT = 8080; private static final boolean USE_SSL = false; public static void main(String[] args) throws Exception { IoAcceptor acceptor = new SocketAcceptor(); IoAcceptorConfig config = new SocketAcceptorConfig(); DefaultIoFilterChainBuilder chain = config.getFilterChain(); ((SocketSessionConfig) config.getSessionConfig()).setReuseAddress(true); // Add SSL filter if SSL is enabled. if (USE_SSL) { addSSLSupport(chain); } // Bind acceptor.bind(new InetSocketAddress(PORT), new HttpProtocolHandler(), config); System.out.println("Listening on port " + PORT); } private static void addSSLSupport(DefaultIoFilterChainBuilder chain) throws Exception { System.out.println("SSL is enabled."); SSLFilter sslFilter = new SSLFilter(BogusSSLContextFactory .getInstance(true)); chain.addLast("sslFilter", sslFilter); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/0000755000175000017500000000000011044712500027215 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.ja0000644000175000017500000002067411002320032033305 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderAdapter; import org.apache.mina.filter.codec.demux.MessageDecoderResult; /** * A {@link org.apache.mina.filter.codec.demux.MessageDecoder} that decodes {@link HttpRequest}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class HttpRequestDecoder extends MessageDecoderAdapter { private static final byte[] CONTENT_LENGTH = new String("Content-Length:") .getBytes(); private CharsetDecoder decoder = Charset.defaultCharset().newDecoder(); private HttpRequestMessage request = null; public HttpRequestDecoder() { } public MessageDecoderResult decodable(IoSession session, ByteBuffer in) { // Return NEED_DATA if the whole header is not read yet. try { return messageComplete(in) ? MessageDecoderResult.OK : MessageDecoderResult.NEED_DATA; } catch (Exception ex) { ex.printStackTrace(); } return MessageDecoderResult.NOT_OK; } public MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { // Try to decode body HttpRequestMessage m = decodeBody(in); // Return NEED_DATA if the body is not fully read. if (m == null) return MessageDecoderResult.NEED_DATA; out.write(m); return MessageDecoderResult.OK; } private boolean messageComplete(ByteBuffer in) throws Exception { int last = in.remaining() - 1; if (in.remaining() < 4) return false; // to speed up things we check if the Http request is a GET or POST if (in.get(0) == (byte) 'G' && in.get(1) == (byte) 'E' && in.get(2) == (byte) 'T') { // Http GET request therefore the last 4 bytes should be 0x0D 0x0A 0x0D 0x0A return (in.get(last) == (byte) 0x0A && in.get(last - 1) == (byte) 0x0D && in.get(last - 2) == (byte) 0x0A && in.get(last - 3) == (byte) 0x0D); } else if (in.get(0) == (byte) 'P' && in.get(1) == (byte) 'O' && in.get(2) == (byte) 'S' && in.get(3) == (byte) 'T') { // Http POST request // first the position of the 0x0D 0x0A 0x0D 0x0A bytes int eoh = -1; for (int i = last; i > 2; i--) { if (in.get(i) == (byte) 0x0A && in.get(i - 1) == (byte) 0x0D && in.get(i - 2) == (byte) 0x0A && in.get(i - 3) == (byte) 0x0D) { eoh = i + 1; break; } } if (eoh == -1) return false; for (int i = 0; i < last; i++) { boolean found = false; for (int j = 0; j < CONTENT_LENGTH.length; j++) { if (in.get(i + j) != CONTENT_LENGTH[j]) { found = false; break; } found = true; } if (found) { // retrieve value from this position till next 0x0D 0x0A StringBuilder contentLength = new StringBuilder(); for (int j = i + CONTENT_LENGTH.length; j < last; j++) { if (in.get(j) == 0x0D) break; contentLength.append(new String( new byte[] { in.get(j) })); } // if content-length worth of data has been received then the message is complete return (Integer.parseInt(contentLength.toString().trim()) + eoh == in.remaining()); } } } // the message is not complete and we need more data return false; } private HttpRequestMessage decodeBody(ByteBuffer in) { request = new HttpRequestMessage(); try { request.setHeaders(parseRequest(new StringReader(in .getString(decoder)))); return request; } catch (CharacterCodingException ex) { ex.printStackTrace(); } return null; } private Map parseRequest(Reader is) { Map map = new HashMap(); BufferedReader rdr = new BufferedReader(is); try { // Get request URL. String line = rdr.readLine(); String[] url = line.split(" "); if (url.length < 3) return map; map.put("URI", new String[] { line }); map.put("Method", new String[] { url[0].toUpperCase() }); map.put("Context", new String[] { url[1].substring(1) }); map.put("Protocol", new String[] { url[2] }); // Read header while ((line = rdr.readLine()) != null && line.length() > 0) { String[] tokens = line.split(": "); map.put(tokens[0], new String[] { tokens[1] }); } // If method 'POST' then read Content-Length worth of data if (url[0].equalsIgnoreCase("POST")) { int len = Integer.parseInt(map.get("Content-Length")[0]); char[] buf = new char[len]; if (rdr.read(buf) == len) { line = String.copyValueOf(buf); } } else if (url[0].equalsIgnoreCase("GET")) { int idx = url[1].indexOf('?'); if (idx != -1) { map.put("Context", new String[] { url[1].substring(1, idx) }); line = url[1].substring(idx + 1); } else { line = null; } } if (line != null) { String[] match = line.split("\\&"); for (int i = 0; i < match.length; i++) { String[] params = new String[1]; String[] tokens = match[i].split("="); switch (tokens.length) { case 0: map.put("@".concat(match[i]), new String[] {}); break; case 1: map.put("@".concat(tokens[0]), new String[] {}); break; default: String name = "@".concat(tokens[0]); if (map.containsKey(name)) { params = map.get(name); String[] tmp = new String[params.length + 1]; for (int j = 0; j < params.length; j++) tmp[j] = params[j]; params = null; params = tmp; } params[params.length - 1] = tokens[1].trim(); map.put(name, params); } } } } catch (IOException ex) { ex.printStackTrace(); } return map; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/package.html0000644000175000017500000000025611002320032031466 0ustar drazzibdrazzib A HTTP server implemented with protocol codec (needs more work). mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/Server.java0000644000175000017500000000517711002320032031325 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import java.net.InetSocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; /** * (Entry point) HTTP server * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Server { /** Default HTTP port */ private static int DEFAULT_PORT = 8080; /** Tile server revision number */ public static final String VERSION_STRING = "$Revision: 555855 $ $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $"; public static void main(String[] args) { int port = DEFAULT_PORT; for (int i = 0; i < args.length; i++) { if (args[i].equals("-port")) { port = Integer.parseInt(args[i + 1]); } } try { // Create an acceptor IoAcceptor acceptor = new SocketAcceptor(); // Create a service configuration SocketAcceptorConfig cfg = new SocketAcceptorConfig(); cfg.setReuseAddress(true); cfg.getFilterChain().addLast( "protocolFilter", new ProtocolCodecFilter( new HttpServerProtocolCodecFactory())); cfg.getFilterChain().addLast("logger", new LoggingFilter()); acceptor .bind(new InetSocketAddress(port), new ServerHandler(), cfg); System.out.println("Server now listening on port " + port); } catch (Exception ex) { ex.printStackTrace(); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestMessage.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestMessage.ja0000644000175000017500000000532111002320032033314 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * A HTTP request message. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class HttpRequestMessage { /** Map */ private Map headers = null; public void setHeaders(Map headers) { this.headers = headers; } public Map getHeaders() { return headers; } public String getContext() { String[] context = (String[]) headers.get("Context"); return context == null ? "" : context[0]; } public String getParameter(String name) { String[] param = (String[]) headers.get("@".concat(name)); return param == null ? "" : param[0]; } public String[] getParameters(String name) { String[] param = (String[]) headers.get("@".concat(name)); return param == null ? new String[] {} : param; } public String[] getHeader(String name) { return (String[]) headers.get(name); } public String toString() { StringBuilder str = new StringBuilder(); Iterator it = headers.entrySet().iterator(); while (it.hasNext()) { Entry e = (Entry) it.next(); str.append(e.getKey() + " : " + arrayToString((String[]) e.getValue(), ',') + "\n"); } return str.toString(); } public static String arrayToString(String[] s, char sep) { if (s == null || s.length == 0) return ""; StringBuffer buf = new StringBuffer(); if (s != null) { for (int i = 0; i < s.length; i++) { if (i > 0) buf.append(sep); buf.append(s[i]); } } return buf.toString(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.j0000644000175000017500000000763511002320032033326 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; /** * A {@link MessageEncoder} that encodes {@link HttpResponseMessage}. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class HttpResponseEncoder implements MessageEncoder { private static final Set> TYPES; static { Set> types = new HashSet>(); types.add(HttpResponseMessage.class); TYPES = Collections.unmodifiableSet(types); } private static final byte[] CRLF = new byte[] { 0x0D, 0x0A }; public HttpResponseEncoder() { } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { HttpResponseMessage msg = (HttpResponseMessage) message; ByteBuffer buf = ByteBuffer.allocate(256); // Enable auto-expand for easier encoding buf.setAutoExpand(true); try { // output all headers except the content length CharsetEncoder encoder = Charset.defaultCharset().newEncoder(); buf.putString("HTTP/1.1 ", encoder); buf.putString(String.valueOf(msg.getResponseCode()), encoder); switch (msg.getResponseCode()) { case HttpResponseMessage.HTTP_STATUS_SUCCESS: buf.putString(" OK", encoder); break; case HttpResponseMessage.HTTP_STATUS_NOT_FOUND: buf.putString(" Not Found", encoder); break; } buf.put(CRLF); for (Iterator it = msg.getHeaders().entrySet().iterator(); it .hasNext();) { Entry entry = (Entry) it.next(); buf.putString((String) entry.getKey(), encoder); buf.putString(": ", encoder); buf.putString((String) entry.getValue(), encoder); buf.put(CRLF); } // now the content length is the body length buf.putString("Content-Length: ", encoder); buf.putString(String.valueOf(msg.getBodyLength()), encoder); buf.put(CRLF); buf.put(CRLF); // add body buf.put(msg.getBody()); //System.out.println("\n+++++++"); //for (int i=0; i> getMessageTypes() { return TYPES; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/ServerHandler.java0000644000175000017500000000613311002320032032614 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.util.SessionLog; /** * An {@link IoHandler} for HTTP. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class ServerHandler extends IoHandlerAdapter { @Override public void sessionOpened(IoSession session) { // set idle time to 60 seconds session.setIdleTime(IdleStatus.BOTH_IDLE, 60); } @Override public void messageReceived(IoSession session, Object message) { // Check that we can service the request context HttpResponseMessage response = new HttpResponseMessage(); response.setContentType("text/plain"); response.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS); response.appendBody("CONNECTED"); // msg.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS); // byte[] b = new byte[ta.buffer.limit()]; // ((ByteBuffer)ta.buffer.rewind()).get(b); // msg.appendBody(b); // System.out.println("####################"); // System.out.println(" GET_TILE RESPONSE SENT - ATTACHMENT GOOD DIAMOND.SI="+d.si+ // ", "+new java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss.SSS").format(new java.util.Date())); // System.out.println("#################### - status="+ta.state+", index="+message.getIndex()); //// Unknown request // response = new HttpResponseMessage(); // response.setResponseCode(HttpResponseMessage.HTTP_STATUS_NOT_FOUND); // response.appendBody(String.format( // "

UNKNOWN REQUEST %d

", // HttpResponseMessage.HTTP_STATUS_NOT_FOUND)); if (response != null) { session.write(response).join(); } } @Override public void sessionIdle(IoSession session, IdleStatus status) { SessionLog.info(session, "Disconnecting the idle."); session.close(); } @Override public void exceptionCaught(IoSession session, Throwable cause) { session.close(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseMessage.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseMessage.j0000644000175000017500000000615711002320032033331 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.mina.common.ByteBuffer; /** * A HTTP response message. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class HttpResponseMessage { /** HTTP response codes */ public static final int HTTP_STATUS_SUCCESS = 200; public static final int HTTP_STATUS_NOT_FOUND = 404; /** Map */ private Map headers = new HashMap(); /** Storage for body of HTTP response. */ private ByteArrayOutputStream body = new ByteArrayOutputStream(1024); private int responseCode = HTTP_STATUS_SUCCESS; public HttpResponseMessage() { headers.put("Server", "HttpServer (" + Server.VERSION_STRING + ')'); headers.put("Cache-Control", "private"); headers.put("Content-Type", "text/html; charset=iso-8859-1"); headers.put("Connection", "keep-alive"); headers.put("Keep-Alive", "200"); headers.put("Date", new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date())); headers.put("Last-Modified", new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date())); } public Map getHeaders() { return headers; } public void setContentType(String contentType) { headers.put("Content-Type", contentType); } public void setResponseCode(int responseCode) { this.responseCode = responseCode; } public int getResponseCode() { return this.responseCode; } public void appendBody(byte[] b) { try { body.write(b); } catch (IOException ex) { ex.printStackTrace(); } } public void appendBody(String s) { try { body.write(s.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } } public ByteBuffer getBody() { return ByteBuffer.wrap(body.toByteArray()); } public int getBodyLength() { return body.size(); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpServerProtocolCodecFactory.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpServerProtocolCod0000644000175000017500000000260611002320032033407 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.httpserver.codec; import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory; /** * Provides a protocol codec for HTTP server. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class HttpServerProtocolCodecFactory extends DemuxingProtocolCodecFactory { public HttpServerProtocolCodecFactory() { super.register(HttpRequestDecoder.class); super.register(HttpResponseEncoder.class); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/tennis/0000755000175000017500000000000011044712500025232 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/tennis/package.html0000644000175000017500000000025311002320032027500 0ustar drazzibdrazzib Two tennis players play a game which demonstates in-VM pipes. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/tennis/TennisPlayer.java0000644000175000017500000000464611002320032030511 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.tennis; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; /** * A {@link IoHandler} implementation which plays a tennis game. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class TennisPlayer extends IoHandlerAdapter { private static int nextId = 0; /** Player ID **/ private final int id = nextId++; public void sessionOpened(IoSession session) { System.out.println("Player-" + id + ": READY"); } public void sessionClosed(IoSession session) { System.out.println("Player-" + id + ": QUIT"); } public void messageReceived(IoSession session, Object message) { System.out.println("Player-" + id + ": RCVD " + message); TennisBall ball = (TennisBall) message; // Stroke: TTL decreases and PING/PONG state changes. ball = ball.stroke(); if (ball.getTTL() > 0) { // If the ball is still alive, pass it back to peer. session.write(ball); } else { // If the ball is dead, this player loses. System.out.println("Player-" + id + ": LOSE"); session.close(); } } public void messageSent(IoSession session, Object message) { System.out.println("Player-" + id + ": SENT " + message); } public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); session.close(); } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/tennis/Main.java0000644000175000017500000000467011002320032026755 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.tennis; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoSession; import org.apache.mina.transport.vmpipe.VmPipeAcceptor; import org.apache.mina.transport.vmpipe.VmPipeAddress; import org.apache.mina.transport.vmpipe.VmPipeConnector; /** * (Entry point) An 'in-VM pipe' example which simulates a tennis game * between client and server. *
    *
  1. Client connects to server
  2. *
  3. At first, client sends {@link TennisBall} with TTL value '10'.
  4. *
  5. Received side (either server or client) decreases the TTL value of the * received ball, and returns it to remote peer.
  6. *
  7. Who gets the ball with 0 TTL loses.
  8. *
* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Main { public static void main(String[] args) throws Exception { IoAcceptor acceptor = new VmPipeAcceptor(); VmPipeAddress address = new VmPipeAddress(8080); // Set up server acceptor.bind(address, new TennisPlayer()); // Connect to the server. VmPipeConnector connector = new VmPipeConnector(); ConnectFuture future = connector.connect(address, new TennisPlayer()); future.join(); IoSession session = future.getSession(); // Send the first ping message session.write(new TennisBall(10)); // Wait until the match ends. session.getCloseFuture().join(); acceptor.unbind(address); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/tennis/TennisBall.java0000644000175000017500000000422611002320032030121 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.tennis; /** * A tennis ball which has TTL value and state whose value is one of 'PING' and * 'PONG'. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class TennisBall { private final boolean ping; private final int ttl; /** * Creates a new ball with the specified TTL (Time To Live) value. */ public TennisBall(int ttl) { this(ttl, true); } /** * Creates a new ball with the specified TTL value and PING/PONG state. */ private TennisBall(int ttl, boolean ping) { this.ttl = ttl; this.ping = ping; } /** * Returns the TTL value of this ball. */ public int getTTL() { return ttl; } /** * Returns the ball after {@link TennisPlayer}'s stroke. * The returned ball has decreased TTL value and switched PING/PONG state. */ public TennisBall stroke() { return new TennisBall(ttl - 1, !ping); } /** * Returns string representation of this message ([PING|PONG] * (TTL)). */ public String toString() { if (ping) { return "PING (" + ttl + ")"; } else { return "PONG (" + ttl + ")"; } } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/reverser/0000755000175000017500000000000011044712500025567 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/reverser/package.html0000644000175000017500000000031411002320032030033 0ustar drazzibdrazzib Reverser server which reverses all text lines demonstating high-level protocol layer. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/reverser/ReverseProtocolHandler.java0000644000175000017500000000353511002320032033060 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.reverser; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; /** * {@link IoHandler} implementation of reverser server protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class ReverseProtocolHandler extends IoHandlerAdapter { public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); // Close connection when unexpected exception is caught. session.close(); } public void messageReceived(IoSession session, Object message) { // Reverse reveiced string String str = message.toString(); StringBuffer buf = new StringBuffer(str.length()); for (int i = str.length() - 1; i >= 0; i--) { buf.append(str.charAt(i)); } // and write it back. session.write(buf.toString()); } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/reverser/Main.java0000644000175000017500000000435611002320032027313 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.reverser; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.common.IoAcceptor; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; /** * (Entry point) Reverser server which reverses all text lines from * clients. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class Main { private static final int PORT = 8080; public static void main(String[] args) throws Exception { IoAcceptor acceptor = new SocketAcceptor(); // Prepare the configuration SocketAcceptorConfig cfg = new SocketAcceptorConfig(); cfg.setReuseAddress(true); cfg.getFilterChain().addLast("logger", new LoggingFilter()); cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8")))); // Bind acceptor.bind(new InetSocketAddress(PORT), new ReverseProtocolHandler(), cfg); System.out.println("Listening on port " + PORT); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/0000755000175000017500000000000011044712500024651 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/serverContext.xml0000644000175000017500000001002311002320032030227 0ustar drazzibdrazzib mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java0000644000175000017500000001155311002320032031405 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.util.SessionLog; /** * {@link IoHandler} implementation of a simple chat server protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class ChatProtocolHandler extends IoHandlerAdapter { private Set sessions = Collections .synchronizedSet(new HashSet()); private Set users = Collections .synchronizedSet(new HashSet()); public void exceptionCaught(IoSession session, Throwable cause) { SessionLog.error(session, "", cause); // Close connection when unexpected exception is caught. session.close(); } public void messageReceived(IoSession session, Object message) { String theMessage = (String) message; String[] result = theMessage.split(" ", 2); String theCommand = result[0]; try { ChatCommand command = ChatCommand.valueOf(theCommand); String user = (String) session.getAttribute("user"); switch (command.toInt()) { case ChatCommand.QUIT: session.write("QUIT OK"); session.close(); break; case ChatCommand.LOGIN: if (user != null) { session.write("LOGIN ERROR user " + user + " already logged in."); return; } if (result.length == 2) { user = result[1]; } else { session.write("LOGIN ERROR invalid login command."); return; } // check if the username is already used if (users.contains(user)) { session.write("LOGIN ERROR the name " + user + " is already used."); return; } sessions.add(session); session.setAttribute("user", user); // Allow all users users.add(user); session.write("LOGIN OK"); broadcast("The user " + user + " has joined the chat session."); break; case ChatCommand.BROADCAST: if (result.length == 2) { broadcast(user + ": " + result[1]); } break; default: SessionLog.info(session, "Unhandled command: " + command); break; } } catch (IllegalArgumentException e) { SessionLog.debug(session, e.getMessage()); } } public void broadcast(String message) { synchronized (sessions) { Iterator iter = sessions.iterator(); while (iter.hasNext()) { IoSession s = (IoSession) iter.next(); if (s.isConnected()) { s.write("BROADCAST OK " + message); } } } } public void sessionClosed(IoSession session) throws Exception { String user = (String) session.getAttribute("user"); users.remove(user); sessions.remove(session); broadcast("The user " + user + " has left the chat session."); } public boolean isChatUser(String name) { return users.contains(name); } public int getNumberOfUsers() { return users.size(); } public void kick(String name) { synchronized (sessions) { Iterator iter = sessions.iterator(); while (iter.hasNext()) { IoSession s = (IoSession) iter.next(); if (name.equals(s.getAttribute("user"))) { s.close(); break; } } } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/package.html0000644000175000017500000000027511002320032027123 0ustar drazzibdrazzib Chat server which demonstates using the text line codec and Spring integration. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/jmxContext.xml0000644000175000017500000000171011002320032027522 0ustar drazzibdrazzib mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/SpringMain.java0000644000175000017500000000413111002320032027547 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * (Entry point) Chat server which uses Spring and the serverContext.xml * file to set up MINA and the server handler. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class SpringMain { public static void main(String[] args) throws Exception { if (System.getProperty("com.sun.management.jmxremote") != null) { new ClassPathXmlApplicationContext(getJmxApplicationContexts()); System.out.println("JMX enabled."); } else { new ClassPathXmlApplicationContext(getApplicationContext()); System.out .println("JMX disabled. Please set the " + "'com.sun.management.jmxremote' system property to enable JMX."); } System.out.println("Listening ..."); } public static String getApplicationContext() { return "org/apache/mina/example/chat/serverContext.xml"; } public static String[] getJmxApplicationContexts() { return new String[] { "org/apache/mina/example/chat/serverContext.xml", "org/apache/mina/example/chat/jmxContext.xml" }; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/0000755000175000017500000000000011044712500026127 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/package.html0000644000175000017500000000020611002320032030373 0ustar drazzibdrazzib Swing based chat client. ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.jav0000644000175000017500000000653311002320032033151 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat.client; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.example.chat.ChatCommand; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; /** * {@link IoHandler} implementation of the client side of the simple chat protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class SwingChatClientHandler extends IoHandlerAdapter { public interface Callback { void connected(); void loggedIn(); void loggedOut(); void disconnected(); void messageReceived(String message); void error(String message); } private static IoFilter LOGGING_FILTER = new LoggingFilter(); private static IoFilter CODEC_FILTER = new ProtocolCodecFilter( new TextLineCodecFactory()); private final Callback callback; public SwingChatClientHandler(Callback callback) { this.callback = callback; } public void sessionCreated(IoSession session) throws Exception { session.getFilterChain().addLast("codec", CODEC_FILTER); session.getFilterChain().addLast("logger", LOGGING_FILTER); } public void sessionOpened(IoSession session) throws Exception { callback.connected(); } public void messageReceived(IoSession session, Object message) throws Exception { String theMessage = (String) message; String[] result = theMessage.split(" ", 3); String status = result[1]; String theCommand = result[0]; ChatCommand command = ChatCommand.valueOf(theCommand); if ("OK".equals(status)) { switch (command.toInt()) { case ChatCommand.BROADCAST: if (result.length == 3) { callback.messageReceived(result[2]); } break; case ChatCommand.LOGIN: callback.loggedIn(); break; case ChatCommand.QUIT: callback.loggedOut(); break; } } else { if (result.length == 3) { callback.error(result[2]); } } } public void sessionClosed(IoSession session) throws Exception { callback.disconnected(); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java0000644000175000017500000002163711002320032032016 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat.client; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.InetSocketAddress; import java.net.SocketAddress; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import org.apache.mina.example.chat.client.SwingChatClientHandler.Callback; import org.apache.mina.transport.socket.nio.SocketConnector; /** * Simple chat client based on Swing & MINA that implements the chat protocol. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class SwingChatClient extends JFrame implements Callback { private static final long serialVersionUID = 1538675161745436968L; private JTextField inputText; private JButton loginButton; private JButton quitButton; private JButton closeButton; private JTextField serverField; private JTextField nameField; private JTextArea area; private JScrollBar scroll; private ChatClientSupport client; private SwingChatClientHandler handler; private SocketConnector connector; public SwingChatClient() { super("Chat Client based on Apache MINA"); connector = new SocketConnector(); loginButton = new JButton(new LoginAction()); loginButton.setText("Connect"); quitButton = new JButton(new LogoutAction()); quitButton.setText("Disconnect"); closeButton = new JButton(new QuitAction()); closeButton.setText("Quit"); inputText = new JTextField(30); inputText.setAction(new BroadcastAction()); area = new JTextArea(10, 50); area.setLineWrap(true); area.setEditable(false); scroll = new JScrollBar(); scroll.add(area); nameField = new JTextField(10); nameField.setEditable(false); serverField = new JTextField(10); serverField.setEditable(false); JPanel h = new JPanel(); h.setLayout(new BoxLayout(h, BoxLayout.LINE_AXIS)); h.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JLabel nameLabel = new JLabel("Name: "); JLabel serverLabel = new JLabel("Server: "); h.add(nameLabel); h.add(Box.createRigidArea(new Dimension(10, 0))); h.add(nameField); h.add(Box.createRigidArea(new Dimension(10, 0))); h.add(Box.createHorizontalGlue()); h.add(Box.createRigidArea(new Dimension(10, 0))); h.add(serverLabel); h.add(Box.createRigidArea(new Dimension(10, 0))); h.add(serverField); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS)); p.setBorder(new EmptyBorder(10, 10, 10, 10)); JPanel left = new JPanel(); left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS)); left.add(area); left.add(Box.createRigidArea(new Dimension(0, 5))); left.add(Box.createHorizontalGlue()); left.add(inputText); JPanel right = new JPanel(); right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS)); right.add(loginButton); right.add(Box.createRigidArea(new Dimension(0, 5))); right.add(quitButton); right.add(Box.createHorizontalGlue()); right.add(Box.createRigidArea(new Dimension(0, 25))); right.add(closeButton); p.add(left); p.add(Box.createRigidArea(new Dimension(10, 0))); p.add(right); getContentPane().add(h, BorderLayout.NORTH); getContentPane().add(p); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); setLoggedOut(); setDefaultCloseOperation(EXIT_ON_CLOSE); } public class LoginAction extends AbstractAction { private static final long serialVersionUID = 3596719854773863244L; public void actionPerformed(ActionEvent e) { ConnectDialog dialog = new ConnectDialog(SwingChatClient.this); dialog.pack(); dialog.setVisible(true); if (dialog.isCancelled()) { return; } SocketAddress address = parseSocketAddress(dialog .getServerAddress()); String name = dialog.getUsername(); handler = new SwingChatClientHandler(SwingChatClient.this); client = new ChatClientSupport(name, handler); nameField.setText(name); serverField.setText(dialog.getServerAddress()); if (!client.connect(connector, address, dialog.isUseSsl())) { JOptionPane.showMessageDialog(SwingChatClient.this, "Could not connect to " + dialog.getServerAddress() + ". "); } } } private class LogoutAction extends AbstractAction { private static final long serialVersionUID = 1655297424639924560L; public void actionPerformed(ActionEvent e) { try { client.quit(); setLoggedOut(); } catch (Exception e1) { JOptionPane.showMessageDialog(SwingChatClient.this, "Session could not be closed."); } } } private class BroadcastAction extends AbstractAction { /** * */ private static final long serialVersionUID = -6276019615521905411L; public void actionPerformed(ActionEvent e) { client.broadcast(inputText.getText()); inputText.setText(""); } } private class QuitAction extends AbstractAction { private static final long serialVersionUID = -6389802816912005370L; public void actionPerformed(ActionEvent e) { if (client != null) { client.quit(); } SwingChatClient.this.dispose(); } } private void setLoggedOut() { inputText.setEnabled(false); quitButton.setEnabled(false); loginButton.setEnabled(true); } private void setLoggedIn() { area.setText(""); inputText.setEnabled(true); quitButton.setEnabled(true); loginButton.setEnabled(false); } private void append(String text) { area.append(text); } private void notifyError(String message) { JOptionPane.showMessageDialog(this, message); } private SocketAddress parseSocketAddress(String s) { s = s.trim(); int colonIndex = s.indexOf(":"); if (colonIndex > 0) { String host = s.substring(0, colonIndex); int port = parsePort(s.substring(colonIndex + 1)); return new InetSocketAddress(host, port); } else { int port = parsePort(s.substring(colonIndex + 1)); return new InetSocketAddress(port); } } private int parsePort(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Illegal port number: " + s); } } public void connected() { } public void disconnected() { append("Connection closed.\n"); setLoggedOut(); } public void error(String message) { notifyError(message + "\n"); } public void loggedIn() { setLoggedIn(); append("You have joined the chat session.\n"); } public void loggedOut() { append("You have left the chat session.\n"); setLoggedOut(); } public void messageReceived(String message) { append(message + "\n"); } public static void main(String[] args) { SwingChatClient client = new SwingChatClient(); client.pack(); client.setVisible(true); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java0000644000175000017500000000641211002320032032375 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat.client; import java.net.SocketAddress; import javax.net.ssl.SSLContext; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; import org.apache.mina.filter.SSLFilter; import org.apache.mina.transport.socket.nio.SocketConnector; import org.apache.mina.transport.socket.nio.SocketConnectorConfig; /** * A simple chat client for a given user. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class ChatClientSupport { private final IoHandler handler; private final String name; private IoSession session; public ChatClientSupport(String name, IoHandler handler) { if (name == null) { throw new IllegalArgumentException("Name can not be null"); } this.name = name; this.handler = handler; } public boolean connect(SocketConnector connector, SocketAddress address, boolean useSsl) { if (session != null && session.isConnected()) { throw new IllegalStateException( "Already connected. Disconnect first."); } try { SocketConnectorConfig config = new SocketConnectorConfig(); if (useSsl) { SSLContext sslContext = BogusSSLContextFactory .getInstance(false); SSLFilter sslFilter = new SSLFilter(sslContext); sslFilter.setUseClientMode(true); config.getFilterChain().addLast("sslFilter", sslFilter); } ConnectFuture future1 = connector.connect(address, handler, config); future1.join(); if (!future1.isConnected()) { return false; } session = future1.getSession(); session.write("LOGIN " + name); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public void broadcast(String message) { session.write("BROADCAST " + message); } public void quit() { if (session != null) { if (session.isConnected()) { session.write("QUIT"); // Wait until the chat ends. session.getCloseFuture().join(); } session.close(); } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/client/ConnectDialog.java0000644000175000017500000000675311002320032031503 0ustar drazzibdrazzib/* * @(#) $Id: ConnectDialog.java 555855 2007-07-13 03:19:00Z trustin $ * * Copyright 2006 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.mina.example.chat.client; import java.awt.BorderLayout; import java.awt.Frame; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ * */ public class ConnectDialog extends JDialog { private static final long serialVersionUID = 2009384520250666216L; private String serverAddress; private String username; private boolean useSsl; private boolean cancelled = false; public ConnectDialog(Frame owner) throws HeadlessException { super(owner, "Connect", true); serverAddress = "localhost:1234"; username = "user" + Math.round(Math.random() * 10); final JTextField serverAddressField = new JTextField(serverAddress); final JTextField usernameField = new JTextField(username); final JCheckBox useSslCheckBox = new JCheckBox("Use SSL", false); JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS)); content.add(new JLabel("Server address")); content.add(serverAddressField); content.add(new JLabel("Username")); content.add(usernameField); content.add(useSslCheckBox); JButton okButton = new JButton(); okButton.setAction(new AbstractAction("OK") { private static final long serialVersionUID = -2292183622613960604L; public void actionPerformed(ActionEvent e) { serverAddress = serverAddressField.getText(); username = usernameField.getText(); useSsl = useSslCheckBox.isSelected(); ConnectDialog.this.dispose(); } }); JButton cancelButton = new JButton(); cancelButton.setAction(new AbstractAction("Cancel") { private static final long serialVersionUID = 6122393546173723305L; public void actionPerformed(ActionEvent e) { cancelled = true; ConnectDialog.this.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(okButton); buttons.add(cancelButton); getContentPane().add(content, BorderLayout.CENTER); getContentPane().add(buttons, BorderLayout.SOUTH); } public boolean isCancelled() { return cancelled; } public String getServerAddress() { return serverAddress; } public String getUsername() { return username; } public boolean isUseSsl() { return useSsl; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java0000644000175000017500000000342511002320032027663 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat; /** * Encapsulates a chat command. Use {@link #valueOf(String)} to create an * instance given a command string. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class ChatCommand { public static final int LOGIN = 0; public static final int QUIT = 1; public static final int BROADCAST = 2; private final int num; private ChatCommand(int num) { this.num = num; } public int toInt() { return num; } public static ChatCommand valueOf(String s) { s = s.toUpperCase(); if ("LOGIN".equals(s)) { return new ChatCommand(LOGIN); } if ("QUIT".equals(s)) { return new ChatCommand(QUIT); } if ("BROADCAST".equals(s)) { return new ChatCommand(BROADCAST); } throw new IllegalArgumentException("Unrecognized command: " + s); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/chat/Main.java0000644000175000017500000000570011002320032026367 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.chat; import java.net.InetSocketAddress; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.SSLFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; /** * (Entry point) Chat server * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class Main { /** Choose your favorite port number. */ private static final int PORT = 1234; /** Set this to true if you want to make the server SSL */ private static final boolean USE_SSL = false; public static void main(String[] args) throws Exception { IoAcceptor acceptor = new SocketAcceptor(); IoAcceptorConfig config = new SocketAcceptorConfig(); DefaultIoFilterChainBuilder chain = config.getFilterChain(); // Add SSL filter if SSL is enabled. if (USE_SSL) { addSSLSupport(chain); } chain.addLast("codec", new ProtocolCodecFilter( new TextLineCodecFactory())); addLogger(chain); // Bind acceptor.bind(new InetSocketAddress(PORT), new ChatProtocolHandler(), config); System.out.println("Listening on port " + PORT); } private static void addSSLSupport(DefaultIoFilterChainBuilder chain) throws Exception { SSLFilter sslFilter = new SSLFilter(BogusSSLContextFactory .getInstance(true)); chain.addLast("sslFilter", sslFilter); System.out.println("SSL ON"); } private static void addLogger(DefaultIoFilterChainBuilder chain) throws Exception { chain.addLast("logger", new LoggingFilter()); System.out.println("Logging ON"); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/proxy/0000755000175000017500000000000011044712500025113 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/proxy/package.html0000644000175000017500000000023011002320032027354 0ustar drazzibdrazzib A TCP/IP tunneling proxy example. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/proxy/ClientToProxyIoHandler.java0000644000175000017500000000532211002320032032316 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.proxy; import java.net.InetSocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoFuture; import org.apache.mina.common.IoFutureListener; import org.apache.mina.common.IoSession; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.TrafficMask; /** * Handles the client to proxy part of the proxied connection. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ * */ public class ClientToProxyIoHandler extends AbstractProxyIoHandler { private final ServerToProxyIoHandler connectorHandler; private final IoConnector connector; private final InetSocketAddress address; public ClientToProxyIoHandler(ServerToProxyIoHandler connectorHandler, IoConnector connector, InetSocketAddress address) { this.connectorHandler = connectorHandler; this.connector = connector; this.address = address; } public void sessionOpened(final IoSession session) throws Exception { connector.connect(address, connectorHandler).addListener( new IoFutureListener() { public void operationComplete(IoFuture f) { ConnectFuture future = (ConnectFuture) f; try { future.getSession().setAttachment(session); session.setAttachment(future.getSession()); future.getSession().setTrafficMask(TrafficMask.ALL); } catch (RuntimeIOException e) { // Connect failed session.close(); } finally { session.setTrafficMask(TrafficMask.ALL); } } }); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/proxy/ServerToProxyIoHandler.java0000644000175000017500000000213611002320032032346 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.proxy; /** * Handles the server to proxy part of the proxied connection. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ * */ public class ServerToProxyIoHandler extends AbstractProxyIoHandler { } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/proxy/AbstractProxyIoHandler.java0000644000175000017500000000442311002320032032341 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.proxy; import java.nio.charset.Charset; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.TrafficMask; import org.apache.mina.util.SessionLog; /** * Base class of {@link org.apache.mina.common.IoHandler} classes which handle * proxied connections. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ * */ public abstract class AbstractProxyIoHandler extends IoHandlerAdapter { private static Charset CHARSET = Charset.forName("iso8859-1"); public void sessionCreated(IoSession session) throws Exception { session.setTrafficMask(TrafficMask.NONE); } public void sessionClosed(IoSession session) throws Exception { if (session.getAttachment() != null) { ((IoSession) session.getAttachment()).setAttachment(null); ((IoSession) session.getAttachment()).close(); session.setAttachment(null); } } public void messageReceived(IoSession session, Object message) throws Exception { ByteBuffer rb = (ByteBuffer) message; ByteBuffer wb = ByteBuffer.allocate(rb.remaining()); rb.mark(); wb.put(rb); wb.flip(); ((IoSession) session.getAttachment()).write(wb); rb.reset(); SessionLog.info(session, rb.getString(CHARSET.newDecoder())); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/proxy/Main.java0000644000175000017500000000557611002320032026644 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.proxy; import java.net.InetSocketAddress; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoConnectorConfig; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.apache.mina.transport.socket.nio.SocketConnector; /** * (Entry point) Demonstrates how to write a very simple tunneling proxy * using MINA. The proxy only logs all data passing through it. This is only * suitable for text based protocols since received data will be converted into * strings before being logged. *

* Start a proxy like this:
* org.apache.mina.example.proxy.Main 12345 www.google.com 80
* and open http://localhost:12345 in a * browser window. *

* * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class Main { public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println(Main.class.getName() + " "); return; } // Create TCP/IP acceptor. IoAcceptor acceptor = new SocketAcceptor(); ((SocketAcceptorConfig) acceptor.getDefaultConfig()) .setReuseAddress(true); // Create TCP/IP connector. IoConnector connector = new SocketConnector(); // Set connect timeout. ((IoConnectorConfig) connector.getDefaultConfig()) .setConnectTimeout(30); ClientToProxyIoHandler handler = new ClientToProxyIoHandler( new ServerToProxyIoHandler(), connector, new InetSocketAddress( args[1], Integer.parseInt(args[2]))); // Start proxy. acceptor .bind(new InetSocketAddress(Integer.parseInt(args[0])), handler); System.out.println("Listening on port " + Integer.parseInt(args[0])); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/0000755000175000017500000000000011044712500025033 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/ToHaikuIoFilter.java0000644000175000017500000000340511002320032030667 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import java.util.ArrayList; import java.util.List; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class ToHaikuIoFilter extends IoFilterAdapter { @SuppressWarnings( { "unchecked" }) @Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { List phrases = (List) session.getAttribute("phrases"); if (null == phrases) { phrases = new ArrayList(); session.setAttribute("phrases", phrases); } phrases.add((String) message); if (phrases.size() == 3) { session.removeAttribute("phrases"); super.messageReceived(nextFilter, session, new Haiku(phrases .toArray(new String[3]))); } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/PhraseUtilities.java0000644000175000017500000000340511002320032031003 0ustar drazzibdrazzibpackage org.apache.mina.example.haiku; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class PhraseUtilities { static int countSyllablesInPhrase(String phrase) { int syllables = 0; for (String word : phrase.split("[^\\w-]+")) { if (word.length() > 0) { syllables += countSyllablesInWord(word.toLowerCase()); } } return syllables; } static int countSyllablesInWord(String word) { char[] chars = word.toCharArray(); int syllables = 0; boolean lastWasVowel = false; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (isVowel(c)) { if (!lastWasVowel || (i > 0 && isE(chars, i - 1) && isO(chars, i))) { ++syllables; lastWasVowel = true; } } else { lastWasVowel = false; } } if (word.endsWith("oned") || word.endsWith("ne") || word.endsWith("ide") || word.endsWith("ve") || word.endsWith("fe") || word.endsWith("nes") || word.endsWith("mes")) { --syllables; } return syllables; } static boolean isE(char[] chars, int position) { return isCharacter(chars, position, 'e'); } static boolean isCharacter(char[] chars, int position, char c) { return chars[position] == c; } static boolean isO(char[] chars, int position) { return isCharacter(chars, position, 'o'); } static boolean isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y'; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/Haiku.java0000644000175000017500000000334411002320032026730 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import java.util.Arrays; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class Haiku { private final String[] phrases; public Haiku(String... lines) { this.phrases = lines; if (null == lines || lines.length != 3) { throw new IllegalArgumentException("Must pass in 3 phrases of text"); } } public String[] getPhrases() { return phrases; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Haiku haiku = (Haiku) o; return Arrays.equals(phrases, haiku.phrases); } @Override public int hashCode() { return Arrays.hashCode(phrases); } @Override public String toString() { return Arrays.toString(phrases); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/InvalidHaikuException.java0000644000175000017500000000363611002320032032122 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class InvalidHaikuException extends Exception { private static final long serialVersionUID = 34877739006797894L; private final int position; private final String phrase; private final int syllableCount; private final int expectedSyllableCount; public InvalidHaikuException(int position, String phrase, int syllableCount, int expectedSyllableCount) { super("phrase " + position + ", '" + phrase + "' had " + syllableCount + " syllables, not " + expectedSyllableCount); this.position = position; this.phrase = phrase; this.syllableCount = syllableCount; this.expectedSyllableCount = expectedSyllableCount; } public int getExpectedSyllableCount() { return expectedSyllableCount; } public String getPhrase() { return phrase; } public int getSyllableCount() { return syllableCount; } public int getPhrasePosition() { return position; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/HaikuValidatorIoHandler.java0000644000175000017500000000277111002320032032367 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class HaikuValidatorIoHandler extends IoHandlerAdapter { private final HaikuValidator validator = new HaikuValidator(); @Override public void messageReceived(IoSession session, Object message) throws Exception { Haiku haiku = (Haiku) message; try { validator.validate(haiku); session.write("HAIKU!"); } catch (InvalidHaikuException e) { session.write("NOT A HAIKU: " + e.getMessage()); } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/HaikuValidationServer.java0000644000175000017500000000430511002320032032130 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.filter.executor.ExecutorFilter; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class HaikuValidationServer { public static void main(String... args) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); SocketAcceptor acceptor = new SocketAcceptor(Runtime.getRuntime() .availableProcessors(), executor); SocketAcceptorConfig config = new SocketAcceptorConfig(); config.getFilterChain().addLast("executor", new ExecutorFilter(executor)); config.getFilterChain().addLast( "to-string", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("US-ASCII")))); config.getFilterChain().addLast("to-haiki", new ToHaikuIoFilter()); acceptor.bind(new InetSocketAddress(42458), new HaikuValidatorIoHandler(), config); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/haiku/HaikuValidator.java0000644000175000017500000000274411002320032030601 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class HaikuValidator { private static final int[] SYLLABLE_COUNTS = { 5, 7, 5 }; public void validate(Haiku haiku) throws InvalidHaikuException { String[] phrases = haiku.getPhrases(); for (int i = 0; i < phrases.length; i++) { String phrase = phrases[i]; int count = PhraseUtilities.countSyllablesInPhrase(phrase); if (count != SYLLABLE_COUNTS[i]) { throw new InvalidHaikuException(i + 1, phrase, count, SYLLABLE_COUNTS[i]); } } } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/netcat/0000755000175000017500000000000011044712500025210 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/netcat/package.html0000644000175000017500000000032511002320032027456 0ustar drazzibdrazzib NetCat client (Network + Unix cat command) which demonstates low-level I/O layer. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/netcat/NetCatProtocolHandler.java0000644000175000017500000000453111002320032032241 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.netcat; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; /** * {@link IoHandler} implementation for NetCat client. This class extended * {@link IoHandlerAdapter} for convenience. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class NetCatProtocolHandler extends IoHandlerAdapter { public void sessionOpened(IoSession session) { // Set reader idle time to 10 seconds. // sessionIdle(...) method will be invoked when no data is read // for 10 seconds. session.setIdleTime(IdleStatus.READER_IDLE, 10); } public void sessionClosed(IoSession session) { // Print out total number of bytes read from the remote peer. System.err.println("Total " + session.getReadBytes() + " byte(s)"); } public void sessionIdle(IoSession session, IdleStatus status) { // Close the connection if reader is idle. if (status == IdleStatus.READER_IDLE) session.close(); } public void messageReceived(IoSession session, Object message) { ByteBuffer buf = (ByteBuffer) message; // Print out read buffer content. while (buf.hasRemaining()) { System.out.print((char) buf.get()); } System.out.flush(); } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/netcat/Main.java0000644000175000017500000000421511002320032026726 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.netcat; import java.net.InetSocketAddress; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnectorConfig; import org.apache.mina.transport.socket.nio.SocketConnector; /** * (Entry point) NetCat client. NetCat client connects to the specified * endpoint and prints out received data. NetCat client disconnects * automatically when no data is read for 10 seconds. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 575220 $, $Date: 2007-09-13 17:45:03 +0900 (Thu, 13 Sep 2007) $, */ public class Main { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println(Main.class.getName() + " "); return; } // Create TCP/IP connector. SocketConnector connector = new SocketConnector(); // Set connect timeout. ((IoConnectorConfig) connector.getDefaultConfig()) .setConnectTimeout(15); // Start communication. ConnectFuture cf = connector.connect(new InetSocketAddress( args[0], Integer.parseInt(args[1])), new NetCatProtocolHandler()); // Wait for the connection attempt to be finished. cf.join(); cf.getSession(); } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/0000755000175000017500000000000011044712500026077 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/package.html0000644000175000017500000000026011002320032030343 0ustar drazzibdrazzib Echo server which demonstates low-level I/O layer and SSL support. mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/0000755000175000017500000000000011044712500026700 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/package.html0000644000175000017500000000020211002320032031140 0ustar drazzibdrazzib SSL support classes. ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/BogusTrustManagerFactory.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/BogusTrustManagerFactor0000644000175000017500000000471111002320032033366 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver.ssl; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactorySpi; import javax.net.ssl.X509TrustManager; /** * Bogus trust manager factory. Creates BogusX509TrustManager * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ class BogusTrustManagerFactory extends TrustManagerFactorySpi { static final X509TrustManager X509 = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; static final TrustManager[] X509_MANAGERS = new TrustManager[] { X509 }; public BogusTrustManagerFactory() { } protected TrustManager[] engineGetTrustManagers() { return X509_MANAGERS; } protected void engineInit(KeyStore keystore) throws KeyStoreException { // noop } protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException { // noop } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/BogusSSLContextFactory.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/BogusSSLContextFactory.0000644000175000017500000001172011002320032033225 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver.ssl; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.Security; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; /** * Factory to create a bougus SSLContext. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class BogusSSLContextFactory { /** * Protocol to use. */ private static final String PROTOCOL = "TLS"; private static final String KEY_MANAGER_FACTORY_ALGORITHM; static { String algorithm = Security .getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } KEY_MANAGER_FACTORY_ALGORITHM = algorithm; } /** * Bougus Server certificate keystore file name. */ private static final String BOGUS_KEYSTORE = "bogus.cert"; // NOTE: The keystore was generated using keytool: // keytool -genkey -alias bogus -keysize 512 -validity 3650 // -keyalg RSA -dname "CN=bogus.com, OU=XXX CA, // O=Bogus Inc, L=Stockholm, S=Stockholm, C=SE" // -keypass boguspw -storepass boguspw -keystore bogus.cert /** * Bougus keystore password. */ private static final char[] BOGUS_PW = { 'b', 'o', 'g', 'u', 's', 'p', 'w' }; private static SSLContext serverInstance = null; private static SSLContext clientInstance = null; /** * Get SSLContext singleton. * * @return SSLContext * @throws java.security.GeneralSecurityException * */ public static SSLContext getInstance(boolean server) throws GeneralSecurityException { SSLContext retInstance = null; if (server) { if (serverInstance == null) { synchronized (BogusSSLContextFactory.class) { if (serverInstance == null) { try { serverInstance = createBougusServerSSLContext(); } catch (Exception ioe) { throw new GeneralSecurityException( "Can't create Server SSLContext:" + ioe); } } } } retInstance = serverInstance; } else { if (clientInstance == null) { synchronized (BogusSSLContextFactory.class) { if (clientInstance == null) { clientInstance = createBougusClientSSLContext(); } } } retInstance = clientInstance; } return retInstance; } private static SSLContext createBougusServerSSLContext() throws GeneralSecurityException, IOException { // Create keystore KeyStore ks = KeyStore.getInstance("JKS"); InputStream in = null; try { in = BogusSSLContextFactory.class .getResourceAsStream(BOGUS_KEYSTORE); ks.load(in, BOGUS_PW); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory .getInstance(KEY_MANAGER_FACTORY_ALGORITHM); kmf.init(ks, BOGUS_PW); // Initialize the SSLContext to work with our key managers. SSLContext sslContext = SSLContext.getInstance(PROTOCOL); sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); return sslContext; } private static SSLContext createBougusClientSSLContext() throws GeneralSecurityException { SSLContext context = SSLContext.getInstance(PROTOCOL); context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null); return context; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootmina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/SSLServerSocketFactory.javamina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/SSLServerSocketFactory.0000644000175000017500000000607111002320032033223 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver.ssl; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.security.GeneralSecurityException; import javax.net.ServerSocketFactory; /** * Simple Server Socket factory to create sockets with or without SSL enabled. * If SSL enabled a "bougus" SSL Context is used (suitable for test purposes) * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SSLServerSocketFactory extends javax.net.ServerSocketFactory { private static boolean sslEnabled = false; private static javax.net.ServerSocketFactory sslFactory = null; private static ServerSocketFactory factory = null; public SSLServerSocketFactory() { super(); } public ServerSocket createServerSocket(int port) throws IOException { return new ServerSocket(port); } public ServerSocket createServerSocket(int port, int backlog) throws IOException { return new ServerSocket(port, backlog); } public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { return new ServerSocket(port, backlog, ifAddress); } public static javax.net.ServerSocketFactory getServerSocketFactory() throws IOException { if (isSslEnabled()) { if (sslFactory == null) { try { sslFactory = BogusSSLContextFactory.getInstance(true) .getServerSocketFactory(); } catch (GeneralSecurityException e) { IOException ioe = new IOException( "could not create SSL socket"); ioe.initCause(e); throw ioe; } } return sslFactory; } else { if (factory == null) { factory = new SSLServerSocketFactory(); } return factory; } } public static boolean isSslEnabled() { return sslEnabled; } public static void setSslEnabled(boolean newSslEnabled) { sslEnabled = newSslEnabled; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/ssl/SSLSocketFactory.java0000644000175000017500000000706011002320032032675 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver.ssl; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import javax.net.SocketFactory; /** * Simple Socket factory to create sockets with or without SSL enabled. * If SSL enabled a "bougus" SSL Context is used (suitable for test purposes) * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class SSLSocketFactory extends SocketFactory { private static boolean sslEnabled = false; private static javax.net.ssl.SSLSocketFactory sslFactory = null; private static javax.net.SocketFactory factory = null; public SSLSocketFactory() { super(); } public Socket createSocket(String arg1, int arg2) throws IOException, UnknownHostException { if (isSslEnabled()) { return getSSLFactory().createSocket(arg1, arg2); } else { return new Socket(arg1, arg2); } } public Socket createSocket(String arg1, int arg2, InetAddress arg3, int arg4) throws IOException, UnknownHostException { if (isSslEnabled()) { return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); } else { return new Socket(arg1, arg2, arg3, arg4); } } public Socket createSocket(InetAddress arg1, int arg2) throws IOException { if (isSslEnabled()) { return getSSLFactory().createSocket(arg1, arg2); } else { return new Socket(arg1, arg2); } } public Socket createSocket(InetAddress arg1, int arg2, InetAddress arg3, int arg4) throws IOException { if (isSslEnabled()) { return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); } else { return new Socket(arg1, arg2, arg3, arg4); } } public static javax.net.SocketFactory getSocketFactory() { if (factory == null) { factory = new SSLSocketFactory(); } return factory; } private javax.net.ssl.SSLSocketFactory getSSLFactory() { if (sslFactory == null) { try { sslFactory = BogusSSLContextFactory.getInstance(false) .getSocketFactory(); } catch (GeneralSecurityException e) { throw new RuntimeException("could not create SSL socket", e); } } return sslFactory; } public static boolean isSslEnabled() { return sslEnabled; } public static void setSslEnabled(boolean newSslEnabled) { sslEnabled = newSslEnabled; } } mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/EchoProtocolHandler.java0000644000175000017500000000541011002320032032625 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.TransportType; import org.apache.mina.filter.SSLFilter; import org.apache.mina.transport.socket.nio.SocketSessionConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link IoHandler} implementation for echo server. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $, */ public class EchoProtocolHandler extends IoHandlerAdapter { private static final Logger log = LoggerFactory .getLogger(EchoProtocolHandler.class); public void sessionCreated(IoSession session) { if (session.getTransportType() == TransportType.SOCKET) { ((SocketSessionConfig) session.getConfig()) .setReceiveBufferSize(2048); } session.setIdleTime(IdleStatus.BOTH_IDLE, 10); // We're going to use SSL negotiation notification. session.setAttribute(SSLFilter.USE_NOTIFICATION); } public void sessionIdle(IoSession session, IdleStatus status) { log.info("*** IDLE #" + session.getIdleCount(IdleStatus.BOTH_IDLE) + " ***"); } public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); session.close(); } public void messageReceived(IoSession session, Object message) throws Exception { if (!(message instanceof ByteBuffer)) { return; } ByteBuffer rb = (ByteBuffer) message; // Write the received data back to remote peer ByteBuffer wb = ByteBuffer.allocate(rb.remaining()); wb.put(rb); wb.flip(); session.write(wb); } }mina-1.1.7.dfsg/example/src/main/java/org/apache/mina/example/echoserver/Main.java0000644000175000017500000000543311002320032027620 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver; import java.net.InetSocketAddress; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.SSLFilter; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; /** * (Entry point) Echo server * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $ */ public class Main { /** Choose your favorite port number. */ private static final int PORT = 8080; /** Set this to true if you want to make the server SSL */ private static final boolean USE_SSL = false; public static void main(String[] args) throws Exception { IoAcceptor acceptor = new SocketAcceptor(); IoAcceptorConfig config = new SocketAcceptorConfig(); DefaultIoFilterChainBuilder chain = config.getFilterChain(); // Add SSL filter if SSL is enabled. if (USE_SSL) { addSSLSupport(chain); } addLogger(chain); // Bind acceptor.bind(new InetSocketAddress(PORT), new EchoProtocolHandler(), config); System.out.println("Listening on port " + PORT); } private static void addSSLSupport(DefaultIoFilterChainBuilder chain) throws Exception { SSLFilter sslFilter = new SSLFilter(BogusSSLContextFactory .getInstance(true)); chain.addLast("sslFilter", sslFilter); System.out.println("SSL ON"); } private static void addLogger(DefaultIoFilterChainBuilder chain) throws Exception { chain.addLast("logger", new LoggingFilter()); System.out.println("Logging ON"); } } mina-1.1.7.dfsg/example/src/test/0000755000175000017500000000000011002320031016441 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/0000755000175000017500000000000011002320031017362 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/0000755000175000017500000000000011002320031020151 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/0000755000175000017500000000000011002320031021372 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/0000755000175000017500000000000011002320031022316 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/0000755000175000017500000000000011002320031023751 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/haiku/0000755000175000017500000000000011044712500025066 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/haiku/HaikuValidatorTest.java0000644000175000017500000000554711002320031031477 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import junit.framework.TestCase; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class HaikuValidatorTest extends TestCase { // from http://allrileyedup.blogspot.com/2006/10/dont-hassle-haiku.html -- good friend of proyal@apache.org private static final String[] HAIKUS = { "This class is boring.\n" + "Will David ever shut up?\n" + "What is Steph wearing?", "Oh, I drank too much.\n" + "Why, oh why did I sign up\n" + "For an eight thirty?", "Which one should I do?\n" + "Wax my chest or perm my hair?\n" + "Can’t wait to decide.", "Watch my video.\n" + "I can't stop this fee-ee-ling!\n" + "What is wrong with me?", "The car chases me.\n" + "I must get away from it.\n" + "Turbo Boost! Oh, yeah.", "My new slogan is\n" + "Don't hassle me... I'm oiling.\n" + "You know it’s so true.", "Michael, I love you.\n" + "I long for you to tell me\n" + "\"KITT, need you buddy.\"", "In Knight Rider, I’m\n" + "A Man Who Does Not Exist.\n" + "(Except in your dreams).", "Yes, I’m Michael Knight\n" + "Check out my unbuttoned shirt.\n" + "And sexy tight pants.", "My bitch ex-wife sucks.\n" + "And so do all the airlines.\n" + "I miss Knight Rider.", "I am Michael Knight.\n" + "I am David Hasselhoff.\n" + "I’m not Rick James, bitch." }; private HaikuValidator validator; @Override protected void setUp() throws Exception { super.setUp(); validator = new HaikuValidator(); } public void testValidateHaikus() throws Exception { for (String s : HAIKUS) { String[] lines = s.split("\n"); Haiku haiku = new Haiku(lines); validator.validate(haiku); } } } mina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/haiku/PhraseUtilitiesTest.java0000644000175000017500000000516711002320031031704 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import junit.framework.TestCase; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class PhraseUtilitiesTest extends TestCase { public void testCountSyllablesInWord() throws Exception { assertSyllableCount(1, "one"); assertSyllableCount(1, "I"); assertSyllableCount(1, "too"); assertSyllableCount(1, "why"); assertSyllableCount(1, "oh"); assertSyllableCount(1, "did"); assertSyllableCount(1, "sign"); assertSyllableCount(1, "up"); assertSyllableCount(1, "watch"); assertSyllableCount(1, "my"); assertSyllableCount(1, "what"); assertSyllableCount(1, "is"); assertSyllableCount(1, "wrong"); assertSyllableCount(1, "with"); assertSyllableCount(1, "me"); assertSyllableCount(1, "don't"); assertSyllableCount(1, "you"); assertSyllableCount(1, "love"); assertSyllableCount(2, "hassle"); assertSyllableCount(2, "oiling"); assertSyllableCount(2, "decide"); assertSyllableCount(2, "Michael"); assertSyllableCount(1, "I'm"); assertSyllableCount(1, "check"); assertSyllableCount(1, "out"); assertSyllableCount(1, "shirt"); assertSyllableCount(1, "bitch"); assertSyllableCount(1, "sucks"); assertSyllableCount(1, "James"); assertSyllableCount(2, "ex-wife"); assertSyllableCount(2, "airlines"); assertSyllableCount(3, "video"); assertSyllableCount(3, "fee-ee-ling"); assertSyllableCount(3, "unbuttoned"); } private static void assertSyllableCount(int count, String word) { assertEquals("syllables in " + word, count, PhraseUtilities .countSyllablesInWord(word.toLowerCase())); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/haiku/HaikuValidatorIoHandlerTest.javamina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/haiku/HaikuValidatorIoHandlerTest.java0000644000175000017500000000412211002320031033251 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; import org.jmock.Mock; import org.jmock.MockObjectTestCase; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class HaikuValidatorIoHandlerTest extends MockObjectTestCase { private IoHandler handler; @Override protected void setUp() throws Exception { super.setUp(); handler = new HaikuValidatorIoHandler(); } public void testValidHaiku() throws Exception { Mock session = mock(IoSession.class); session.expects(once()).method("write").with(eq("HAIKU!")); IoSession sessionProxy = (IoSession) session.proxy(); handler.messageReceived(sessionProxy, new Haiku( "Oh, I drank too much.", "Why, oh why did I sign up", "For an eight thirty?")); } public void testInvalidHaiku() throws Exception { Mock session = mock(IoSession.class); session.expects(once()).method("write").with( eq("NOT A HAIKU: phrase 1, 'foo' had 1 syllables, not 5")); IoSession sessionProxy = (IoSession) session.proxy(); handler.messageReceived(sessionProxy, new Haiku("foo", "a haiku", "poo")); } } mina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/haiku/ToHaikuIoFilterTest.java0000644000175000017500000000605111002320031031561 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.mina.example.haiku; import java.util.Collections; import java.util.List; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoSession; import org.jmock.Mock; import org.jmock.MockObjectTestCase; /** * @author Apache Mina Project (dev@mina.apache.org) * @version $Rev: $, $Date: $ */ public class ToHaikuIoFilterTest extends MockObjectTestCase { private IoFilter filter; @Override protected void setUp() throws Exception { super.setUp(); filter = new ToHaikuIoFilter(); } public void testThreeStringsMakesAHaiku() throws Exception { Mock list = mock(List.class); list.expects(once()).method("add").with(eq("two")).will( returnValue(true)); list.expects(once()).method("add").with(eq("three")).will( returnValue(true)); list.expects(once()).method("toArray").with(isA(String[].class)).will( returnValue(new String[] { "one", "two", "three" })); list.expects(exactly(2)).method("size").will( onConsecutiveCalls(returnValue(2), returnValue(3))); Mock session = mock(IoSession.class); session.expects(exactly(3)).method("getAttribute").with(eq("phrases")) .will( onConsecutiveCalls(returnValue(null), returnValue(list .proxy()), returnValue(list.proxy()), returnValue(list.proxy()))); session.expects(exactly(1)).method("setAttribute").with(eq("phrases"), eq(Collections.emptyList())); session.expects(exactly(1)).method("removeAttribute").with( eq("phrases")); IoSession sessionProxy = (IoSession) session.proxy(); Mock nextFilter = mock(IoFilter.NextFilter.class); nextFilter.expects(once()).method("messageReceived").with( eq(sessionProxy), eq(new Haiku("one", "two", "three"))); IoFilter.NextFilter nextFilterProxy = (IoFilter.NextFilter) nextFilter .proxy(); filter.messageReceived(nextFilterProxy, sessionProxy, "one"); filter.messageReceived(nextFilterProxy, sessionProxy, "two"); filter.messageReceived(nextFilterProxy, sessionProxy, "three"); } } mina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/echoserver/0000755000175000017500000000000011044712500026132 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/echoserver/ConnectorTest.java0000644000175000017500000002045111002320032031556 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver; import java.net.InetSocketAddress; import junit.framework.Assert; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.IoConnector; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.RuntimeIOException; import org.apache.mina.common.WriteFuture; import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; import org.apache.mina.filter.SSLFilter; import org.apache.mina.transport.socket.nio.DatagramConnector; import org.apache.mina.transport.socket.nio.SocketConnector; import org.apache.mina.util.AvailablePortFinder; import org.apache.mina.util.SessionLog; /** * Tests echo server example. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev:448075 $, $Date:2006-09-20 05:26:53Z $ */ public class ConnectorTest extends AbstractTest { private static final int TIMEOUT = 10000; // 10 seconds private final int COUNT = 10; private final int DATA_SIZE = 16; private SSLFilter connectorSSLFilter; public ConnectorTest() { } protected void setUp() throws Exception { super.setUp(); connectorSSLFilter = new SSLFilter(BogusSSLContextFactory .getInstance(false)); connectorSSLFilter.setUseClientMode(true); // set client mode } public void testTCP() throws Exception { IoConnector connector = new SocketConnector(); testConnector(connector); } public void testTCPWithSSL() throws Exception { useSSL = true; // Create a connector IoConnector connector = new SocketConnector(); // Add an SSL filter to connector connector.getDefaultConfig().getFilterChain().addLast("SSL", connectorSSLFilter); testConnector(connector); } public void testUDP() throws Exception { IoConnector connector = new DatagramConnector(); testConnector(connector); } private void testConnector(IoConnector connector) throws Exception { System.out.println("* Without localAddress"); testConnector(connector, false); System.out.println("* With localAddress"); testConnector(connector, true); } private void testConnector(IoConnector connector, boolean useLocalAddress) throws Exception { EchoConnectorHandler handler = new EchoConnectorHandler(); IoSession session = null; if (!useLocalAddress) { ConnectFuture future = connector.connect(new InetSocketAddress( "localhost", port), handler); future.join(); session = future.getSession(); } else { int clientPort = port; for (int i = 0; i < 65536; i++) { clientPort = AvailablePortFinder .getNextAvailable(clientPort + 1); try { ConnectFuture future = connector.connect( new InetSocketAddress("localhost", port), new InetSocketAddress(clientPort), handler); future.join(); session = future.getSession(); break; } catch (RuntimeIOException e) { // Try again until we succeed to bind. } } if (session == null) { Assert.fail("Failed to find out an appropriate local address."); } } // Run a basic connector test. testConnector0(session); // Send closeNotify to test TLS closure if it is TLS connection. if (useSSL) { connectorSSLFilter.stopSSL(session).join(); System.out .println("-------------------------------------------------------------------------------"); // Test again after we finished TLS session. testConnector0(session); System.out .println("-------------------------------------------------------------------------------"); // Test if we can enter TLS mode again. //// Send StartTLS request. handler.readBuf.clear(); ByteBuffer buf = ByteBuffer.allocate(1); buf.put((byte) '.'); buf.flip(); session.write(buf).join(); //// Wait for StartTLS response. waitForResponse(handler, 1); handler.readBuf.flip(); Assert.assertEquals(1, handler.readBuf.remaining()); Assert.assertEquals((byte) '.', handler.readBuf.get()); // Now start TLS connection Assert.assertTrue(connectorSSLFilter.startSSL(session)); testConnector0(session); } session.close().join(); } private void testConnector0(IoSession session) throws InterruptedException { EchoConnectorHandler handler = (EchoConnectorHandler) session .getHandler(); ByteBuffer readBuf = handler.readBuf; readBuf.clear(); WriteFuture writeFuture = null; for (int i = 0; i < COUNT; i++) { ByteBuffer buf = ByteBuffer.allocate(DATA_SIZE); buf.limit(DATA_SIZE); fillWriteBuffer(buf, i); buf.flip(); writeFuture = session.write(buf); if (session.getTransportType().isConnectionless()) { // This will align message arrival order in connectionless transport types waitForResponse(handler, (i + 1) * DATA_SIZE); } } writeFuture.join(); waitForResponse(handler, DATA_SIZE * COUNT); // Assert data //// Please note that BufferOverflowException can be thrown //// in SocketIoProcessor if there was a read timeout because //// we share readBuf. readBuf.flip(); SessionLog.info(session, "readBuf: " + readBuf); Assert.assertEquals(DATA_SIZE * COUNT, readBuf.remaining()); ByteBuffer expectedBuf = ByteBuffer.allocate(DATA_SIZE * COUNT); for (int i = 0; i < COUNT; i++) { expectedBuf.limit((i + 1) * DATA_SIZE); fillWriteBuffer(expectedBuf, i); } expectedBuf.position(0); assertEquals(expectedBuf, readBuf); } private void waitForResponse(EchoConnectorHandler handler, int bytes) throws InterruptedException { for (int j = 0; j < TIMEOUT / 10; j++) { if (handler.readBuf.position() >= bytes) { break; } Thread.sleep(10); } Assert.assertEquals(bytes, handler.readBuf.position()); } private void fillWriteBuffer(ByteBuffer writeBuf, int i) { while (writeBuf.remaining() > 0) { writeBuf.put((byte) (i++)); } } public static void main(String[] args) { junit.textui.TestRunner.run(ConnectorTest.class); } private static class EchoConnectorHandler extends IoHandlerAdapter { private ByteBuffer readBuf = ByteBuffer.allocate(1024); private EchoConnectorHandler() { readBuf.setAutoExpand(true); } public void messageReceived(IoSession session, Object message) { readBuf.put((ByteBuffer) message); } public void messageSent(IoSession session, Object message) { } public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); } } } mina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/echoserver/ssl/0000755000175000017500000000000011044712500026733 5ustar drazzibdrazzibmina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/echoserver/ssl/SSLFilterTest.java0000644000175000017500000001245011002320031032233 0ustar drazzibdrazzibpackage org.apache.mina.example.echoserver.ssl; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import junit.framework.TestCase; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.filter.SSLFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptor; public class SSLFilterTest extends TestCase { private static final int PORT = 17887; private IoAcceptor acceptor; SocketAddress socketAddress = new InetSocketAddress(PORT); protected void setUp() throws Exception { super.setUp(); acceptor = new SocketAcceptor(); } protected void tearDown() throws Exception { acceptor.unbindAll(); super.tearDown(); } public void testMessageSentIsCalled() throws Exception { testMessageSentIsCalled(false); } public void testMessageSentIsCalled_With_SSL() throws Exception { testMessageSentIsCalled(true); } private void testMessageSentIsCalled(boolean useSSL) throws Exception { SSLFilter sslFilter = null; if (useSSL) { sslFilter = new SSLFilter(BogusSSLContextFactory.getInstance(true)); acceptor.getFilterChain().addLast("sslFilter", sslFilter); } acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8")))); EchoHandler handler = new EchoHandler(); acceptor.bind(socketAddress, handler); System.out.println("MINA server started."); Socket socket = getClientSocket(useSSL); int bytesSent = 0; bytesSent += writeMessage(socket, "test-1\n"); if (useSSL) { // Test renegotiation SSLSocket ss = (SSLSocket) socket; //ss.getSession().invalidate(); ss.startHandshake(); } bytesSent += writeMessage(socket, "test-2\n"); byte[] response = new byte[bytesSent]; for (int i = 0; i < response.length; i++) { response[i] = (byte) socket.getInputStream().read(); } if (useSSL) { // Read SSL close notify. while (socket.getInputStream().read() >= 0) { continue; } } socket.close(); long millis = System.currentTimeMillis(); while (handler.sentMessages.size() < 2 && System.currentTimeMillis() < millis + 5000) { Thread.sleep(200); } assertEquals("received what we sent", "test-1\ntest-2\n", new String( response, "UTF-8")); System.out.println("handler: " + handler.sentMessages); assertEquals("handler should have sent 2 messages:", 2, handler.sentMessages.size()); assertTrue(handler.sentMessages.contains("test-1")); assertTrue(handler.sentMessages.contains("test-2")); } private int writeMessage(Socket socket, String message) throws Exception { byte request[] = message.getBytes("UTF-8"); socket.getOutputStream().write(request); return request.length; } private Socket getClientSocket(boolean ssl) throws Exception { if (ssl) { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustManagers, null); return ctx.getSocketFactory().createSocket("localhost", PORT); } return new Socket("localhost", PORT); } private static class EchoHandler extends IoHandlerAdapter { List sentMessages = new ArrayList(); public void exceptionCaught(IoSession session, Throwable cause) throws Exception { cause.printStackTrace(); } public void messageReceived(IoSession session, Object message) throws Exception { session.write(message); } public void messageSent(IoSession session, Object message) throws Exception { sentMessages.add(message.toString()); System.out.println(message); if (sentMessages.size() >= 2) { session.close(); } } } TrustManager[] trustManagers = new TrustManager[] { new TrustAnyone() }; private static class TrustAnyone implements X509TrustManager { public void checkClientTrusted( java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { } public void checkServerTrusted( java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } } } mina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/echoserver/AcceptorTest.java0000644000175000017500000001365411002320032031373 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; import org.apache.commons.net.EchoTCPClient; import org.apache.commons.net.EchoUDPClient; import org.apache.mina.example.echoserver.ssl.SSLServerSocketFactory; import org.apache.mina.example.echoserver.ssl.SSLSocketFactory; /** * Tests echo server example. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev:448075 $, $Date:2006-09-20 05:26:53Z $ */ public class AcceptorTest extends AbstractTest { public AcceptorTest() { } public void testTCP() throws Exception { EchoTCPClient client = new EchoTCPClient(); testTCP0(client); } public void testTCPWithSSL() throws Exception { // Add an SSL filter useSSL = true; // Create a commons-net socket factory SSLSocketFactory.setSslEnabled(true); SSLServerSocketFactory.setSslEnabled(true); org.apache.commons.net.SocketFactory factory = new org.apache.commons.net.SocketFactory() { private SocketFactory f = SSLSocketFactory.getSocketFactory(); private ServerSocketFactory ssf = SSLServerSocketFactory .getServerSocketFactory(); public Socket createSocket(String arg0, int arg1) throws UnknownHostException, IOException { return f.createSocket(arg0, arg1); } public Socket createSocket(InetAddress arg0, int arg1) throws IOException { return f.createSocket(arg0, arg1); } public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3) throws UnknownHostException, IOException { return f.createSocket(arg0, arg1, arg2, arg3); } public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException { return f.createSocket(arg0, arg1, arg2, arg3); } public ServerSocket createServerSocket(int arg0) throws IOException { return ssf.createServerSocket(arg0); } public ServerSocket createServerSocket(int arg0, int arg1) throws IOException { return ssf.createServerSocket(arg0, arg1); } public ServerSocket createServerSocket(int arg0, int arg1, InetAddress arg2) throws IOException { return ssf.createServerSocket(arg0, arg1, arg2); } }; // Create a echo client with SSL factory and test it. EchoTCPClient client = new EchoTCPClient(); client.setSocketFactory(factory); testTCP0(client); } private void testTCP0(EchoTCPClient client) throws Exception { client.connect("localhost", port); byte[] writeBuf = new byte[16]; for (int i = 0; i < 10; i++) { fillWriteBuffer(writeBuf, i); client.getOutputStream().write(writeBuf); } client.setSoTimeout(30000); byte[] readBuf = new byte[writeBuf.length]; for (int i = 0; i < 10; i++) { fillWriteBuffer(writeBuf, i); int readBytes = 0; while (readBytes < readBuf.length) { int nBytes = client.getInputStream().read(readBuf, readBytes, readBuf.length - readBytes); if (nBytes < 0) fail("Unexpected disconnection."); readBytes += nBytes; } assertEquals(writeBuf, readBuf); } client.setSoTimeout(500); try { client.getInputStream().read(); fail("Unexpected incoming data."); } catch (SocketTimeoutException e) { } client.disconnect(); } public void testUDP() throws Exception { EchoUDPClient client = new EchoUDPClient(); client.open(); client.setSoTimeout(3000); byte[] writeBuf = new byte[16]; byte[] readBuf = new byte[writeBuf.length]; client.setSoTimeout(500); for (int i = 0; i < 10; i++) { fillWriteBuffer(writeBuf, i); client.send(writeBuf, writeBuf.length, InetAddress.getByName(null), port); assertEquals(readBuf.length, client .receive(readBuf, readBuf.length)); assertEquals(writeBuf, readBuf); } try { client.receive(readBuf); fail("Unexpected incoming data."); } catch (SocketTimeoutException e) { } client.close(); } private void fillWriteBuffer(byte[] writeBuf, int i) { for (int j = writeBuf.length - 1; j >= 0; j--) { writeBuf[j] = (byte) (j + i); } } public static void main(String[] args) { junit.textui.TestRunner.run(AcceptorTest.class); } } mina-1.1.7.dfsg/example/src/test/java/org/apache/mina/example/echoserver/AbstractTest.java0000644000175000017500000001431611002320032031372 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.example.echoserver; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import junit.framework.TestCase; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoSession; import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; import org.apache.mina.filter.SSLFilter; import org.apache.mina.transport.socket.nio.DatagramAcceptor; import org.apache.mina.transport.socket.nio.DatagramSessionConfig; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.apache.mina.util.SessionLog; /** * Tests echo server example. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev:448075 $, $Date:2006-09-20 05:26:53Z $ */ public abstract class AbstractTest extends TestCase { protected boolean useSSL; protected int port; protected SocketAddress boundAddress; protected IoAcceptor datagramAcceptor; protected IoAcceptor socketAcceptor; protected AbstractTest() { } protected static void assertEquals(byte[] expected, byte[] actual) { assertEquals(toString(expected), toString(actual)); } protected static void assertEquals(ByteBuffer expected, ByteBuffer actual) { assertEquals(toString(expected), toString(actual)); } protected static String toString(byte[] buf) { StringBuffer str = new StringBuffer(buf.length * 4); for (int i = 0; i < buf.length; i++) { str.append(buf[i]); str.append(' '); } return str.toString(); } protected static String toString(ByteBuffer buf) { return buf.getHexDump(); } protected void setUp() throws Exception { // Disable SSL by default useSSL = false; final SSLFilter sslFilter = new SSLFilter(BogusSSLContextFactory .getInstance(true)); boundAddress = null; datagramAcceptor = new DatagramAcceptor(); socketAcceptor = new SocketAcceptor(); ((DatagramSessionConfig) datagramAcceptor.getDefaultConfig() .getSessionConfig()).setReuseAddress(true); ((SocketAcceptorConfig) socketAcceptor.getDefaultConfig()) .setReuseAddress(true); // Find an availble test port and bind to it. boolean socketBound = false; boolean datagramBound = false; // Let's start from port #1 to detect possible resource leak // because test will fail in port 1-1023 if user run this test // as a normal user. SocketAddress address = null; for (port = 1; port <= 65535; port++) { socketBound = false; datagramBound = false; address = new InetSocketAddress(port); try { socketAcceptor.bind(address, new EchoProtocolHandler() { public void sessionCreated(IoSession session) { if (useSSL) { session.getFilterChain().addFirst("SSL", sslFilter); } } // This is for TLS reentrance test public void messageReceived(IoSession session, Object message) throws Exception { if (!(message instanceof ByteBuffer)) { return; } ByteBuffer buf = (ByteBuffer) message; if (session.getFilterChain().contains("SSL") && buf.remaining() == 1 && buf.get() == (byte) '.') { SessionLog.info(session, "TLS Reentrance"); ((SSLFilter) session.getFilterChain().get("SSL")) .startSSL(session); // Send a response buf = ByteBuffer.allocate(1); buf.put((byte) '.'); buf.flip(); session .setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE); session.write(buf); } else { super.messageReceived(session, message); } } }); socketBound = true; datagramAcceptor.bind(address, new EchoProtocolHandler()); datagramBound = true; break; } catch (IOException e) { } finally { if (socketBound && !datagramBound) { socketAcceptor.unbind(address); } if (datagramBound && !socketBound) { datagramAcceptor.unbind(address); } } } // If there is no port available, test fails. if (!socketBound || !datagramBound) { throw new IOException("Cannot bind any test port."); } boundAddress = address; System.out.println("Using port " + port + " for testing."); } protected void tearDown() throws Exception { if (boundAddress != null) { socketAcceptor.unbind(boundAddress); datagramAcceptor.unbind(boundAddress); } } } mina-1.1.7.dfsg/release.xml0000644000175000017500000000435711002320032015414 0ustar drazzibdrazzib all tar.gz tar.bz2 zip **/README* **/LICENSE* **/NOTICE* **/*.txt **/*.xml **/src/** **/lib/** **/target/** **/.*/** target/site docs apidocs*/** xref*/** core/target *.jar filter-codec-netty/target *.jar filter-compression/target *.jar filter-ssl/target *.jar java5/target *.jar integration-spring/target *.jar integration-jmx/target *.jar