pax_global_header00006660000000000000000000000064115615734620014524gustar00rootroot0000000000000052 comment=2cba9fe74a3492b9cc35fa53a5baa4d020b62c84 activemq-activeio-3.1.1/000077500000000000000000000000001156157346200151405ustar00rootroot00000000000000activemq-activeio-3.1.1/LICENSE000066400000000000000000000261371156157346200161560ustar00rootroot00000000000000 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. activemq-activeio-3.1.1/NOTICE000066400000000000000000000002651156157346200160470ustar00rootroot00000000000000Apache ActiveMQ ActiveIO Copyright 2005-2009 Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). activemq-activeio-3.1.1/activeio-core/000077500000000000000000000000001156157346200176715ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/pom.xml000066400000000000000000000053241156157346200212120ustar00rootroot00000000000000 4.0.0 org.apache.activemq activeio-parent 3.1.1 activeio-core bundle ActiveIO :: Core A high performance IO abstraction framework maven-jar-plugin test-jar maven-surefire-plugin **/*Test.* **/ChannelFactoryTest.* **/NIOAsyncChannelTest.* org.apache.geronimo.specs geronimo-j2ee-management_1.1_spec commons-logging commons-logging howl howl-logger true activemq-activeio-3.1.1/activeio-core/src/000077500000000000000000000000001156157346200204605ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/000077500000000000000000000000001156157346200214045ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/000077500000000000000000000000001156157346200223255ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/000077500000000000000000000000001156157346200231145ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/000077500000000000000000000000001156157346200243355ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/000077500000000000000000000000001156157346200261405ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/adapter/000077500000000000000000000000001156157346200275605ustar00rootroot00000000000000PacketByteArrayOutputStream.java000066400000000000000000000061461156157346200360020ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/adapter/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.adapter; import java.io.IOException; import java.io.OutputStream; import org.apache.activeio.packet.AppendedPacket; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.Packet; /** * */ final public class PacketByteArrayOutputStream extends OutputStream { private Packet result; private Packet current; int nextAllocationSize=0; public PacketByteArrayOutputStream() { this( 1024 ); } public PacketByteArrayOutputStream(int initialSize) { nextAllocationSize = initialSize; current = allocate(); } protected Packet allocate() { ByteArrayPacket packet = new ByteArrayPacket(new byte[nextAllocationSize]); nextAllocationSize <<= 3; // x by 8 return packet; } public void skip(int size) { while( size > 0 ) { if( !current.hasRemaining() ) { allocatedNext(); } int skip = ((size <= current.remaining()) ? size : current.remaining()); current.position(current.position()+skip); size -= skip; } } public void write(int b) throws IOException { if( !current.hasRemaining() ) { allocatedNext(); } current.write(b); } public void write(byte[] b, int off, int len) throws IOException { while( len > 0 ) { if( !current.hasRemaining() ) { allocatedNext(); } int wrote = current.write(b,off,len); off+=wrote; len-=wrote; } } private void allocatedNext() { if( result == null ) { current.flip(); result = current; } else { current.flip(); result = AppendedPacket.join(result, current); } current = allocate(); } public Packet getPacket() { if( result == null ) { current.flip(); return current.slice(); } else { current.flip(); return AppendedPacket.join(result, current); } } public void reset() { result = null; current.clear(); } public int position() { return current.position() + (result==null ? 0 : result.remaining()); } } PacketInputStream.java000066400000000000000000000021351156157346200337500ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/adapter/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.adapter; import org.apache.activeio.packet.Packet; /** * @deprecated Use PacketToInputStream instead. This class will be removed very soon. */ public class PacketInputStream extends PacketToInputStream { public PacketInputStream(Packet packet) { super(packet); } } PacketOutputStream.java000066400000000000000000000031001156157346200341420ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/adapter/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.adapter; import java.io.IOException; import java.io.OutputStream; import org.apache.activeio.packet.Packet; /** * Provides an OutputStream for a given Packet. * * @version $Revision$ */ public class PacketOutputStream extends OutputStream { final Packet packet; public PacketOutputStream(Packet packet) { this.packet = packet; } public void write(int b) throws IOException { if( !packet.write(b) ) throw new IOException("Packet does not have any remaining space to write to."); } public void write(byte[] b, int off, int len) throws IOException { if( packet.write(b, off, len)!=len ) throw new IOException("Packet does not have "+len+" byte(s) left to write to."); } } PacketToInputStream.java000066400000000000000000000030341156157346200342520ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/adapter/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.adapter; import java.io.IOException; import java.io.InputStream; import org.apache.activeio.packet.Packet; /** * Provides an InputStream for a given Packet. * * @version $Revision$ */ public class PacketToInputStream extends InputStream { final Packet packet; /** * @param packet */ public PacketToInputStream(Packet packet) { this.packet = packet; } /** * @see java.io.InputStream#read() */ public int read() throws IOException { return packet.read(); } /** * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] b, int off, int len) throws IOException { return packet.read(b, off, len); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/adapter/package.html000066400000000000000000000020211156157346200320340ustar00rootroot00000000000000

The Adapter package provides classes that make it easy ot bridge between the the SynchChannel, AsyncChannel, InputStream, OutputStream, Socket, and ServerSocket domains.

activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/000077500000000000000000000000001156157346200276125ustar00rootroot00000000000000InvalidRecordLocationException.java000066400000000000000000000031121156157346200364700ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal; /** * Exception thrown by a Journal to indicate that an invalid RecordLocation was detected. * * @version $Revision: 1.1 $ */ public class InvalidRecordLocationException extends Exception { /** * Comment for serialVersionUID */ private static final long serialVersionUID = 3618414947307239475L; /** * */ public InvalidRecordLocationException() { super(); } /** * @param msg */ public InvalidRecordLocationException(String msg) { super(msg); } /** * @param msg * @param rootCause */ public InvalidRecordLocationException(String msg, Throwable rootCause) { super(msg, rootCause); } /** * @param rootCause */ public InvalidRecordLocationException(Throwable rootCause) { super(rootCause); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/Journal.java000066400000000000000000000117131156157346200320720ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal; import java.io.IOException; import org.apache.activeio.packet.Packet; /** * A Journal is a record logging Interface that can be used to implement * a transaction log. * * * This interface was largely extracted out of the HOWL project to allow * ActiveMQ to switch between different Journal implementations verry easily. * * @version $Revision: 1.1 $ */ public interface Journal { /** * Writes a {@see Packet} of data to the journal. If sync * is true, then this call blocks until the data has landed on the physical * disk. Otherwise, this enqueues the write request and returns. * * @param record - the data to be written to disk. * @param sync - If this call should block until the data lands on disk. * * @return RecordLocation the location where the data will be written to on disk. * * @throws IOException if the write failed. * @throws IllegalStateException if the journal is closed. */ public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException; /** * Reads a previously written record from the journal. * * @param location is where to read the record from. * * @return the data previously written at the location. * * @throws InvalidRecordLocationException if location parameter is out of range. * It cannot be a location that is before the current mark. * @throws IOException if the record could not be read. * @throws IllegalStateException if the journal is closed. */ public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException; /** * Informs the journal that all the journal space up to the location is no longer * needed and can be reclaimed for reuse. * * @param location the location of the record to mark. All record locations before the marked * location will no longger be vaild. * * @param sync if this call should block until the mark is set on the journal. * * @throws InvalidRecordLocationException if location parameter is out of range. * It cannot be a location that is before the current mark. * @throws IOException if the record could not be read. * @throws IllegalStateException if the journal is closed. */ public abstract void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException, IOException, IllegalStateException; /** * Obtains the mark that was set in the Journal. * * @see read(RecordLocation location); * @return the mark that was set in the Journal. * @throws IllegalStateException if the journal is closed. */ public RecordLocation getMark() throws IllegalStateException; /** * Close the Journal. * This is blocking operation that waits for any pending put opperations to be forced to disk. * Once the Journal is closed, all other methods of the journal should throw IllegalStateException. * * @throws IOException if an error occurs while the journal is being closed. */ public abstract void close() throws IOException; /** * Allows you to get the next RecordLocation after the location that * is in the journal. * * @param location the reference location the is used to find the next location. * To get the oldest location available in the journal, location * should be set to null. * * * @return the next record location * * @throws InvalidRecordLocationException if location parameter is out of range. * It cannot be a location that is before the current mark. * @throws IllegalStateException if the journal is closed. */ public abstract RecordLocation getNextRecordLocation(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException; /** * Registers a JournalEventListener that will receive notifications from the Journal. * * @param listener object that will receive journal events. * @throws IllegalStateException if the journal is closed. */ public abstract void setJournalEventListener(JournalEventListener listener) throws IllegalStateException; } JournalEventListener.java000066400000000000000000000027161156157346200345260ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal; /** * Defines an object which listens for Journal Events. * * @version $Revision: 1.1 $ */ public interface JournalEventListener { /** * This event is issues when a Journal implementations wants to recover * disk space used by old records. If journal space is not reliquised * by setting the Journal's mark at or past the safeLocation * further write opperations against the Journal may casuse IOExceptions * to occur due to a log overflow condition. * * @param safeLocation the oldest location that the journal recomends the mark to be set. */ void overflowNotification(RecordLocation safeLocation); } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/RecordLocation.java000066400000000000000000000022161156157346200333650ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal; /** * A RecordLocation is used to locate data records that have been * logged to a Journal via the Journal.put() method call. * * RecordLocation are comparable on the position in the Journal * where they reside. * * @version $Revision: 1.1 $ */ public interface RecordLocation extends Comparable { } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/000077500000000000000000000000001156157346200310655ustar00rootroot00000000000000BatchedWrite.java000066400000000000000000000072611156157346200342240ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import org.apache.activeio.packet.Packet; import java.util.concurrent.CountDownLatch; /** * This contains all the data needed to write and force a list of records to a * LogFile. The more records that can be cramed into a single BatchedWrite, the * higher throughput that can be achived by a write and force operation. * * @version $Revision: 1.1 $ */ final public class BatchedWrite { private final Packet packet; public Throwable error; private Location mark; private boolean appendDisabled = false; private boolean appendInProgress = false; private CountDownLatch writeDoneCountDownLatch; /** * @param packet */ public BatchedWrite(Packet packet) { this.packet = packet; } /** * @throws InterruptedException * */ synchronized private void disableAppend() throws InterruptedException { appendDisabled = true; while (appendInProgress) { wait(); } } /** * @param packet2 * @param mark2 * @return */ public boolean append(Record record, Location recordMark, boolean force) { synchronized (this) { if (appendDisabled) return false; appendInProgress = true; } if( force && writeDoneCountDownLatch==null) writeDoneCountDownLatch = new CountDownLatch(1); record.read(packet); // if we fit the record in this batch if ( !record.hasRemaining() ) { if (recordMark != null) mark = recordMark; } synchronized (this) { appendInProgress = false; this.notify(); if (appendDisabled) return false; else return packet.remaining() > 0; } } public void waitForForce() throws Throwable { if( writeDoneCountDownLatch!=null ) { writeDoneCountDownLatch.await(); synchronized (this) { if (error != null) throw error; } } } public void forced() { if( writeDoneCountDownLatch!=null ) { writeDoneCountDownLatch.countDown(); } } public void writeFailed(Throwable error) { if( writeDoneCountDownLatch!=null ) { synchronized (this) { this.error = error; } writeDoneCountDownLatch.countDown(); } } public Packet getPacket() { return packet; } /** * @return */ public Location getMark() { return mark; } /** * @throws InterruptedException * */ public void flip() throws InterruptedException { disableAppend(); packet.flip(); } public boolean getForce() { return writeDoneCountDownLatch!=null; } } ControlFile.java000066400000000000000000000140021156157346200340660ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.HashSet; import java.util.Properties; import java.util.Set; import org.apache.activeio.packet.ByteBufferPacket; import org.apache.activeio.packet.Packet; /** * Control file holds the last known good state of the journal. It stores the state in * record that is versioned and repeated twice in the file so that a failure in the * middle of the write of the first or second record do not not result in an unknown * state. * * @version $Revision: 1.1 $ */ final public class ControlFile { /** The File that holds the control data. */ private final RandomAccessFile file; private final FileChannel channel; private final ByteBufferPacket controlData; private final static boolean brokenFileLock = "true".equals(System.getProperty("java.nio.channels.FileLock.broken", "false")); private long controlDataVersion=0; private FileLock lock; private boolean disposed; private static Set lockSet; private String canonicalPath; public ControlFile(File fileName, int controlDataSize) throws IOException { canonicalPath = fileName.getCanonicalPath(); boolean existed = fileName.exists(); file = new RandomAccessFile(fileName, "rw"); channel = file.getChannel(); controlData = new ByteBufferPacket(ByteBuffer.allocateDirect(controlDataSize)); } /** * Locks the control file. * @throws IOException */ public void lock() throws IOException { Properties properties = System.getProperties(); synchronized(properties) { String lockKey = "org.apache.activeio.journal.active.lockMap:"+canonicalPath; if( properties.setProperty(lockKey, "true")!=null ) { throw new JournalLockedException("Journal is already opened by this application."); } if( !brokenFileLock ) { lock = channel.tryLock(); if (lock == null) { properties.remove(lockKey); throw new JournalLockedException("Journal is already opened by another application"); } } } } /** * Un locks the control file. * * @throws IOException */ public void unlock() throws IOException { Properties properties = System.getProperties(); synchronized(properties) { if (lock != null) { String lockKey = "org.apache.activeio.journal.active.lockMap:"+canonicalPath; properties.remove(lockKey); lock.release(); lock = null; } } } public boolean load() throws IOException { long l = file.length(); if( l < controlData.capacity() ) { controlDataVersion=0; controlData.position(0); controlData.limit(0); return false; } else { file.seek(0); long v1 = file.readLong(); file.seek(controlData.capacity()+8); long v1check = file.readLong(); file.seek(controlData.capacity()+16); long v2 = file.readLong(); file.seek((controlData.capacity()*2)+24); long v2check = file.readLong(); if( v2 == v2check ) { controlDataVersion = v2; file.seek(controlData.capacity()+24); controlData.clear(); channel.read(controlData.getByteBuffer()); } else if ( v1 == v1check ){ controlDataVersion = v1; file.seek(controlData.capacity()+8); controlData.clear(); channel.read(controlData.getByteBuffer()); } else { // Bummer.. Both checks are screwed. we don't know // if any of the two buffer are ok. This should // only happen is data got corrupted. throw new IOException("Control data corrupted."); } return true; } } public void store() throws IOException { controlDataVersion++; file.setLength((controlData.capacity()*2)+32); file.seek(0); // Write the first copy of the control data. file.writeLong(controlDataVersion); controlData.clear(); channel.write(controlData.getByteBuffer()); file.writeLong(controlDataVersion); // Write the second copy of the control data. file.writeLong(controlDataVersion); controlData.clear(); channel.write(controlData.getByteBuffer()); file.writeLong(controlDataVersion); channel.force(false); } public Packet getControlData() { controlData.clear(); return controlData; } public void dispose() { if( disposed ) return; disposed=true; try { unlock(); } catch (IOException e) { } try { file.close(); } catch (IOException e) { } } } JournalImpl.java000066400000000000000000000404421156157346200341110ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import org.apache.activeio.journal.InvalidRecordLocationException; import org.apache.activeio.journal.Journal; import org.apache.activeio.journal.JournalEventListener; import org.apache.activeio.journal.RecordLocation; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.ByteBufferPacketPool; import org.apache.activeio.packet.Packet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * A high speed Journal implementation. Inspired by the ideas of the Howl project but tailored to the needs * of ActiveMQ.

This Journal provides the following features: *

*

* * @version $Revision: 1.1 $ */ final public class JournalImpl implements Journal { public static final int DEFAULT_POOL_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPoolSize", ""+(5))); public static final int DEFAULT_PACKET_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPacketSize", ""+(1024*1024*4))); static final private int OVERFLOW_RENOTIFICATION_DELAY = 500; static private ByteBufferPacketPool lastPool; private boolean disposed = false; // The id of the current log file that is being filled. private int appendLogFileId = 0; // The offset in the current log file that is being filled. private int appendLogFileOffset = 0; // Used to batch writes together. private BatchedWrite pendingBatchWrite; private Location lastMarkedLocation; private LogFileManager file; private ThreadPoolExecutor executor; private int rolloverFence; private JournalEventListener eventListener; private ByteBufferPacketPool packetPool; private long overflowNotificationTime = System.currentTimeMillis(); private Packet markPacket = new ByteArrayPacket(new byte[Location.SERIALIZED_SIZE]); private boolean doingNotification=false; public JournalImpl(File logDirectory) throws IOException { this(new LogFileManager(logDirectory)); } public JournalImpl(File logDirectory, int logFileCount, int logFileSize) throws IOException { this(new LogFileManager(logDirectory, logFileCount, logFileSize, null)); } public JournalImpl(File logDirectory, int logFileCount, int logFileSize, File archiveDirectory) throws IOException { this(new LogFileManager(logDirectory, logFileCount, logFileSize, archiveDirectory)); } public JournalImpl(LogFileManager logFile) { this.file = logFile; this.packetPool = createBufferPool(); this.executor = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue(), new ThreadFactory() { public Thread newThread(Runnable runnable) { Thread answer = new Thread(runnable, "Journal Writer"); answer.setPriority(Thread.MAX_PRIORITY); answer.setDaemon(true); return answer; } }); //executor.allowCoreThreadTimeOut(true); lastMarkedLocation = file.getLastMarkedRecordLocation(); Location nextAppendLocation = file.getNextAppendLocation(); appendLogFileId = nextAppendLocation.getLogFileId(); appendLogFileOffset = nextAppendLocation.getLogFileOffset(); rolloverFence = (file.getInitialLogFileSize() / 10) * 9; } /** * When running unit tests we may not be able to create new pools fast enough * since the old pools are not being gc'ed fast enough. So we pool the pool. * @return */ synchronized static private ByteBufferPacketPool createBufferPool() { if( lastPool !=null ) { ByteBufferPacketPool rc = lastPool; lastPool = null; return rc; } else { return new ByteBufferPacketPool(DEFAULT_POOL_SIZE, DEFAULT_PACKET_SIZE); } } /** * When running unit tests we may not be able to create new pools fast enough * since the old pools are not being gc'ed fast enough. So we pool the pool. * @return */ synchronized static private void disposeBufferPool(ByteBufferPacketPool pool) { if( lastPool!=null ) { pool.dispose(); } else { pool.waitForPacketsToReturn(); lastPool = pool; } } public RecordLocation write(Packet data, boolean sync) throws IOException { return write(LogFileManager.DATA_RECORD_TYPE, data, sync, null); } private Location write(byte recordType, Packet data, boolean sync, Location mark) throws IOException { try { Location location; BatchedWrite writeCommand; Record record = new Record(recordType, data, mark); // The following synchronized block is the bottle neck of the journal. Make this // code faster and the journal should speed up. synchronized (this) { if (disposed) { throw new IOException("Journal has been closed."); } // Create our record location = new Location(appendLogFileId, appendLogFileOffset); record.setLocation(location); // Piggy back the packet on the pending write batch. writeCommand = addToPendingWriteBatch(record, mark, sync); // Update where the next record will land. appendLogFileOffset += data.limit() + Record.RECORD_BASE_SIZE; rolloverCheck(); } if (sync) { writeCommand.waitForForce(); } return location; } catch (IOException e) { throw e; } catch (InterruptedException e) { throw (IOException) new InterruptedIOException().initCause(e); } catch (Throwable e) { throw (IOException) new IOException("Write failed: " + e).initCause(e); } } /** * @param record * @return * @throws InterruptedException */ private BatchedWrite addToPendingWriteBatch(Record record, Location mark, boolean force) throws InterruptedException { // Load the write batch up with data from our record. // it may take more than one write batch if the record is large. BatchedWrite answer = null; while (record.hasRemaining()) { // Do we need another BatchWrite? boolean queueTheWrite=false; if (pendingBatchWrite == null) { pendingBatchWrite = new BatchedWrite(packetPool.getPacket()); queueTheWrite = true; } answer = pendingBatchWrite; // Can we continue to use the pendingBatchWrite? boolean full = !pendingBatchWrite.append(record, mark, force); if( queueTheWrite ) { final BatchedWrite queuedWrite = pendingBatchWrite; executor.execute(new Runnable() { public void run() { try { queuedWrite(queuedWrite); } catch (InterruptedException e) { } } }); } if( full ) pendingBatchWrite = null; } return answer; } /** * This is a blocking call * * @param write * @throws InterruptedException */ private void queuedWrite(BatchedWrite write) throws InterruptedException { // Stop other threads from appending more pendingBatchWrite. write.flip(); // Do the write. try { file.append(write); write.forced(); } catch (Throwable e) { write.writeFailed(e); } finally { write.getPacket().dispose(); } } /** * */ private void rolloverCheck() throws IOException { // See if we need to issue an overflow notification. if (eventListener != null && file.isPastHalfActive() && overflowNotificationTime + OVERFLOW_RENOTIFICATION_DELAY < System.currentTimeMillis() && !doingNotification ) { doingNotification = true; try { // We need to send an overflow notification to free up // some logFiles. Location safeSpot = file.getFirstRecordLocationOfSecondActiveLogFile(); eventListener.overflowNotification(safeSpot); overflowNotificationTime = System.currentTimeMillis(); } finally { doingNotification = false; } } // Is it time to roll over? if (appendLogFileOffset > rolloverFence ) { // Can we roll over? if ( !file.canActivateNextLogFile() ) { // don't delay the next overflow notification. overflowNotificationTime -= OVERFLOW_RENOTIFICATION_DELAY; } else { try { final FutureTask result = new FutureTask(new Callable() { public Object call() throws Exception { return queuedActivateNextLogFile(); }}); executor.execute(result); Location location = (Location) result.get(); appendLogFileId = location.getLogFileId(); appendLogFileOffset = location.getLogFileOffset(); } catch (InterruptedException e) { throw (IOException) new IOException("Interrupted.").initCause(e); } catch (ExecutionException e) { throw handleExecutionException(e); } } } } /** * This is a blocking call */ private Location queuedActivateNextLogFile() throws IOException { file.activateNextLogFile(); return file.getNextAppendLocation(); } /** * @param recordLocator * @param force * @return * @throws InvalidRecordLocationException * @throws IOException * @throws InterruptedException */ synchronized public void setMark(RecordLocation l, boolean force) throws InvalidRecordLocationException, IOException { Location location = (Location) l; if (location == null) throw new InvalidRecordLocationException("The location cannot be null."); if (lastMarkedLocation != null && location.compareTo(lastMarkedLocation) < 0) throw new InvalidRecordLocationException("The location is less than the last mark."); markPacket.clear(); location.writeToPacket(markPacket); markPacket.flip(); write(LogFileManager.MARK_RECORD_TYPE, markPacket, force, location); lastMarkedLocation = location; } /** * @return */ public RecordLocation getMark() { return lastMarkedLocation; } /** * @param lastLocation * @return * @throws IOException * @throws InvalidRecordLocationException */ public RecordLocation getNextRecordLocation(final RecordLocation lastLocation) throws IOException, InvalidRecordLocationException { if (lastLocation == null) { if (lastMarkedLocation != null) { return lastMarkedLocation; } else { return file.getFirstActiveLogLocation(); } } // Run this in the queued executor thread. try { final FutureTask result = new FutureTask(new Callable() { public Object call() throws Exception { return queuedGetNextRecordLocation((Location) lastLocation); }}); executor.execute(result); return (Location) result.get(); } catch (InterruptedException e) { throw (IOException) new IOException("Interrupted.").initCause(e); } catch (ExecutionException e) { throw handleExecutionException(e); } } protected IOException handleExecutionException(ExecutionException e) throws IOException { Throwable cause = e.getCause(); if (cause instanceof IOException) { return (IOException) cause; } else { return (IOException) new IOException(cause.getMessage()).initCause(cause); } } private Location queuedGetNextRecordLocation(Location location) throws IOException, InvalidRecordLocationException { return file.getNextDataRecordLocation(location); } /** * @param location * @return * @throws InvalidRecordLocationException * @throws IOException */ public Packet read(final RecordLocation l) throws IOException, InvalidRecordLocationException { final Location location = (Location) l; // Run this in the queued executor thread. try { final FutureTask result = new FutureTask(new Callable() { public Object call() throws Exception { return file.readPacket(location); }}); executor.execute(result); return (Packet) result.get(); } catch (InterruptedException e) { throw (IOException) new IOException("Interrupted.").initCause(e); } catch (ExecutionException e) { throw handleExecutionException(e); } } public void setJournalEventListener(JournalEventListener eventListener) { this.eventListener = eventListener; } /** * @deprecated @see #dispose() */ public void close() throws IOException { dispose(); } /** */ public void dispose() { if (disposed) return; disposed=true; executor.shutdown(); file.dispose(); ByteBufferPacketPool pool = packetPool; packetPool=null; disposeBufferPool(pool); } /** * @return */ public File getLogDirectory() { return file.getLogDirectory(); } public int getInitialLogFileSize() { return file.getInitialLogFileSize(); } public String toString() { return "Active Journal: using "+file.getOnlineLogFileCount()+" x " + (file.getInitialLogFileSize()/(1024*1024f)) + " Megs at: " + getLogDirectory(); } } JournalLockedException.java000066400000000000000000000022771156157346200362740ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.IOException; /** * @version $Revision$ */ public class JournalLockedException extends IOException { private static final long serialVersionUID = -3696987774575855799L; public JournalLockedException() { super(); } /** * @param arg0 */ public JournalLockedException(String arg0) { super(arg0); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java000066400000000000000000000056151156157346200335070ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.activeio.journal.RecordLocation; import org.apache.activeio.packet.Packet; import org.apache.activeio.packet.PacketData; /** * Defines a where a record can be located in the Journal. * * @version $Revision: 1.1 $ */ final public class Location implements RecordLocation { static final public int SERIALIZED_SIZE=8; final private int logFileId; final private int logFileOffset; public Location(int logFileId, int fileOffset) { this.logFileId = logFileId; this.logFileOffset = fileOffset; } public int compareTo(Object o) { int rc = logFileId - ((Location) o).logFileId; if (rc != 0) return rc; return logFileOffset - ((Location) o).logFileOffset; } public int hashCode() { return logFileOffset ^ logFileId; } public boolean equals(Object o) { if (o == null || o.getClass() != Location.class) return false; Location rl = (Location) o; return rl.logFileId == this.logFileId && rl.logFileOffset == this.logFileOffset; } public String toString() { return "" + logFileId + ":" + logFileOffset; } public int getLogFileId() { return logFileId; } public int getLogFileOffset() { return logFileOffset; } public void writeToPacket(Packet packet) throws IOException { PacketData data = new PacketData(packet); data.writeInt(logFileId); data.writeInt(logFileOffset); } public void writeToDataOutput(DataOutput data) throws IOException { data.writeInt(logFileId); data.writeInt(logFileOffset); } static public Location readFromPacket(Packet packet) throws IOException { PacketData data = new PacketData(packet); return new Location(data.readInt(), data.readInt()); } public static Location readFromDataInput(DataInput data) throws IOException { return new Location(data.readInt(), data.readInt()); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFile.java000066400000000000000000000110761156157346200332560ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * Allows read/append access to a LogFile. * * @version $Revision: 1.1 $ */ final public class LogFile { private final RandomAccessFile file; private final FileChannel channel; /** Prefered size. The size that the log file is set to when initilaized. */ private final int initialSize; /** Where the we are in the file right now */ private int currentOffset; private boolean disposed; public LogFile(File file, int initialSize) throws IOException { this.initialSize = initialSize; boolean initializationNeeeded = !file.exists(); this.file = new RandomAccessFile(file, "rw"); channel = this.file.getChannel(); if( initializationNeeeded ) resize(); channel.position(0); reloadCurrentOffset(); } /** * To avoid doing un-needed seeks. */ private void seek(int offset) throws IOException { if( offset == currentOffset ) { if( currentOffset != channel.position() ) throw new RuntimeException(" "+currentOffset+", "+channel.position() ); return; } channel.position(offset); currentOffset = offset; } private void reloadCurrentOffset() throws IOException { currentOffset= (int) channel.position(); } private void addToCurrentOffset(int rc) { currentOffset+=rc; } public boolean loadAndCheckRecord(int offset, Record record) throws IOException { try { // Read the next header seek(offset); record.readHeader(file); if (Record.isChecksumingEnabled()) { record.checksum(file); } // Load the footer. seek(offset+record.getPayloadLength()+Record.RECORD_HEADER_SIZE); record.readFooter(file); addToCurrentOffset(record.getRecordLength()); return true; } catch (IOException e) { reloadCurrentOffset(); return false; } } public void resize() throws IOException { file.setLength(initialSize); } public void force() throws IOException { channel.force(false); } public void dispose() { if( disposed ) return; disposed=true; try { this.file.close(); } catch (IOException e) { } } public void write(int offset, ByteBuffer buffer) throws IOException { try { int size = buffer.remaining(); seek(offset); while (buffer.hasRemaining()) { channel.write(buffer); } addToCurrentOffset(size); } catch (IOException e) { reloadCurrentOffset(); } } public void readRecordHeader(int offset, Record record) throws IOException { seek(offset); try { record.readHeader(file); } catch ( IOException e ) { reloadCurrentOffset(); throw e; } addToCurrentOffset(Record.RECORD_HEADER_SIZE); } public void read(int offset, byte[] answer) throws IOException { seek(offset); file.readFully(answer); addToCurrentOffset(answer.length); } public void copyTo(File location) throws IOException { FileOutputStream fos = new FileOutputStream(location); channel.transferTo(0, channel.size(), fos.getChannel()); fos.getChannel().force(false); fos.close(); } } LogFileManager.java000066400000000000000000000446711156157346200345010ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.text.NumberFormat; import java.util.HashMap; import java.util.Iterator; import org.apache.activeio.adapter.PacketOutputStream; import org.apache.activeio.adapter.PacketToInputStream; import org.apache.activeio.journal.InvalidRecordLocationException; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.ByteBufferPacket; import org.apache.activeio.packet.Packet; import java.util.concurrent.atomic.AtomicInteger; /** * Provides a logical view of many separate files as one single long log file. * The separate files that compose the LogFile are Segments of the LogFile. *

This class is not thread safe. * * @version $Revision: 1.1 $ */ final public class LogFileManager { public static final int DEFAULT_LOGFILE_COUNT = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultLogFileCount", ""+(2))); public static final int DEFAULT_LOGFILE_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultLogFileSize", ""+(1024*1024*20))); static final public int SERIALIZED_SIZE = 6+Location.SERIALIZED_SIZE; static final public byte DATA_RECORD_TYPE = 1; static final public byte MARK_RECORD_TYPE = 2; static final private NumberFormat onlineLogNameFormat = NumberFormat.getNumberInstance(); static { onlineLogNameFormat.setMinimumIntegerDigits(3); onlineLogNameFormat.setMaximumIntegerDigits(3); onlineLogNameFormat.setGroupingUsed(false); onlineLogNameFormat.setParseIntegerOnly(true); onlineLogNameFormat.setMaximumFractionDigits(0); } static final private NumberFormat archiveLogNameFormat = NumberFormat.getNumberInstance(); static { archiveLogNameFormat.setMinimumIntegerDigits(8); archiveLogNameFormat.setMaximumIntegerDigits(8); archiveLogNameFormat.setGroupingUsed(false); archiveLogNameFormat.setParseIntegerOnly(true); archiveLogNameFormat.setMaximumFractionDigits(0); } // Config private final File logDirectory; private final int initialLogFileSize; private final int onlineLogFileCount; private final AtomicInteger activeLogFileCount = new AtomicInteger(0); // Keeps track of the online log file. private LogFileNode firstNode; private LogFileNode firstActiveNode; private LogFileNode firstInactiveNode; private LogFileNode appendNode; private ControlFile controlFile; private int lastLogFileId = -1; private Location lastMark; private boolean disposed; private boolean loadedFromCleanShutDown; private File archiveDirectory; HashMap openArchivedLogs = new HashMap(); public LogFileManager(File logDirectory) throws IOException { this(logDirectory, DEFAULT_LOGFILE_COUNT, DEFAULT_LOGFILE_SIZE, null); } public LogFileManager(File logDirectory, int onlineLogFileCount, int initialLogFileSize, File archiveDirectory) throws IOException { this.logDirectory = logDirectory; this.onlineLogFileCount = onlineLogFileCount; this.initialLogFileSize = initialLogFileSize; initialize(onlineLogFileCount); this.archiveDirectory=archiveDirectory; } void initialize(int onlineLogFileCount) throws IOException { try { LogFileNode logFiles[] = new LogFileNode[onlineLogFileCount]; // Create the log directory if it does not exist. if (!logDirectory.exists()) { if (!logDirectory.mkdirs()) { throw new IOException("Could not create directory: " + logDirectory); } } // Open the control file. int controlDataSize = SERIALIZED_SIZE + (LogFileNode.SERIALIZED_SIZE*onlineLogFileCount); controlFile = new ControlFile(new File(logDirectory, "control.dat"), controlDataSize); // Make sure we are the only process using the control file. controlFile.lock(); // Initialize the nodes. for (int i = 0; i < onlineLogFileCount; i++) { LogFile file = new LogFile(new File(logDirectory, "log-" + onlineLogNameFormat.format(i) + ".dat"), initialLogFileSize); logFiles[i] = new LogFileNode(file); } // Link the nodes together. for (int i = 0; i < onlineLogFileCount; i++) { if (i == (onlineLogFileCount - 1)) { logFiles[i].setNext(logFiles[0]); } else { logFiles[i].setNext(logFiles[i + 1]); } } firstNode = logFiles[0]; loadState(); // Find the first active node for (int i = 0; i < onlineLogFileCount; i++) { if( logFiles[i].isActive() ) { if( firstActiveNode == null || logFiles[i].getId() < firstActiveNode.getId() ) { firstActiveNode = logFiles[i]; } } } // None was active? activate one. if ( firstActiveNode == null ) { firstInactiveNode = logFiles[0]; activateNextLogFile(); } else { // Find the append log and the first inactive node firstInactiveNode = null; LogFileNode log = firstActiveNode; do { if( !log.isActive() ) { firstInactiveNode = log; break; } else { appendNode = log; } log = log.getNext(); } while (log != firstActiveNode); } // If we did not have a clean shut down then we have to check the state // of the append log. if( !this.loadedFromCleanShutDown ) { checkAppendLog(); } loadedFromCleanShutDown = false; storeState(); } catch (JournalLockedException e) { controlFile.dispose(); throw e; } } private void checkAppendLog() throws IOException { // We are trying to get the true append offset and the last Mark that was written in // the append log. int offset = 0; Record record = new Record(); LogFile logFile = appendNode.getLogFile(); Location markLocation=null; while( logFile.loadAndCheckRecord(offset, record) ) { if( record.getLocation().getLogFileId()!= appendNode.getId() || record.getLocation().getLogFileOffset()!=offset ) { // We must have run past the end of the append location. break; } if ( record.getRecordType()==LogFileManager.MARK_RECORD_TYPE) { markLocation = record.getLocation(); } offset += record.getRecordLength(); } appendNode.setAppendOffset(offset); if( markLocation!=null ) { try { Packet packet = readPacket(markLocation); markLocation = Location.readFromPacket(packet); } catch (InvalidRecordLocationException e) { throw (IOException)new IOException(e.getMessage()).initCause(e); } updateMark(markLocation); } } private void storeState() throws IOException { Packet controlData = controlFile.getControlData(); if( controlData.remaining() == 0 ) return; DataOutput data = new DataOutputStream(new PacketOutputStream(controlData)); data.writeInt(lastLogFileId); data.writeBoolean(lastMark!=null); if( lastMark!=null ) lastMark.writeToDataOutput(data); data.writeBoolean(loadedFromCleanShutDown); // Load each node's state LogFileNode log = firstNode; do { log.writeExternal( data ); log = log.getNext(); } while (log != firstNode); controlFile.store(); } private void loadState() throws IOException { if( controlFile.load() ) { Packet controlData = controlFile.getControlData(); if( controlData.remaining() == 0 ) return; DataInput data = new DataInputStream(new PacketToInputStream(controlData)); lastLogFileId =data.readInt(); if( data.readBoolean() ) lastMark = Location.readFromDataInput(data); else lastMark = null; loadedFromCleanShutDown = data.readBoolean(); // Load each node's state LogFileNode log = firstNode; do { log.readExternal( data ); log = log.getNext(); } while (log != firstNode); } } public void dispose() { if (disposed) return; this.disposed = true; try { // Close all the opened log files. LogFileNode log = firstNode; do { log.getLogFile().dispose(); log = log.getNext(); } while (log != firstNode); Iterator iter = openArchivedLogs.values().iterator(); while (iter.hasNext()) { ((LogFile)iter.next()).dispose(); } loadedFromCleanShutDown=true; storeState(); controlFile.dispose(); } catch ( IOException e ) { } } private int getNextLogFileId() { return ++lastLogFileId; } /** * @param write * @throws IOException */ public void append(BatchedWrite write) throws IOException { if (!appendNode.isActive()) throw new IllegalStateException("Log file is not active. Writes are not allowed"); if (appendNode.isReadOnly()) throw new IllegalStateException("Log file has been marked Read Only. Writes are not allowed"); // Write and force the data to disk. LogFile logFile = appendNode.getLogFile(); ByteBuffer buffer = ((ByteBufferPacket)write.getPacket().getAdapter(ByteBufferPacket.class)).getByteBuffer(); int size = buffer.remaining(); logFile.write(appendNode.getAppendOffset(), buffer); if( write.getForce() ) logFile.force(); // Update state appendNode.appended(size); if (write.getMark() != null) { updateMark(write.getMark()); } } /** * @param write * @throws IOException */ synchronized private void updateMark(Location mark) throws IOException { // If we wrote a mark we may need to deactivate some log files. this.lastMark = mark; while (firstActiveNode != appendNode) { if (firstActiveNode.getId() < lastMark.getLogFileId()) { if( archiveDirectory!=null ) { File file = getArchiveFile(firstActiveNode.getId()); firstActiveNode.getLogFile().copyTo(file); } firstActiveNode.deactivate(); activeLogFileCount.decrementAndGet(); if( firstInactiveNode == null ) firstInactiveNode = firstActiveNode; firstActiveNode = firstActiveNode.getNextActive(); } else { break; } } } private File getArchiveFile(int logId) { return new File(archiveDirectory, "" + archiveLogNameFormat.format(logId) + ".log"); } RecordInfo readRecordInfo(Location location) throws IOException, InvalidRecordLocationException { LogFile logFile; LogFileNode logFileState = getLogFileWithId(location.getLogFileId()); if( logFileState !=null ) { // There can be no record at the append offset. if (logFileState.getAppendOffset() == location.getLogFileOffset()) { throw new InvalidRecordLocationException("No record at (" + location + ") found. Location past end of logged data."); } logFile = logFileState.getLogFile(); } else { if( archiveDirectory==null ) { throw new InvalidRecordLocationException("Log file: " + location.getLogFileId() + " is not active."); } else { logFile = getArchivedLogFile(location.getLogFileId()); } } // Is there a record header at the seeked location? try { Record header = new Record(); logFile.readRecordHeader(location.getLogFileOffset(), header); return new RecordInfo(location, header, logFileState, logFile); } catch (IOException e) { throw new InvalidRecordLocationException("No record at (" + location + ") found."); } } private LogFile getArchivedLogFile(int logFileId) throws InvalidRecordLocationException, IOException { Integer key = new Integer(logFileId); LogFile rc = (LogFile) openArchivedLogs.get(key); if( rc == null ) { File archiveFile = getArchiveFile(logFileId); if( !archiveFile.canRead() ) throw new InvalidRecordLocationException("Log file: " + logFileId + " does not exist."); rc = new LogFile(archiveFile, getInitialLogFileSize()); openArchivedLogs.put(key, rc); // TODO: turn openArchivedLogs into LRU cache and close old log files. } return rc; } LogFileNode getLogFileWithId(int logFileId) throws InvalidRecordLocationException { for (LogFileNode lf = firstActiveNode; lf != null; lf = lf.getNextActive()) { if (lf.getId() == logFileId) { return lf; } // Short cut since id's will only increment if (logFileId < lf.getId()) break; } return null; } /** * @param lastLocation * @return */ public Location getNextDataRecordLocation(Location lastLocation) throws IOException, InvalidRecordLocationException { RecordInfo ri = readRecordInfo(lastLocation); while (true) { int logFileId = ri.getLocation().getLogFileId(); int offset = ri.getNextLocation(); // Are we overflowing into next logFile? if (offset >= ri.getLogFileState().getAppendOffset()) { LogFileNode nextActive = ri.getLogFileState().getNextActive(); if (nextActive == null || nextActive.getId() <= ri.getLogFileState().getId() ) { return null; } logFileId = nextActive.getId(); offset = 0; } try { ri = readRecordInfo(new Location(logFileId, offset)); } catch (InvalidRecordLocationException e) { return null; } // Is the next record the right record type? if (ri.getHeader().getRecordType() == DATA_RECORD_TYPE) { return ri.getLocation(); } // No? go onto the next record. } } /** * @param logFileIndex * @param logFileOffset * @return * @throws IOException * @throws InvalidRecordLocationException */ public Packet readPacket(Location location) throws IOException, InvalidRecordLocationException { // Is there a record header at the seeked location? RecordInfo recordInfo = readRecordInfo(location); byte data[] = new byte[recordInfo.getHeader().getPayloadLength()]; LogFile logFile = recordInfo.getLogFile(); logFile.read(recordInfo.getDataOffset(), data); return new ByteArrayPacket(data); } public int getInitialLogFileSize() { return initialLogFileSize; } public Location getFirstActiveLogLocation() { if (firstActiveNode == null) return null; if (firstActiveNode.getAppendOffset() == 0) return null; return new Location(firstActiveNode.getId(), 0); } void activateNextLogFile() throws IOException { // The current append logFile becomes readonly if (appendNode != null) { appendNode.setReadOnly(true); } LogFileNode next = firstInactiveNode; synchronized (this) { firstInactiveNode = firstInactiveNode.getNextInactive(); next.activate(getNextLogFileId()); if (firstActiveNode == null) { firstActiveNode = next; } } activeLogFileCount.incrementAndGet(); appendNode = next; storeState(); } /** * @return Returns the logDirectory. */ public File getLogDirectory() { return logDirectory; } /** * @return Returns the lastMark. */ public Location getLastMarkedRecordLocation() { return lastMark; } public Location getNextAppendLocation() { return new Location(appendNode.getId(), appendNode.getAppendOffset()); } /** * @return Returns the onlineLogFileCount. */ public int getOnlineLogFileCount() { return onlineLogFileCount; } public boolean isPastHalfActive() { return (onlineLogFileCount/2.f) < activeLogFileCount.get(); } synchronized public Location getFirstRecordLocationOfSecondActiveLogFile() { return firstActiveNode.getNextActive().getFirstRecordLocation(); } synchronized public boolean canActivateNextLogFile() { return firstInactiveNode!=null; } } LogFileNode.java000066400000000000000000000102261156157346200340010ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * @version $Revision: 1.1 $ */ final class LogFileNode { static final public int SERIALIZED_SIZE = 10; private final LogFile logFile; private LogFileNode next; /** The id of the log file. */ private int id; /** Does it have live records in it? */ private boolean active = false; /** Is the log file in readonly mode */ private boolean readOnly; /** The location of the next append offset */ private int appendOffset = 0; public LogFileNode(LogFile logFile) { this.logFile = logFile; } public LogFile getLogFile() { return logFile; } ///////////////////////////////////////////////////////////// // // Method used to mange the state of the log file. // ///////////////////////////////////////////////////////////// public void activate(int id) { if (active) throw new IllegalStateException("Log already active."); this.id = id; this.readOnly = false; this.active = true; this.appendOffset = 0; } public int getId() { return id; } public void setReadOnly(boolean enable) { if (!active) throw new IllegalStateException("Log not active."); this.readOnly = enable; } public void deactivate() throws IOException { if (!active) throw new IllegalStateException("Log already inactive."); this.active=false; this.id = -1; this.readOnly = true; this.appendOffset = 0; getLogFile().resize(); } public boolean isActive() { return active; } public int getAppendOffset() { return appendOffset; } public Location getFirstRecordLocation() { if (isActive() && appendOffset > 0) return new Location(getId(), 0); return null; } public boolean isReadOnly() { return readOnly; } public void appended(int i) { appendOffset += i; } ///////////////////////////////////////////////////////////// // // Method used to maintain the list of LogFileNodes used by // the LogFileManager // ///////////////////////////////////////////////////////////// public LogFileNode getNext() { return next; } public void setNext(LogFileNode state) { next = state; } public LogFileNode getNextActive() { if (getNext().isActive()) return getNext(); return null; } public LogFileNode getNextInactive() { if (!getNext().isActive()) return getNext(); return null; } /** * @param data * @throws IOException */ public void writeExternal(DataOutput data) throws IOException { data.writeInt(id); data.writeBoolean(active); data.writeBoolean(readOnly); data.writeInt(appendOffset); } /** * @param data * @throws IOException */ public void readExternal(DataInput data) throws IOException { id = data.readInt(); active = data.readBoolean(); readOnly = data.readBoolean(); appendOffset = data.readInt(); } public void setAppendOffset(int offset) { appendOffset = offset; } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/Record.java000066400000000000000000000232151156157346200331510ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.util.zip.CRC32; import org.apache.activeio.adapter.PacketOutputStream; import org.apache.activeio.adapter.PacketToInputStream; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.Packet; /** * Serializes/Deserializes data records. * * @version $Revision: 1.1 $ */ final public class Record { static final public int RECORD_HEADER_SIZE=8+Location.SERIALIZED_SIZE; static final public int RECORD_FOOTER_SIZE=12+Location.SERIALIZED_SIZE; static final public int RECORD_BASE_SIZE=RECORD_HEADER_SIZE+RECORD_FOOTER_SIZE; static final public byte[] START_OF_RECORD = new byte[] { 'S', 'o', 'R' }; static final public byte[] END_OF_RECORD = new byte[] { 'E', 'o', 'R', '.' }; static final public int SELECTED_CHECKSUM_ALGORITHIM; static final public int NO_CHECKSUM_ALGORITHIM=0; static final public int HASH_CHECKSUM_ALGORITHIM=1; static final public int CRC32_CHECKSUM_ALGORITHIM=2; static { String type = System.getProperty("org.apache.activeio.journal.active.SELECTED_CHECKSUM_ALGORITHIM", "none"); if( "none".equals(type) ) { SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM; } else if( "crc32".equals(type) ) { SELECTED_CHECKSUM_ALGORITHIM = CRC32_CHECKSUM_ALGORITHIM; } else if( "hash".equals(type) ) { SELECTED_CHECKSUM_ALGORITHIM = HASH_CHECKSUM_ALGORITHIM; } else { System.err.println("System property 'org.apache.activeio.journal.active.SELECTED_CHECKSUM_ALGORITHIM' not set properly. Valid values are: 'none', 'hash', or 'crc32'"); SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM; } } static public boolean isChecksumingEnabled() { return SELECTED_CHECKSUM_ALGORITHIM!=NO_CHECKSUM_ALGORITHIM; } private final ByteArrayPacket headerFooterPacket = new ByteArrayPacket(new byte[RECORD_BASE_SIZE]); private final DataOutputStream headerFooterData = new DataOutputStream(new PacketOutputStream(headerFooterPacket)); private int payloadLength; private Location location; private byte recordType; private long checksum; private Location mark; private Packet payload; public Record() { } public Record(byte recordType, Packet payload, Location mark) throws IOException { this(null, recordType, payload, mark); } public Record(Location location, byte recordType, Packet payload, Location mark) throws IOException { this.location = location; this.recordType = recordType; this.mark = mark; this.payload = payload.slice(); this.payloadLength = payload.remaining(); if( isChecksumingEnabled() ) { checksum(new DataInputStream(new PacketToInputStream(this.payload))); } writeHeader(headerFooterData); writeFooter(headerFooterData); } public void setLocation(Location location) throws IOException { this.location = location; headerFooterPacket.clear(); headerFooterPacket.position(8); location.writeToDataOutput(headerFooterData); headerFooterPacket.position(RECORD_HEADER_SIZE+8); location.writeToDataOutput(headerFooterData); payload.clear(); headerFooterPacket.position(0); headerFooterPacket.limit(RECORD_HEADER_SIZE); } private void writeHeader( DataOutput out ) throws IOException { out.write(START_OF_RECORD); out.writeByte(recordType); out.writeInt(payloadLength); if( location!=null ) location.writeToDataOutput(out); else out.writeLong(0); } public void readHeader( DataInput in ) throws IOException { readAndCheckConstant(in, START_OF_RECORD, "Invalid record header: start of record constant missing."); recordType = in.readByte(); payloadLength = in.readInt(); if( payloadLength < 0 ) throw new IOException("Invalid record header: record length cannot be less than zero."); location = Location.readFromDataInput(in); } private void writeFooter( DataOutput out ) throws IOException { out.writeLong(checksum); if( location!=null ) location.writeToDataOutput(out); else out.writeLong(0); out.write(END_OF_RECORD); } public void readFooter( DataInput in ) throws IOException { long l = in.readLong(); if( isChecksumingEnabled() ) { if( l!=checksum ) throw new IOException("Invalid record footer: checksum does not match."); } else { checksum = l; } Location loc = Location.readFromDataInput(in); if( !loc.equals(location) ) throw new IOException("Invalid record footer: location id does not match."); readAndCheckConstant(in, END_OF_RECORD, "Invalid record header: end of record constant missing."); } /** * @param randomAccessFile * @throws IOException */ public void checksum(DataInput in) throws IOException { if( SELECTED_CHECKSUM_ALGORITHIM==HASH_CHECKSUM_ALGORITHIM ) { byte buffer[] = new byte[1024]; byte rc[] = new byte[8]; for (int i = 0; i < payloadLength;) { int l = Math.min(buffer.length, payloadLength-i); in.readFully(buffer,0,l); for (int j = 0; j < l; j++) { rc[j%8] ^= buffer[j]; } i+=l; } checksum = (rc[0])|(rc[1]<<1)|(rc[2]<<2)|(rc[3]<<3)|(rc[4]<<4)|(rc[5]<<5)|(rc[6]<<6)|(rc[7]<<7) ; } else if( SELECTED_CHECKSUM_ALGORITHIM==CRC32_CHECKSUM_ALGORITHIM ) { byte buffer[] = new byte[1024]; CRC32 crc32 = new CRC32(); for (int i = 0; i < payloadLength;) { int l = Math.min(buffer.length, payloadLength-i); in.readFully(buffer,0,l); crc32.update(buffer,0,l); i+=l; } checksum = crc32.getValue(); } else { checksum = 0L; } } /** */ private void readAndCheckConstant(DataInput in, byte[] byteConstant, String errorMessage ) throws IOException { for (int i = 0; i < byteConstant.length; i++) { byte checkByte = byteConstant[i]; if( in.readByte()!= checkByte ) { throw new IOException(errorMessage); } } } public boolean readFromPacket(Packet packet) throws IOException { Packet dup = packet.duplicate(); if( dup.remaining() < RECORD_HEADER_SIZE ) return false; DataInputStream is = new DataInputStream(new PacketToInputStream(dup)); readHeader( is ); if( dup.remaining() < payloadLength+RECORD_FOOTER_SIZE ) { return false; } // Set limit to create a slice of the payload. dup.limit(dup.position()+payloadLength); this.payload = dup.slice(); if( isChecksumingEnabled() ) { checksum(new DataInputStream(new PacketToInputStream(payload))); } // restore the limit and seek to the footer. dup.limit(packet.limit()); dup.position(dup.position()+payloadLength); readFooter(is); // If every thing went well.. advance the position of the orignal packet. packet.position(dup.position()); dup.dispose(); return true; } /** * @return Returns the checksum. */ public long getChecksum() { return checksum; } /** * @return Returns the length. */ public int getPayloadLength() { return payloadLength; } /** * @return Returns the length of the record . */ public int getRecordLength() { return payloadLength+Record.RECORD_BASE_SIZE; } /** * @return Returns the location. */ public Location getLocation() { return location; } /** * @return Returns the mark. */ public Location getMark() { return mark; } /** * @return Returns the payload. */ public Packet getPayload() { return payload; } /** * @return Returns the recordType. */ public byte getRecordType() { return recordType; } public boolean hasRemaining() { return headerFooterPacket.position()!=RECORD_BASE_SIZE; } public void read(Packet packet) { // push the header headerFooterPacket.read(packet); // push the payload. payload.read(packet); // Can we switch to the footer now? if( !payload.hasRemaining() && headerFooterPacket.position()==RECORD_HEADER_SIZE ) { headerFooterPacket.position(RECORD_HEADER_SIZE); headerFooterPacket.limit(RECORD_BASE_SIZE); headerFooterPacket.read(packet); } } public void dispose() { if( payload!=null ) { payload.dispose(); payload=null; } } } RecordInfo.java000066400000000000000000000034511156157346200337060ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; /** * @version $Revision: 1.1 $ */ final public class RecordInfo { private final Location location; private final Record header; private final LogFileNode logFileState; private final LogFile logFile; public RecordInfo(Location location, Record header, LogFileNode logFileState, LogFile logFile) { this.location = location; this.header = header; this.logFileState = logFileState; this.logFile = logFile; } int getNextLocation() { return location.getLogFileOffset() + header.getPayloadLength() + Record.RECORD_BASE_SIZE; } public Record getHeader() { return header; } public Location getLocation() { return location; } public LogFileNode getLogFileState() { return logFileState; } public LogFile getLogFile() { return logFile; } public int getDataOffset() { return location.getLogFileOffset() + Record.RECORD_HEADER_SIZE; } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/active/package.html000066400000000000000000000017531156157346200333540ustar00rootroot00000000000000

The Active Journal is a high performance Journal implemenation which does not place limits on how big the data being logged can be.

activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/howl/000077500000000000000000000000001156157346200305635ustar00rootroot00000000000000HowlJournal.java000066400000000000000000000151041156157346200336140ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/howl/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.howl; import java.io.IOException; import java.io.InterruptedIOException; import org.apache.activeio.journal.InvalidRecordLocationException; import org.apache.activeio.journal.Journal; import org.apache.activeio.journal.JournalEventListener; import org.apache.activeio.journal.RecordLocation; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.Packet; import org.objectweb.howl.log.Configuration; import org.objectweb.howl.log.InvalidFileSetException; import org.objectweb.howl.log.InvalidLogBufferException; import org.objectweb.howl.log.InvalidLogKeyException; import org.objectweb.howl.log.LogConfigurationException; import org.objectweb.howl.log.LogEventListener; import org.objectweb.howl.log.LogRecord; import org.objectweb.howl.log.Logger; /** * An implementation of the Journal interface using a HOWL logger. This is is a thin * wrapper around a HOWL logger. * * This implementation can be used to write records but not to retreive them * yet. Once the HOWL logger implements the methods needed to retreive * previously stored records, this class can be completed. * * @version $Revision: 1.2 $ */ public class HowlJournal implements Journal { private final Logger logger; private RecordLocation lastMark; public HowlJournal(Configuration configuration) throws InvalidFileSetException, LogConfigurationException, InvalidLogBufferException, ClassNotFoundException, IOException, InterruptedException { this.logger = new Logger(configuration); this.logger.open(); lastMark = new LongRecordLocation(logger.getActiveMark()); } /** * @see org.apache.activeio.journal.Journal#write(byte[], boolean) */ public RecordLocation write(Packet packet, boolean sync) throws IOException { try { return new LongRecordLocation(logger.put(packet.sliceAsBytes(), sync)); } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException() .initCause(e); } catch (IOException e) { throw e; } catch (Exception e) { throw (IOException) new IOException("Journal write failed: " + e) .initCause(e); } } /** * @see org.apache.activeio.journal.Journal#setMark(org.codehaus.activemq.journal.RecordLocation, boolean) */ public void setMark(RecordLocation recordLocator, boolean force) throws InvalidRecordLocationException, IOException { try { long location = toLong(recordLocator); logger.mark(location, force); lastMark = recordLocator; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException() .initCause(e); } catch (IOException e) { throw e; } catch (InvalidLogKeyException e) { throw new InvalidRecordLocationException(e.getMessage(), e); } catch (Exception e) { throw (IOException) new IOException("Journal write failed: " + e) .initCause(e); } } /** * @param recordLocator * @return * @throws InvalidRecordLocationException */ private long toLong(RecordLocation recordLocator) throws InvalidRecordLocationException { if (recordLocator == null || recordLocator.getClass() != LongRecordLocation.class) throw new InvalidRecordLocationException(); long location = ((LongRecordLocation) recordLocator) .getLongLocation(); return location; } /** * @see org.apache.activeio.journal.Journal#getMark() */ public RecordLocation getMark() { return lastMark; } /** * @see org.apache.activeio.journal.Journal#close() */ public void close() throws IOException { try { logger.close(); } catch (IOException e) { throw e; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException() .initCause(e); } catch (Exception e) { throw (IOException) new IOException("Journal close failed: " + e) .initCause(e); } } /** * @see org.apache.activeio.journal.Journal#setJournalEventListener(org.codehaus.activemq.journal.JournalEventListener) */ public void setJournalEventListener(final JournalEventListener eventListener) { logger.setLogEventListener(new LogEventListener() { public void logOverflowNotification(long key) { eventListener.overflowNotification(new LongRecordLocation(key)); } }); } /** * @see org.apache.activeio.journal.Journal#getNextRecordLocation(org.codehaus.activemq.journal.RecordLocation) */ public RecordLocation getNextRecordLocation(RecordLocation lastLocation) throws InvalidRecordLocationException { if( lastLocation ==null ) { if( this.lastMark !=null ) { lastLocation = lastMark; } else { return null; } } try { while(true) { LogRecord record = logger.get(null, toLong(lastLocation)); // I assume getNext will return null if there is no next record. LogRecord next = logger.getNext(record); if( next==null || next.length == 0 ) return null; lastLocation = new LongRecordLocation(next.key); if( !next.isCTRL() ) return lastLocation; } } catch (Exception e) { throw (InvalidRecordLocationException)new InvalidRecordLocationException().initCause(e); } } /** * @see org.apache.activeio.journal.Journal#read(org.codehaus.activemq.journal.RecordLocation) */ public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException { try { LogRecord record = logger.get(null, toLong(location)); return new ByteArrayPacket(record.data); } catch (InvalidLogKeyException e) { throw new InvalidRecordLocationException(e.getMessage(), e); } catch (Exception e) { throw (IOException) new IOException("Journal write failed: " + e) .initCause(e); } } } LongRecordLocation.java000066400000000000000000000040001156157346200350700ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/howl/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.howl; import org.apache.activeio.journal.RecordLocation; /** * Provides a RecordLocation implementation for the long based * location pointers that HOWL uses. * * @version $Revision: 1.1 $ */ public class LongRecordLocation implements RecordLocation { final private long location; public LongRecordLocation(long l) { this.location = l; } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { return (int) (location - ((LongRecordLocation) o).location); } /** * @return the original long location provided by HOWL */ public long getLongLocation() { return location; } /** * @see java.lang.Object#hashCode() */ public int hashCode() { int lowPart = (int) (0xFFFFFFFF & location); int highPart = (int) (0xFFFFFFFF & (location >> 4)); return lowPart ^ highPart; } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || o.getClass() != LongRecordLocation.class) return false; return ((LongRecordLocation) o).location == location; } /** * @see java.lang.Object#toString() */ public String toString() { return "0x" + Long.toHexString(location); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/howl/package.html000066400000000000000000000017561156157346200330550ustar00rootroot00000000000000

A Journal implemenation using using a high performance transaction log implemented using Howl

activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/journal/package.html000066400000000000000000000017031156157346200320740ustar00rootroot00000000000000

Provides the API for storing and accessing record based binary data in sequential log files.

activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/000077500000000000000000000000001156157346200276265ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java000066400000000000000000000042061156157346200334420ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; import java.util.HashSet; import org.apache.activeio.packet.Packet; public class HttpRecognizer implements ProtocolRecognizer { static private HashSet methods = new HashSet(); static { // This list built using: http://www.w3.org/Protocols/HTTP/Methods.html methods.add("GET "); methods.add("PUT "); methods.add("POST "); methods.add("HEAD "); methods.add("LINK "); methods.add("TRACE "); methods.add("UNLINK "); methods.add("SEARCH "); methods.add("DELETE "); methods.add("CHECKIN "); methods.add("OPTIONS "); methods.add("CONNECT "); methods.add("CHECKOUT "); methods.add("SPACEJUMP "); methods.add("SHOWMETHOD "); methods.add("TEXTSEARCH "); } static final public HttpRecognizer HTTP_RECOGNIZER = new HttpRecognizer(); private HttpRecognizer() {} public boolean recognizes(Packet packet) { StringBuffer b = new StringBuffer(12); for (int i = 0; i < 11; i++) { int c = (char)packet.read(); if( c == -1) return false; b.append((char)c); if(((char)c)==' ') break; } return methods.contains(b.toString()); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java000066400000000000000000000024201156157346200332570ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; import org.apache.activeio.packet.Packet; public class IIOPRecognizer implements ProtocolRecognizer { static final public IIOPRecognizer IIOP_RECOGNIZER = new IIOPRecognizer(); private IIOPRecognizer() {} public boolean recognizes(Packet packet) { return ( packet.read()=='G' && packet.read()=='I' && packet.read()=='O' && packet.read()=='P' ); } } ProtocolRecognizer.java000066400000000000000000000017151156157346200342470ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; import org.apache.activeio.packet.Packet; /** * */ public interface ProtocolRecognizer { boolean recognizes(Packet packet); } UnknownRecognizer.java000066400000000000000000000023141156157346200341010ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; import org.apache.activeio.packet.Packet; class UnknownRecognizer implements ProtocolRecognizer { static public final ProtocolRecognizer UNKNOWN_RECOGNIZER = new UnknownRecognizer(); private UnknownRecognizer() { } public boolean recognizes(Packet packet) { if( packet.limit() > 15 ) return true; return false; } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/package.html000066400000000000000000000021361156157346200321110ustar00rootroot00000000000000

This package provides the implementing classes that allow you to run multiple protocols from a sigle port. The only restriction is that all the protococols sharing the port must provide a magic number in the intial request message to the server.

activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/000077500000000000000000000000001156157346200274075ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/AppendedPacket.java000066400000000000000000000154161156157346200331310ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; /** * Appends two packets together. * * @version $Revision$ */ final public class AppendedPacket implements Packet { private final Packet first; private final Packet last; private final int capacity; private final int firstCapacity; static public Packet join(Packet first, Packet last) { if( first.hasRemaining() ) { if( last.hasRemaining() ) { //TODO: this might even be a rejoin of the same continous buffer. //It would be good if we detected that and avoided just returned the buffer. return new AppendedPacket(first.slice(), last.slice()); } else { return first.slice(); } } else { if( last.hasRemaining() ) { return last.slice(); } else { return EmptyPacket.EMPTY_PACKET; } } } /** * @deprecated use {@see #join(Packet, Packet)} instead. */ public AppendedPacket(Packet first, Packet second) { this.first = first; this.last = second; this.firstCapacity = first.capacity(); this.capacity = first.capacity()+last.capacity(); clear(); } public void position(int position) { if( position <= firstCapacity ) { last.position(0); first.position(position); } else { last.position(position-firstCapacity); first.position(firstCapacity); } } public void limit(int limit) { if( limit <= firstCapacity ) { last.limit(0); first.limit(limit); } else { last.limit(limit-firstCapacity); first.limit(firstCapacity); } } public Packet slice() { return join(first,last); } public Packet duplicate() { return new AppendedPacket(first.duplicate(), last.duplicate()); } public Object duplicate(ClassLoader cl) throws IOException { try { Class pclazz = cl.loadClass(Packet.class.getName()); Class clazz = cl.loadClass(AppendedPacket.class.getName()); Constructor constructor = clazz.getConstructor(new Class[]{pclazz, pclazz}); return constructor.newInstance(new Object[]{first.duplicate(cl), last.duplicate(cl)}); } catch (Throwable e) { throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e); } } public void flip() { limit(position()); position(0); } public int position() { return first.position()+last.position(); } public int limit() { return first.limit()+last.limit(); } public int remaining() { return first.remaining()+last.remaining(); } public void rewind() { first.rewind(); last.rewind(); } public boolean hasRemaining() { return first.hasRemaining()||last.hasRemaining(); } public void clear() { first.clear(); last.clear(); } public int capacity() { return capacity; } public void writeTo(OutputStream out) throws IOException { first.writeTo(out); last.writeTo(out); } public void writeTo(DataOutput out) throws IOException { first.writeTo(out); last.writeTo(out); } /** * @see org.apache.activeio.packet.Packet#read() */ public int read() { if( first.hasRemaining() ) { return first.read(); } else if( last.hasRemaining() ) { return last.read(); } else { return -1; } } /** * @see org.apache.activeio.packet.Packet#read(byte[], int, int) */ public int read(byte[] data, int offset, int length) { int rc1 = first.read(data, offset, length); if( rc1==-1 ) { int rc2 = last.read(data, offset, length); return ( rc2==-1 ) ? -1 : rc2; } else { int rc2 = last.read(data, offset+rc1, length-rc1); return ( rc2==-1 ) ? rc1 : rc1+rc2; } } /** * @see org.apache.activeio.packet.Packet#write(int) */ public boolean write(int data) { if( first.hasRemaining() ) { return first.write(data); } else if( last.hasRemaining() ) { return last.write(data); } else { return false; } } /** * @see org.apache.activeio.packet.Packet#write(byte[], int, int) */ public int write(byte[] data, int offset, int length) { int rc1 = first.write(data, offset, length); if( rc1==-1 ) { int rc2 = last.write(data, offset, length); return ( rc2==-1 ) ? -1 : rc2; } else { int rc2 = last.write(data, offset+rc1, length-rc1); return ( rc2==-1 ) ? rc1 : rc1+rc2; } } public int read(Packet dest) { int rc = first.read(dest); rc += last.read(dest); return rc; } public String toString() { return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}"; } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } Object object = first.getAdapter(target); if( object == null ) object = last.getAdapter(target); return object; } public ByteSequence asByteSequence() { // TODO: implement me return null; } public byte[] sliceAsBytes() { // TODO: implement me return null; } public void dispose() { first.dispose(); last.dispose(); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/ByteArrayPacket.java000066400000000000000000000146771156157346200333230ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; /** * Provides a Packet implementation that is directly backed by a byte[]. * * @version $Revision$ */ final public class ByteArrayPacket implements Packet { private final byte buffer[]; private final int offset; private final int capacity; private int position; private int limit; private int remaining; public ByteArrayPacket(byte buffer[]) { this(buffer,0, buffer.length); } public ByteArrayPacket(ByteSequence sequence) { this(sequence.getData(), sequence.getOffset(), sequence.getLength()); } public ByteArrayPacket(byte buffer[], int offset, int capacity) { this.buffer = buffer; this.offset=offset; this.capacity=capacity; this.position = 0; this.limit = capacity; this.remaining = limit-position; } public int position() { return position; } public void position(int position) { this.position = position; remaining = limit-position; } public int limit() { return limit; } public void limit(int limit) { this.limit = limit; remaining = limit-position; } public void flip() { limit = position; position = 0; remaining = limit - position; } public int remaining() { return remaining; } public void rewind() { position = 0; remaining = limit - position; } public boolean hasRemaining() { return remaining > 0; } public void clear() { position = 0; limit = capacity; remaining = limit - position; } public int capacity() { return capacity; } public Packet slice() { return new ByteArrayPacket(buffer, offset+position, remaining); } public Packet duplicate() { return new ByteArrayPacket(buffer, offset, capacity); } public Object duplicate(ClassLoader cl) throws IOException { try{ Class clazz = cl.loadClass(ByteArrayPacket.class.getName()); Constructor constructor = clazz.getConstructor(new Class[]{byte[].class, int.class, int.class}); return constructor.newInstance(new Object[]{buffer, new Integer(offset), new Integer(capacity())}); } catch (Throwable e) { throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e); } } public void writeTo(OutputStream out) throws IOException { out.write(buffer, offset+position, remaining); position=limit; remaining = limit-position; } public void writeTo(DataOutput out) throws IOException { out.write(buffer, offset+position, remaining); position=limit; remaining = limit-position; } /** * @see org.apache.activeio.packet.Packet#read() */ public int read() { if( !(remaining > 0) ) return -1; int rc = buffer[offset+position]; position++; remaining = limit-position; return rc & 0xff; } /** * @see org.apache.activeio.packet.Packet#read(byte[], int, int) */ public int read(byte[] data, int offset, int length) { if( !(remaining > 0) ) return -1; int copyLength = ((length <= remaining) ? length : remaining); System.arraycopy(buffer, this.offset+position, data, offset, copyLength); position += copyLength; remaining = limit-position; return copyLength; } /** * @see org.apache.activeio.packet.Packet#write(int) */ public boolean write(int data) { if( !(remaining > 0) ) return false; buffer[offset+position]=(byte) data; position++; remaining = limit-position; return true; } /** * @see org.apache.activeio.packet.Packet#write(byte[], int, int) */ public int write(byte[] data, int offset, int length) { if( !(remaining > 0) ) return -1; int copyLength = ((length <= remaining) ? length : remaining); System.arraycopy(data, offset, buffer, this.offset+position, copyLength); position+=copyLength; remaining = limit-position; return copyLength; } public ByteSequence asByteSequence() { return new ByteSequence(buffer, offset+position, remaining); } /** * @see org.apache.activeio.packet.Packet#sliceAsBytes() */ public byte[] sliceAsBytes() { if( buffer.length == remaining ) { return buffer; } else { byte rc[] = new byte[remaining]; int op = position; read(rc,0,remaining); position=op; remaining = limit-position; return rc; } } /** * @param dest * @return the number of bytes read into the dest. */ public int read(Packet dest) { int a = dest.remaining(); int rc = ((a <= remaining) ? a : remaining); if( rc > 0 ) { dest.write( buffer, offset+position, rc); position = position+rc; remaining = limit-position; } return rc; } public String toString() { return "{position="+position+",limit="+limit+",capacity="+capacity+"}"; } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } return null; } public byte[] getBuffer() { return buffer; } public void dispose() { } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacket.java000066400000000000000000000202361156157346200334420ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.nio.ByteBuffer; /** * Provides a Packet implementation that is backed by a {@see java.nio.ByteBuffer} * * @version $Revision$ */ final public class ByteBufferPacket implements Packet { public static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.DefaultByteBufferSize", ""+(64*1024))); public static final int DEFAULT_DIRECT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.DefaultDirectByteBufferSize", ""+(8*1024))); private final ByteBuffer buffer; private static final int TEMP_BUFFER_SIZE = 64*1024; public ByteBufferPacket(ByteBuffer buffer) { this.buffer = buffer; clear(); } public ByteBuffer getByteBuffer() { return buffer; } public static ByteBufferPacket createDefaultBuffer(boolean direct) { if( direct ) return new ByteBufferPacket( ByteBuffer.allocateDirect(DEFAULT_DIRECT_BUFFER_SIZE) ); return new ByteBufferPacket( ByteBuffer.allocate(DEFAULT_BUFFER_SIZE) ); } public void writeTo(OutputStream out) throws IOException { if( buffer.hasArray() ) { // If the buffer is backed by an array.. then use it directly. out.write(buffer.array(), position(), remaining()); position(limit()); } else { // It's not backed by a buffer.. We can only dump it to a OutputStream via a byte[] so, // create a temp buffer that we can use to chunk it out. byte temp[] = new byte[TEMP_BUFFER_SIZE]; while( buffer.hasRemaining() ) { int maxWrite = buffer.remaining() > temp.length ? temp.length : buffer.remaining(); buffer.get(temp, 0, maxWrite); out.write(temp,0, maxWrite); } } } public void writeTo(DataOutput out) throws IOException { if( buffer.hasArray() ) { // If the buffer is backed by an array.. then use it directly. out.write(buffer.array(), position(), remaining()); position(limit()); } else { // It's not backed by a buffer.. We can only dump it to a OutputStream via a byte[] so, // create a temp buffer that we can use to chunk it out. byte temp[] = new byte[TEMP_BUFFER_SIZE]; while( buffer.hasRemaining() ) { int maxWrite = buffer.remaining() > temp.length ? temp.length : buffer.remaining(); buffer.get(temp, 0, maxWrite); out.write(temp,0, maxWrite); } } } public int capacity() { return buffer.capacity(); } public void clear() { buffer.clear(); } public Packet compact() { buffer.compact(); return this; } public void flip() { buffer.flip(); } public boolean hasRemaining() { return buffer.hasRemaining(); } public boolean isDirect() { return buffer.isDirect(); } public boolean isReadOnly() { return buffer.isReadOnly(); } public int limit() { return buffer.limit(); } public void limit(int arg0) { buffer.limit(arg0); } public Packet mark() { buffer.mark(); return this; } public int position() { return buffer.position(); } public void position(int arg0) { buffer.position(arg0); } public int remaining() { return buffer.remaining(); } public void rewind() { buffer.rewind(); } public Packet slice() { return new ByteBufferPacket(buffer.slice()); } public Packet duplicate() { return new ByteBufferPacket(buffer.duplicate()); } public Object duplicate(ClassLoader cl) throws IOException { try { Class clazz = cl.loadClass(ByteBufferPacket.class.getName()); Constructor constructor = clazz.getConstructor(new Class[]{ByteBuffer.class}); return constructor.newInstance(new Object[]{buffer.duplicate()}); } catch (Throwable e) { throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e); } } /** * @see org.apache.activeio.packet.Packet#read() */ public int read() { if( !buffer.hasRemaining() ) return -1; return buffer.get() & 0xff; } /** * @see org.apache.activeio.packet.Packet#read(byte[], int, int) */ public int read(byte[] data, int offset, int length) { if( !hasRemaining() ) return -1; int copyLength = Math.min(length, remaining()); buffer.get(data, offset, copyLength); return copyLength; } /** * @see org.apache.activeio.packet.Packet#write(int) */ public boolean write(int data) { if( !buffer.hasRemaining() ) return false; buffer.put((byte)data); return true; } /** * @see org.apache.activeio.packet.Packet#write(byte[], int, int) */ public int write(byte[] data, int offset, int length) { if( !hasRemaining() ) return -1; int copyLength = Math.min(length, remaining()); buffer.put(data, offset, copyLength); return copyLength; } /** * @see org.apache.activeio.packet.Packet#asByteSequence() */ public ByteSequence asByteSequence() { if( buffer.hasArray() ) { byte[] bs = buffer.array(); return new ByteSequence(bs, buffer.position(), buffer.remaining()); } else { byte[] bs = new byte[buffer.remaining()]; int p = buffer.position(); buffer.get(bs); buffer.position(p); return new ByteSequence(bs, 0, bs.length); } } /** * @see org.apache.activeio.packet.Packet#sliceAsBytes() */ public byte[] sliceAsBytes() { // TODO Auto-generated method stub return null; } /** * @param dest * @return the number of bytes read into the dest. */ public int read(Packet dest) { int rc = Math.min(dest.remaining(), remaining()); if( rc > 0 ) { if( dest.getClass() == ByteBufferPacket.class ) { // Adjust our limit so that we don't overflow the dest buffer. int limit = limit(); limit(position()+rc); ((ByteBufferPacket)dest).buffer.put(buffer); // restore the limit. limit(limit); return 0; } else { ByteSequence sequence = dest.asByteSequence(); rc = read(sequence.getData(), sequence.getOffset(), sequence.getLength()); dest.position(dest.position()+rc); } } return rc; } public String toString() { return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}"; } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } return null; } public void dispose() { } } ByteBufferPacketPool.java000066400000000000000000000030711156157346200342130ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.nio.ByteBuffer; /** * Provides a simple pool of ByteBuffer objects. * * @version $Revision: 1.1 $ */ final public class ByteBufferPacketPool extends PacketPool { private final int packetSize; /** * Creates a pool of bufferCount ByteBuffers that are * directly allocated being bufferSize big. * * @param packetCount the number of buffers that will be in the pool. * @param packetSize the size of the buffers that are in the pool. */ public ByteBufferPacketPool(int packetCount,int packetSize) { super(packetCount); this.packetSize = packetSize; } protected Packet allocateNewPacket() { return new ByteBufferPacket(ByteBuffer.allocateDirect(packetSize)); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/BytePacket.java000066400000000000000000000117651156157346200323170ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; /** * Provides a Packet implementation that is directly backed by a byte. * * @version $Revision$ */ final public class BytePacket implements Packet { private byte data; private byte position; private byte limit; public BytePacket(byte data) { this.data = data; clear(); } public int position() { return position; } public void position(int position) { this.position = (byte) position; } public int limit() { return limit; } public void limit(int limit) { this.limit = (byte) limit; } public void flip() { limit(position()); position(0); } public int remaining() { return limit() - position(); } public void rewind() { position(0); } public boolean hasRemaining() { return remaining() > 0; } public void clear() { position(0); limit(capacity()); } public int capacity() { return 1; } public Packet slice() { if( hasRemaining() ) return new BytePacket(data); return EmptyPacket.EMPTY_PACKET; } public Packet duplicate() { BytePacket packet = new BytePacket(data); packet.limit(limit()); packet.position(position()); return packet; } public Object duplicate(ClassLoader cl) throws IOException { try { Class clazz = cl.loadClass(BytePacket.class.getName()); Constructor constructor = clazz.getConstructor(new Class[]{byte.class}); return constructor.newInstance(new Object[]{new Byte(data)}); } catch (Throwable e) { throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e); } } public void writeTo(OutputStream out) throws IOException { if( hasRemaining() ) { out.write(data); position(1); } } public void writeTo(DataOutput out) throws IOException { if( hasRemaining() ) { out.write(data); position(1); } } /** * @see org.apache.activeio.packet.Packet#read() */ public int read() { if( !hasRemaining() ) return -1; position(1); return data & 0xff; } /** * @see org.apache.activeio.packet.Packet#read(byte[], int, int) */ public int read(byte[] data, int offset, int length) { if( !hasRemaining() ) return -1; if( length > 0 ) { data[offset] = this.data; position(1); return 1; } return 0; } /** * @see org.apache.activeio.packet.Packet#write(int) */ public boolean write(int data) { if( !hasRemaining() ) return false; this.data = (byte) data; position(1); return true; } /** * @see org.apache.activeio.packet.Packet#write(byte[], int, int) */ public int write(byte[] data, int offset, int length) { if( !hasRemaining() ) return -1; if( length > 0 ) { this.data = data[offset] ; position(1); return 1; } return 0; } public ByteSequence asByteSequence() { return null; } /** * @see org.apache.activeio.packet.Packet#sliceAsBytes() */ public byte[] sliceAsBytes() { return null; } /** * @param dest * @return the number of bytes read into the dest. */ public int read(Packet dest) { if( hasRemaining() ) { dest.write(data); position(1); return 1; } return 0; } public String toString() { return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}"; } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } return null; } public void dispose() { } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/ByteSequence.java000066400000000000000000000023771156157346200326570ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; public class ByteSequence { final byte[] data; final int offset; final int length; public ByteSequence(byte data[], int offset, int length) { this.data = data; this.offset = offset; this.length = length; } public byte[] getData() { return data; } public int getLength() { return length; } public int getOffset() { return offset; } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/EOSPacket.java000066400000000000000000000070161156157346200320340ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; /** * Provides a Packet implementation that is used to represent the end of a stream. * * @version $Revision$ */ final public class EOSPacket implements Packet { static final public EOSPacket EOS_PACKET = new EOSPacket(); private EOSPacket() { } public void writeTo(OutputStream out) throws IOException { } public void writeTo(DataOutput out) throws IOException { } public int position() { return 1; } public void position(int position) { } public int limit() { return 0; } public void limit(int limit) { } public void flip() { } public int remaining() { return -1; } public void rewind() { } public boolean hasRemaining() { return false; } public void clear() { } public int capacity() { return 0; } public Packet slice() { return this; } public Packet duplicate() { return this; } public Object duplicate(ClassLoader cl) throws IOException { try { Class clazz = cl.loadClass(EOSPacket.class.getName()); return clazz.getField("EOS_PACKET").get(null); } catch (Throwable e) { throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e); } } /** * @see org.apache.activeio.packet.Packet#read() */ public int read() { return -1; } /** * @see org.apache.activeio.packet.Packet#read(byte[], int, int) */ public int read(byte[] data, int offset, int length) { return -1; } /** * @see org.apache.activeio.packet.Packet#write(int) */ public boolean write(int data) { return false; } /** * @see org.apache.activeio.packet.Packet#write(byte[], int, int) */ public int write(byte[] data, int offset, int length) { return -1; } public ByteSequence asByteSequence() { return EmptyPacket.EMPTY_BYTE_SEQUENCE; } public byte[] sliceAsBytes() { return EmptyPacket.EMPTY_BYTE_ARRAY; } /** * @param dest * @return the number of bytes read into the dest. */ public int read(Packet dest) { return 0; } public String toString() { return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}"; } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } return null; } public void dispose() { } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/EmptyPacket.java000066400000000000000000000072411156157346200325040ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; /** * Provides a Packet implementation that is directly backed by a byte[0]. * * @version $Revision$ */ final public class EmptyPacket implements Packet { static final public EmptyPacket EMPTY_PACKET = new EmptyPacket(); static final byte EMPTY_BYTE_ARRAY[] = new byte[]{}; static final ByteSequence EMPTY_BYTE_SEQUENCE = new ByteSequence(EMPTY_BYTE_ARRAY,0,0); private EmptyPacket() { } public void writeTo(OutputStream out) throws IOException { } public void writeTo(DataOutput out) throws IOException { } public int position() { return 0; } public void position(int position) { } public int limit() { return 0; } public void limit(int limit) { } public void flip() { } public int remaining() { return 0; } public void rewind() { } public boolean hasRemaining() { return false; } public void clear() { } public int capacity() { return 0; } public Packet slice() { return this; } public Packet duplicate() { return this; } public Object duplicate(ClassLoader cl) throws IOException { try { Class clazz = cl.loadClass(EmptyPacket.class.getName()); return clazz.getField("EMPTY_PACKET").get(null); } catch (Throwable e) { throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e); } } /** * @see org.apache.activeio.packet.Packet#read() */ public int read() { return -1; } /** * @see org.apache.activeio.packet.Packet#read(byte[], int, int) */ public int read(byte[] data, int offset, int length) { return -1; } /** * @see org.apache.activeio.packet.Packet#write(int) */ public boolean write(int data) { return false; } /** * @see org.apache.activeio.packet.Packet#write(byte[], int, int) */ public int write(byte[] data, int offset, int length) { return -1; } public ByteSequence asByteSequence() { return EMPTY_BYTE_SEQUENCE; } public byte[] sliceAsBytes() { return EMPTY_BYTE_ARRAY; } /** * @param dest * @return the number of bytes read into the dest. */ public int read(Packet dest) { return -1; } public String toString() { return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}"; } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } return null; } public void dispose() { } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/FilterPacket.java000066400000000000000000000063221156157346200326320ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; /** * Provides a Packet implementation that filters operations to another packet. * * Used to make it easier to augment the {@see #narrow(Class)}method. * * @version $Revision$ */ public abstract class FilterPacket implements Packet { final protected Packet next; public FilterPacket(Packet next) { this.next = next; } public ByteSequence asByteSequence() { return next.asByteSequence(); } public int capacity() { return next.capacity(); } public void clear() { next.clear(); } public void flip() { next.flip(); } public boolean hasRemaining() { return next.hasRemaining(); } public int limit() { return next.limit(); } public void limit(int limit) { next.limit(limit); } public Object getAdapter(Class target) { if( target.isAssignableFrom(getClass()) ) { return this; } return next.getAdapter(target); } public int position() { return next.position(); } public void position(int position) { next.position(position); } public int read() { return next.read(); } public int read(byte[] data, int offset, int length) { return next.read(data, offset, length); } public int read(Packet dest) { return next.read(dest); } public int remaining() { return next.remaining(); } public void rewind() { next.rewind(); } public byte[] sliceAsBytes() { return next.sliceAsBytes(); } public int write(byte[] data, int offset, int length) { return next.write(data, offset, length); } public boolean write(int data) { return next.write(data); } public void writeTo(OutputStream out) throws IOException { next.writeTo(out); } public void writeTo(DataOutput out) throws IOException { next.writeTo(out); } public Object duplicate(ClassLoader cl) throws IOException { return next.duplicate(cl); } public Packet duplicate() { return filter(next.duplicate()); } public Packet slice() { return filter(next.slice()); } public void dispose() { next.dispose(); } abstract public Packet filter(Packet packet); } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/Packet.java000066400000000000000000000044731156157346200314710ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; /** * Provides a ByteBuffer like interface to work with IO channel packets of data. * * @version $Revision$ */ public interface Packet { public int position(); public void position(int position); public int limit(); public void limit(int limit); public void flip(); public int remaining(); public void rewind(); public boolean hasRemaining(); public void clear(); public Packet slice(); public Packet duplicate(); public Object duplicate(ClassLoader cl) throws IOException; public int capacity(); public void dispose(); public ByteSequence asByteSequence(); public byte[] sliceAsBytes(); /** * @Return object that is an instance of requested type and is associated this this object. May return null if no * object of that type is associated. */ Object getAdapter(Class target); /** * Writes the remaing bytes in the packet to the output stream. * * @param out * @return */ void writeTo(OutputStream out) throws IOException; void writeTo(DataOutput out) throws IOException; // To read data out of the packet. public int read(); public int read(byte data[], int offset, int length); // To write data into the packet. public boolean write( int data ); public int write( byte data[], int offset, int length ); public int read(Packet dest); } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/PacketData.java000066400000000000000000000321361156157346200322600ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.io.EOFException; import java.io.IOException; /** * Used to write and read primitives to and from a Packet. */ final public class PacketData { final private Packet packet; private final boolean bigEndian; public PacketData(Packet packet) { this(packet, true); } public PacketData(Packet packet, boolean bigEndian) { this.packet = packet; this.bigEndian = bigEndian; } private static void spaceNeeded(Packet packet, int space) throws IOException { if (packet.remaining() < space) throw new EOFException("Not enough space left in the packet."); } public void readFully(byte[] b) throws IOException { readFully(packet, b, 0, b.length); } public static void readFully(Packet packet, byte[] b) throws IOException { readFully(packet, b, 0, b.length); } public void readFully(byte[] b, int off, int len) throws IOException { readFully(packet, b, off, len); } public static void readFully(Packet packet, byte[] b, int off, int len) throws IOException { spaceNeeded(packet, len); packet.read(b, off, len); } public int skipBytes(int n) throws IOException { return skipBytes(packet, n); } public static int skipBytes(Packet packet, int n) throws IOException { int rc = Math.min(n, packet.remaining()); packet.position(packet.position() + rc); return rc; } public boolean readBoolean() throws IOException { return readBoolean(packet); } public static boolean readBoolean(Packet packet) throws IOException { spaceNeeded(packet, 1); return packet.read() != 0; } public byte readByte() throws IOException { return readByte(packet); } public static byte readByte(Packet packet) throws IOException { spaceNeeded(packet, 1); return (byte) packet.read(); } public int readUnsignedByte() throws IOException { return readUnsignedByte(packet); } public static int readUnsignedByte(Packet packet) throws IOException { spaceNeeded(packet, 1); return packet.read(); } public short readShort() throws IOException { if( bigEndian ) { return readShortBig(packet); } else { return readShortLittle(packet); } } public static short readShortBig(Packet packet) throws IOException { spaceNeeded(packet, 2); return (short) ((packet.read() << 8) + (packet.read() << 0)); } public static short readShortLittle(Packet packet) throws IOException { spaceNeeded(packet, 2); return (short) ((packet.read() << 0) + (packet.read() << 8) ); } public int readUnsignedShort() throws IOException { if( bigEndian ) { return readUnsignedShortBig(packet); } else { return readUnsignedShortLittle(packet); } } public static int readUnsignedShortBig(Packet packet) throws IOException { spaceNeeded(packet, 2); return ((packet.read() << 8) + (packet.read() << 0)); } public static int readUnsignedShortLittle(Packet packet) throws IOException { spaceNeeded(packet, 2); return ((packet.read() << 0) + (packet.read() << 8) ); } public char readChar() throws IOException { if( bigEndian ) { return readCharBig(packet); } else { return readCharLittle(packet); } } public static char readCharBig(Packet packet) throws IOException { spaceNeeded(packet, 2); return (char) ((packet.read() << 8) + (packet.read() << 0)); } public static char readCharLittle(Packet packet) throws IOException { spaceNeeded(packet, 2); return (char) ((packet.read() << 0) + (packet.read() << 8) ); } public int readInt() throws IOException { if( bigEndian ) { return readIntBig(packet); } else { return readIntLittle(packet); } } public static int readIntBig(Packet packet) throws IOException { spaceNeeded(packet, 4); return ((packet.read() << 24) + (packet.read() << 16) + (packet.read() << 8) + (packet.read() << 0)); } public static int readIntLittle(Packet packet) throws IOException { spaceNeeded(packet, 4); return ((packet.read() << 0) + (packet.read() << 8) + (packet.read() << 16) + (packet.read() << 24)); } public long readLong() throws IOException { if( bigEndian ) { return readLongBig(packet); } else { return readLongLittle(packet); } } public static long readLongBig(Packet packet) throws IOException { spaceNeeded(packet, 8); return (((long) packet.read() << 56) + ((long) packet.read() << 48) + ((long) packet.read() << 40) + ((long) packet.read() << 32) + ((long) packet.read() << 24) + ((packet.read()) << 16) + ((packet.read()) << 8) + ((packet.read()) << 0)); } public static long readLongLittle(Packet packet) throws IOException { spaceNeeded(packet, 8); return ((packet.read() << 0) + (packet.read() << 8) + (packet.read() << 16) + ((long) packet.read() << 24) + ((long) packet.read() << 32) + ((long) packet.read() << 40) + ((long) packet.read() << 48) + ((long) packet.read() << 56)); } public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } public static double readDoubleBig(Packet packet) throws IOException { return Double.longBitsToDouble(readLongBig(packet)); } public static double readDoubleLittle(Packet packet) throws IOException { return Double.longBitsToDouble(readLongLittle(packet)); } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public static float readFloatBig(Packet packet) throws IOException { return Float.intBitsToFloat(readIntBig(packet)); } public static float readFloatLittle(Packet packet) throws IOException { return Float.intBitsToFloat(readIntLittle(packet)); } public void write(int b) throws IOException { write(packet, b); } public static void write(Packet packet, int b) throws IOException { spaceNeeded(packet, 1); packet.write(b); } public void write(byte[] b) throws IOException { write(packet, b, 0, b.length); } public static void write(Packet packet, byte[] b) throws IOException { write(packet, b, 0, b.length); } public void write(byte[] b, int off, int len) throws IOException { write(packet, b, off, len); } public static void write(Packet packet, byte[] b, int off, int len) throws IOException { spaceNeeded(packet, len); packet.write(b, off, len); } public void writeBoolean(boolean v) throws IOException { writeBoolean(packet, v); } public static void writeBoolean(Packet packet, boolean v) throws IOException { spaceNeeded(packet, 1); packet.write(v ? 1 : 0); } public void writeByte(int v) throws IOException { writeByte(packet, v); } public static void writeByte(Packet packet, int v) throws IOException { spaceNeeded(packet, 1); packet.write(v); } public void writeShort(int v) throws IOException { if (bigEndian) { writeShortBig(packet,v); } else { writeShortLittle(packet,v); } } public static void writeShortBig(Packet packet, int v) throws IOException { spaceNeeded(packet, 2); packet.write((v >>> 8) & 0xFF); packet.write((v >>> 0) & 0xFF); } public static void writeShortLittle(Packet packet, int v) throws IOException { spaceNeeded(packet, 2); packet.write((v >>> 0) & 0xFF); packet.write((v >>> 8) & 0xFF); } public void writeChar(int v) throws IOException { if (bigEndian) { writeCharBig(packet, v); } else { writeCharLittle(packet, v); } } public static void writeCharBig(Packet packet, int v) throws IOException { spaceNeeded(packet, 2); packet.write((v >>> 8) & 0xFF); packet.write((v >>> 0) & 0xFF); } public static void writeCharLittle(Packet packet, int v) throws IOException { spaceNeeded(packet, 2); packet.write((v >>> 0) & 0xFF); packet.write((v >>> 8) & 0xFF); } public void writeInt(int v) throws IOException { if (bigEndian) { writeIntBig(packet, v); } else { writeIntLittle(packet, v); } } public static void writeIntBig(Packet packet, int v) throws IOException { spaceNeeded(packet, 4); packet.write((v >>> 24) & 0xFF); packet.write((v >>> 16) & 0xFF); packet.write((v >>> 8) & 0xFF); packet.write((v >>> 0) & 0xFF); } public static void writeIntLittle(Packet packet, int v) throws IOException { spaceNeeded(packet, 4); packet.write((v >>> 0) & 0xFF); packet.write((v >>> 8) & 0xFF); packet.write((v >>> 16) & 0xFF); packet.write((v >>> 24) & 0xFF); } public void writeLong(long v) throws IOException { if (bigEndian) { writeLongBig(packet, v); } else { writeLongLittle(packet, v); } } public static void writeLongBig(Packet packet, long v) throws IOException { spaceNeeded(packet, 8); packet.write((int) (v >>> 56) & 0xFF); packet.write((int) (v >>> 48) & 0xFF); packet.write((int) (v >>> 40) & 0xFF); packet.write((int) (v >>> 32) & 0xFF); packet.write((int) (v >>> 24) & 0xFF); packet.write((int) (v >>> 16) & 0xFF); packet.write((int) (v >>> 8) & 0xFF); packet.write((int) (v >>> 0) & 0xFF); } public static void writeLongLittle(Packet packet, long v) throws IOException { spaceNeeded(packet, 8); packet.write((int) (v >>> 0) & 0xFF); packet.write((int) (v >>> 8) & 0xFF); packet.write((int) (v >>> 16) & 0xFF); packet.write((int) (v >>> 24) & 0xFF); packet.write((int) (v >>> 32) & 0xFF); packet.write((int) (v >>> 40) & 0xFF); packet.write((int) (v >>> 48) & 0xFF); packet.write((int) (v >>> 56) & 0xFF); } public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } public static void writeDoubleBig(Packet packet, double v) throws IOException { writeLongBig(packet, Double.doubleToLongBits(v)); } public static void writeDoubleLittle(Packet packet, double v) throws IOException { writeLongLittle(packet, Double.doubleToLongBits(v)); } public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } public static void writeFloatBig(Packet packet, float v) throws IOException { writeIntBig(packet, Float.floatToIntBits(v)); } public static void writeFloatLittle(Packet packet, float v) throws IOException { writeIntLittle(packet, Float.floatToIntBits(v)); } public void writeRawDouble(double v) throws IOException { writeLong(Double.doubleToRawLongBits(v)); } public static void writeRawDoubleBig(Packet packet, double v) throws IOException { writeLongBig(packet, Double.doubleToRawLongBits(v)); } public static void writeRawDoubleLittle(Packet packet, double v) throws IOException { writeLongLittle(packet, Double.doubleToRawLongBits(v)); } public void writeRawFloat(float v) throws IOException { writeInt(Float.floatToRawIntBits(v)); } public static void writeRawFloatBig(Packet packet, float v) throws IOException { writeIntBig(packet, Float.floatToRawIntBits(v)); } public static void writeRawFloatLittle(Packet packet, float v) throws IOException { writeIntLittle(packet, Float.floatToRawIntBits(v)); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/PacketPool.java000066400000000000000000000101701156157346200323120ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; /** * Provides a simple pool of Packet objects. When the packets that this pool produces are disposed, * they are returned to the pool. * * @version $Revision: 1.1 $ */ abstract public class PacketPool { public static final int DEFAULT_POOL_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPoolSize", ""+(5))); public static final int DEFAULT_PACKET_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPacketSize", ""+(1024*1024*4))); private final ArrayList pool = new ArrayList(); private final int maxPackets; private int currentPoolSize; private boolean disposed; public class PooledPacket extends FilterPacket { private final AtomicInteger referenceCounter; public PooledPacket(Packet next) { this(next, new AtomicInteger(0)); } private PooledPacket(Packet next, AtomicInteger referenceCounter) { super(next); this.referenceCounter=referenceCounter; this.referenceCounter.incrementAndGet(); } public Packet filter(Packet packet) { return new PooledPacket(next, referenceCounter); } int getReferenceCounter() { return referenceCounter.get(); } public void dispose() { if( referenceCounter.decrementAndGet()==0 ) { returnPacket(next); } } } /** * @param maxPackets the number of buffers that will be in the pool. */ public PacketPool(int maxPackets) { this.maxPackets = maxPackets; } /** * Blocks until a ByteBuffer can be retreived from the pool. * * @return * @throws InterruptedException */ public Packet getPacket() throws InterruptedException { Packet answer=null; synchronized(this) { while(answer==null) { if( disposed ) return null; if( pool.size()>0) { answer = (Packet) pool.remove(pool.size()-1); } else if( currentPoolSize < maxPackets ) { answer = allocateNewPacket(); currentPoolSize++; } if( answer==null ) { this.wait(); } } } return new PooledPacket(answer); } /** * Returns a ByteBuffer to the pool. * * @param packet */ private void returnPacket(Packet packet) { packet.clear(); synchronized(this) { pool.add(packet); this.notify(); } } synchronized public void dispose() { disposed = true; while( currentPoolSize>0 ) { if( pool.size()>0) { currentPoolSize -= pool.size(); pool.clear(); } else { try { this.wait(); } catch (InterruptedException e) { return; } } } } synchronized public void waitForPacketsToReturn() { while( currentPoolSize!=pool.size() ) { try { this.wait(); } catch (InterruptedException e) { return; } } } /** * @return */ abstract protected Packet allocateNewPacket(); } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/package.html000066400000000000000000000016131156157346200316710ustar00rootroot00000000000000

Implementations of the Packet class.

activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/000077500000000000000000000000001156157346200271165ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ServerService.java000066400000000000000000000027571156157346200325630ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; import java.util.Properties; /** * The Server will call the following methods. *

* newInstance() * init( port, properties) * start() * stop() *

* All ServerService implementations must have a no argument * constructor. */ public interface ServerService extends SocketService { public void init(Properties props) throws Exception; public void start() throws ServiceException; public void stop() throws ServiceException; /** * Gets the ip number that the * daemon is listening on. */ public String getIP(); /** * Gets the port number that the * daemon is listening on. */ public int getPort(); } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ServiceDaemon.java000066400000000000000000000135441156157346200325140ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.Properties; public class ServiceDaemon implements ServerService { private static final Log log = LogFactory.getLog(ServiceDaemon.class); private final SocketService socketService; private final InetAddress address; private int port; private SocketListener socketListener; private int timeout; private String name; public ServiceDaemon(SocketService socketService, InetAddress address, int port) { this(null, socketService, address, port); } public ServiceDaemon(String name, SocketService socketService, InetAddress address, int port) { this.name = name; if (socketService == null) { throw new IllegalArgumentException("socketService is null"); } this.socketService = socketService; this.address = address; this.port = port; } public void setSoTimeout(int timeout) throws SocketException { this.timeout = timeout; if (socketListener != null) { socketListener.setSoTimeout(timeout); } } public int getSoTimeout() throws IOException { if (socketListener == null) return 0; return socketListener.getSoTimeout(); } public String getServiceName() { return socketService.getName(); } /** * Gets the inetAddress number that the * daemon is listening on. */ public InetAddress getAddress() { return address; } public void init(Properties props) throws Exception { } public void start() throws ServiceException { synchronized (this) { // Don't bother if we are already started/starting if (socketListener != null) { return; } ServerSocket serverSocket; try { serverSocket = new ServerSocket(port, 20, address); port = serverSocket.getLocalPort(); serverSocket.setSoTimeout(timeout); } catch (Exception e) { throw new ServiceException("Service failed to open socket", e); } socketListener = new SocketListener(socketService, serverSocket); Thread thread = new Thread(socketListener); thread.setName("service." + name + "@" + socketListener.hashCode()); thread.setDaemon(true); thread.start(); } } public void stop() throws ServiceException { synchronized (this) { if (socketListener != null) { socketListener.stop(); socketListener = null; } } } public String getIP() { return null; } /** * Gets the port number that the * daemon is listening on. */ public int getPort() { return port; } public void service(Socket socket) throws ServiceException, IOException { } public String getName() { return null; } private static class SocketListener implements Runnable { private SocketService serverService; private ServerSocket serverSocket; private boolean stopped; public SocketListener(SocketService serverService, ServerSocket serverSocket) { this.serverService = serverService; this.serverSocket = serverSocket; stopped = false; } public synchronized void stop() { stopped = true; } private synchronized boolean shouldStop() { return stopped; } public void run() { while (!shouldStop()) { Socket socket = null; try { socket = serverSocket.accept(); socket.setTcpNoDelay(true); if (!shouldStop()) { // the server service is responsible // for closing the socket. serverService.service(socket); } } catch (SocketTimeoutException e) { // we don't really care // log.debug("Socket timed-out",e); } catch (Throwable e) { log.error("Unexpected error", e); } } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException ioException) { log.debug("Error cleaning up socked", ioException); } serverSocket = null; } serverService = null; } public void setSoTimeout(int timeout) throws SocketException { serverSocket.setSoTimeout(timeout); } public int getSoTimeout() throws IOException { return serverSocket.getSoTimeout(); } } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ServiceException.java000066400000000000000000000043551156157346200332470ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; /** * */ public class ServiceException extends Exception { /** *

* Default constructor, which simply delegates exception * handling up the inheritance chain to Exception. *

*/ public ServiceException() { super(); } /** *

* This constructor allows a message to be supplied indicating the source * of the problem that occurred. *

* * @param message String identifying the cause of the problem. */ public ServiceException(String message) { super(message); } /** *

* This constructor allows a "root cause" exception to be supplied, * which may later be used by the wrapping application. *

* * @param rootCause Throwable that triggered the problem. */ public ServiceException(Throwable rootCause) { super(rootCause); } /** * This constructor allows both a message identifying the * problem that occurred as well as a "root cause" exception * to be supplied, which may later be used by the wrapping * application. * * @param message String identifying the cause of the problem. * @param rootCause Throwable that triggered this problem. */ public ServiceException(String message, Throwable rootCause) { super(message, rootCause); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ServiceLogger.java000066400000000000000000000074701156157346200325310ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.Properties; public class ServiceLogger implements ServerService { private final Log log; private final ServerService next; private final String[] logOnSuccess; private final String[] logOnFailure; private final String name; public ServiceLogger(String name, ServerService next, String[] logOnSuccess, String[] logOnFailure) { this.log = LogFactory.getLog("OpenEJB.server.service." + name); this.next = next; this.logOnSuccess = logOnSuccess; this.logOnFailure = logOnFailure; this.name = name; } /** * log_on_success * ----------------- * Different information can be logged when a server starts: *

* PID : the server's PID (if it's an internal xinetd service, the PID has then a value of 0) ; * HOST : the client address ; * USERID : the identity of the remote user, according to RFC1413 defining identification protocol; * EXIT : the process exit status; * DURATION : the session duration. *

* log_on_failure * ------------------ * Here again, xinetd can log a lot of information when a server can't start, either by lack of resources or because of access rules: * HOST, USERID : like above mentioned ; * ATTEMPT : logs an access attempt. This an automatic option as soon as another value is provided; * RECORD : logs every information available on the client. * * @param socket * @throws org.apache.activeio.xnet.ServiceException * * @throws IOException */ public void service(Socket socket) throws ServiceException, IOException { // Fill this in more deeply later. InetAddress client = socket.getInetAddress(); // MDC.put("HOST", client.getHostName()); // MDC.put("SERVER", getName()); try { logIncoming(); next.service(socket); logSuccess(); } catch (Exception e) { logFailure(e); e.printStackTrace(); } } public String[] getLogOnSuccess() { return logOnSuccess; } public String[] getLogOnFailure() { return logOnFailure; } private void logIncoming() { log.trace("incomming request"); } private void logSuccess() { log.trace("successful request"); } private void logFailure(Exception e) { log.error(e.getMessage()); } public void init(Properties props) throws Exception { next.init(props); } public void start() throws ServiceException { next.start(); } public void stop() throws ServiceException { next.stop(); } public String getName() { return next.getName(); } public String getIP() { return next.getIP(); } public int getPort() { return next.getPort(); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ServicePool.java000066400000000000000000000107571156157346200322250ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.Socket; import java.util.Properties; public class ServicePool implements ServerService { private static final Log log = LogFactory.getLog(ServicePool.class); private final ServerService next; private final Executor executor; public ServicePool(ServerService next, final String name, final int threads, final long keepAliveTime) { this.next = next; ThreadPoolExecutor p = new ThreadPoolExecutor(threads, threads, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); p.setThreadFactory(new ThreadFactory() { private volatile int id = 0; public Thread newThread(Runnable arg0) { Thread thread = new Thread(arg0, name + " " + getNextID()); return thread; } private int getNextID() { return id++; } }); executor = p; } public ServicePool(ServerService next, Executor executor) { this.next = next; this.executor = executor; } public void service(final Socket socket) throws ServiceException, IOException { final Runnable service = new Runnable() { public void run() { try { next.service(socket); } catch (SecurityException e) { log.error("Security error: " + e.getMessage(), e); } catch (Throwable e) { log.error("Unexpected error", e); } finally { try { if (socket != null) { socket.close(); } } catch (Throwable t) { log.warn("Error while closing connection with client", t); } } } }; final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Runnable ctxCL = new Runnable() { public void run() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(tccl); try { service.run(); } finally { Thread.currentThread().setContextClassLoader(cl); } } }; executor.execute(ctxCL); } /** * Pulls out the access log information * * @param props * @throws ServiceException */ public void init(Properties props) throws Exception { // Do our stuff // Then call the next guy next.init(props); } public void start() throws ServiceException { // Do our stuff // Then call the next guy next.start(); } public void stop() throws ServiceException { // Do our stuff // Then call the next guy next.stop(); } /** * Gets the name of the service. * Used for display purposes only */ public String getName() { return next.getName(); } /** * Gets the ip number that the * daemon is listening on. */ public String getIP() { return next.getIP(); } /** * Gets the port number that the * daemon is listening on. */ public int getPort() { return next.getPort(); } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/SocketService.java000066400000000000000000000022271156157346200325350ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; import java.io.IOException; import java.net.Socket; /** * @version $Revision: 1.1 $ $Date: 2004/04/09 19:04:01 $ */ public interface SocketService { void service(Socket socket) throws ServiceException, IOException; /** * Gets the name of the service. * Used for display purposes only */ String getName(); } StandardServiceStack.java000066400000000000000000000064041156157346200337550ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; import java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.activeio.xnet.hba.ServiceAccessController; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; public class StandardServiceStack { private String name; private ServiceDaemon daemon; private ServiceLogger logger; private ServiceAccessController hba; private ServicePool pool; private ServerService server; private String host; public StandardServiceStack(String name, int port, String host, IPAddressPermission[] allowHosts, String[] logOnSuccess, String[] logOnFailure, Executor executor, ServerService server) throws UnknownHostException { this.server = server; this.name = name; this.host = host; InetAddress address = InetAddress.getByName(host); this.pool = new ServicePool(server, executor); this.hba = new ServiceAccessController(name, pool, allowHosts); this.logger = new ServiceLogger(name, hba, logOnSuccess, logOnFailure); this.daemon = new ServiceDaemon(name, logger, address, port); } public String getName() { return name; } public InetAddress getAddress() { return daemon.getAddress(); } public InetSocketAddress getFullAddress() { return new InetSocketAddress(getAddress(), getPort()); } public String getHost() { return host; } public int getPort() { return daemon.getPort(); } public int getSoTimeout() throws IOException { return daemon.getSoTimeout(); } public void setSoTimeout(int timeout) throws SocketException { daemon.setSoTimeout(timeout); } public String[] getLogOnSuccess() { return logger.getLogOnSuccess(); } public String[] getLogOnFailure() { return logger.getLogOnFailure(); } public IPAddressPermission[] getAllowHosts() { return hba.getAllowHosts(); } public void setAllowHosts(IPAddressPermission[] allowHosts) { hba.setAllowHosts(allowHosts); } public void doStart() throws Exception { daemon.start(); } public void doStop() throws Exception { daemon.stop(); } public void doFail() { try { daemon.stop(); } catch (ServiceException dontCare) { } } } activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/000077500000000000000000000000001156157346200276505ustar00rootroot00000000000000ExactIPAddressPermission.java000066400000000000000000000046451156157346200353210ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.net.InetAddress; import java.net.Inet4Address; /** * @version $Revision$ $Date$ */ public class ExactIPAddressPermission implements IPAddressPermission { private static final Pattern MASK_VALIDATOR = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"); public static boolean canSupport(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); return matcher.matches(); } private final byte[] bytes; public ExactIPAddressPermission(byte[] bytes) { this.bytes = bytes; } public ExactIPAddressPermission(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); if (false == matcher.matches()) { throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); } bytes = new byte[4]; for (int i = 0; i < 4; i++) { String group = matcher.group(i + 1); int value = Integer.parseInt(group); if (value < 0 || 255 < value) { throw new IllegalArgumentException("byte #" + i + " is not valid."); } bytes[i] = (byte) value; } } public boolean implies(InetAddress address) { if (false == address instanceof Inet4Address) { return false; } byte[] byteAddress = address.getAddress(); for (int i = 0; i < 4; i++) { if (byteAddress[i] != bytes[i]) { return false; } } return true; } } ExactIPv6AddressPermission.java000066400000000000000000000047341156157346200355740ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.StringTokenizer; import java.net.InetAddress; import java.net.Inet6Address; /** * @version $Revision$ $Date$ */ public class ExactIPv6AddressPermission implements IPAddressPermission { private static final Pattern MASK_VALIDATOR = Pattern.compile("^(([a-fA-F0-9]{1,4}:){7})([a-fA-F0-9]{1,4})$"); public static boolean canSupport(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); return matcher.matches(); } private final byte[] bytes; public ExactIPv6AddressPermission(byte[] bytes) { this.bytes = bytes; } public ExactIPv6AddressPermission(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); if (false == matcher.matches()) { throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); } bytes = new byte[16]; int pos = 0; StringTokenizer tokenizer = new StringTokenizer(mask, ":"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); int value = Integer.parseInt(token, 16); bytes[pos++] = (byte) ((value & 0xff00) >> 8); bytes[pos++] = (byte) value; } } public boolean implies(InetAddress address) { if (false == address instanceof Inet6Address) { return false; } byte[] byteAddress = address.getAddress(); for (int i = 0; i < 16; i++) { if (byteAddress[i] != bytes[i]) { return false; } } return true; } } FactorizedIPAddressPermission.java000066400000000000000000000075711156157346200363500ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.StringTokenizer; import java.net.InetAddress; import java.net.Inet4Address; /** * @version $Revision$ $Date$ */ public class FactorizedIPAddressPermission implements IPAddressPermission { private static final Pattern MASK_VALIDATOR = Pattern.compile("^((\\d{1,3}){1}(\\.\\d{1,3}){0,2}\\.)?\\{(\\d{1,3}){1}((,\\d{1,3})*)\\}$"); public static boolean canSupport(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); return matcher.matches(); } private final byte[] prefixBytes; private final byte[] suffixBytes; public FactorizedIPAddressPermission(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); if (false == matcher.matches()) { throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); } // group 1 is the factorized IP part. // e.g. group 1 in "1.2.3.{4,5,6}" is "1.2.3." String prefix = matcher.group(1); StringTokenizer tokenizer = new StringTokenizer(prefix, "."); prefixBytes = new byte[tokenizer.countTokens()]; for (int i = 0; i < prefixBytes.length; i++) { String token = tokenizer.nextToken(); int value = Integer.parseInt(token); if (value < 0 || 255 < value) { throw new IllegalArgumentException("byte #" + i + " is not valid."); } prefixBytes[i] = (byte) value; } // group 5 is a comma separated list of optional suffixes. // e.g. group 5 in "1.2.3.{4,5,6}" is ",5,6" String suffix = matcher.group(5); tokenizer = new StringTokenizer(suffix, ","); suffixBytes = new byte[1 + tokenizer.countTokens()]; // group 4 is the compulsory and first suffix. // e.g. group 4 in "1.2.3.{4,5,6}" is "4" int value = Integer.parseInt(matcher.group(4)); int i = 0; if (value < 0 || 255 < value) { throw new IllegalArgumentException("suffix " + i + " is not valid."); } suffixBytes[i++] = (byte) value; for (; i < suffixBytes.length; i++) { String token = tokenizer.nextToken(); value = Integer.parseInt(token); if (value < 0 || 255 < value) { throw new IllegalArgumentException("byte #" + i + " is not valid."); } suffixBytes[i] = (byte) value; } } public boolean implies(InetAddress address) { if (false == address instanceof Inet4Address) { return false; } byte[] byteAddress = address.getAddress(); for (int i = 0; i < prefixBytes.length; i++) { if (byteAddress[i] != prefixBytes[i]) { return false; } } byte lastByte = byteAddress[prefixBytes.length]; for (int i = 0; i < suffixBytes.length; i++) { if (lastByte == suffixBytes[i]) { return true; } } return false; } } IPAddressPermission.java000066400000000000000000000020311156157346200343170ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.io.Serializable; import java.net.InetAddress; /** * @version $Revision$ $Date$ */ public interface IPAddressPermission extends Serializable { public boolean implies(InetAddress address); } IPAddressPermissionEditor.java000066400000000000000000000023521156157346200354740ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.beans.PropertyEditorSupport; /** * @version $Revision$ $Date$ */ public class IPAddressPermissionEditor extends PropertyEditorSupport { private IPAddressPermission addressMask; public void setAsText(String text) throws IllegalArgumentException { addressMask = IPAddressPermissionFactory.getIPAddressMask(text); } public Object getValue() { return addressMask; } } IPAddressPermissionFactory.java000066400000000000000000000034521156157346200356570ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; /** * @version $Revision$ $Date$ */ public class IPAddressPermissionFactory { public static IPAddressPermission getIPAddressMask(String mask) { if (StartWithIPAddressPermission.canSupport(mask)) { return new StartWithIPAddressPermission(mask); } else if (ExactIPAddressPermission.canSupport(mask)) { return new ExactIPAddressPermission(mask); } else if (FactorizedIPAddressPermission.canSupport(mask)) { return new FactorizedIPAddressPermission(mask); } else if (NetmaskIPAddressPermission.canSupport(mask)) { return new NetmaskIPAddressPermission(mask); } else if (ExactIPv6AddressPermission.canSupport(mask)) { return new ExactIPv6AddressPermission(mask); } else if (NetmaskIPv6AddressPermission.canSupport(mask)) { return new NetmaskIPv6AddressPermission(mask); } throw new IllegalArgumentException("Mask " + mask + " is not supported."); } } NetmaskIPAddressPermission.java000066400000000000000000000064271156157346200356570ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.net.InetAddress; import java.net.Inet4Address; /** * @version $Revision$ $Date$ */ public class NetmaskIPAddressPermission implements IPAddressPermission { private static final Pattern MASK_VALIDATOR = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/((\\d{1,2})|(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}))$"); public static boolean canSupport(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); return matcher.matches(); } private final byte[] networkAddressBytes; private final byte[] netmaskBytes; public NetmaskIPAddressPermission(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); if (false == matcher.matches()) { throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); } networkAddressBytes = new byte[4]; for (int i = 0; i < 4; i++) { String group = matcher.group(i + 1); int value = Integer.parseInt(group); if (value < 0 || 255 < value) { throw new IllegalArgumentException("byte #" + i + " is not valid."); } networkAddressBytes[i] = (byte) value; } netmaskBytes = new byte[4]; String netmask = matcher.group(6); if (null != netmask) { int value = Integer.parseInt(netmask); int pos = value / 8; int shift = 8 - value % 8; for (int i = 0; i < pos; i++) { netmaskBytes[i] = (byte) 0xff; } netmaskBytes[pos] = (byte) (0xff << shift); } else { for (int i = 0; i < 4; i++) { String group = matcher.group(i + 7); int value = Integer.parseInt(group); if (value < 0 || 255 < value) { throw new IllegalArgumentException("byte #" + i + " is not valid."); } netmaskBytes[i] = (byte) value; } } } public boolean implies(InetAddress address) { if (false == address instanceof Inet4Address) { return false; } byte[] byteAddress = address.getAddress(); for (int i = 0; i < 4; i++) { if ((netmaskBytes[i] & byteAddress[i]) != networkAddressBytes[i]) { return false; } } return true; } } NetmaskIPv6AddressPermission.java000066400000000000000000000065531156157346200361330ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.StringTokenizer; import java.net.InetAddress; import java.net.Inet6Address; /** * @version $Revision$ $Date$ */ public class NetmaskIPv6AddressPermission implements IPAddressPermission { private static final Pattern MASK_VALIDATOR = Pattern.compile("^(([a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4})/((\\d{1,3})|(([a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}))$"); public static boolean canSupport(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); return matcher.matches(); } private final byte[] networkAddressBytes; private final byte[] netmaskBytes; public NetmaskIPv6AddressPermission(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); if (false == matcher.matches()) { throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); } networkAddressBytes = new byte[16]; int pos = 0; StringTokenizer tokenizer = new StringTokenizer(matcher.group(1), ":"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); int value = Integer.parseInt(token, 16); networkAddressBytes[pos++] = (byte) ((value & 0xff00) >> 8); networkAddressBytes[pos++] = (byte) value; } netmaskBytes = new byte[16]; String netmask = matcher.group(4); if (null != netmask) { int value = Integer.parseInt(netmask); pos = value / 8; int shift = 8 - value % 8; for (int i = 0; i < pos; i++) { netmaskBytes[i] = (byte) 0xff; } netmaskBytes[pos] = (byte) (0xff << shift); } else { pos = 0; tokenizer = new StringTokenizer(matcher.group(5), ":"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); int value = Integer.parseInt(token, 16); netmaskBytes[pos++] = (byte) ((value & 0xff00) >> 8); netmaskBytes[pos++] = (byte) value; } } } public boolean implies(InetAddress address) { if (false == address instanceof Inet6Address) { return false; } byte[] byteAddress = address.getAddress(); for (int i = 0; i < 16; i++) { if ((netmaskBytes[i] & byteAddress[i]) != networkAddressBytes[i]) { return false; } } return true; } } ServiceAccessController.java000066400000000000000000000105011156157346200352170ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import org.apache.activeio.xnet.ServerService; import org.apache.activeio.xnet.ServiceException; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.Properties; import java.util.StringTokenizer; public class ServiceAccessController implements ServerService { private final ServerService next; private IPAddressPermission[] allowHosts; public ServiceAccessController(ServerService next) { this.next = next; } public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { this.next = next; this.allowHosts = ipAddressMasks; } public void service(Socket socket) throws ServiceException, IOException { // Check authorization checkHostsAuthorization(socket.getInetAddress(), socket.getLocalAddress()); next.service(socket); } public IPAddressPermission[] getAllowHosts() { return allowHosts; } public void setAllowHosts(IPAddressPermission[] ipAddressMasks) { this.allowHosts = ipAddressMasks; } public void checkHostsAuthorization(InetAddress clientAddress, InetAddress serverAddress) throws SecurityException { // Check the client ip against the server ip. Hosts are // allowed to access themselves, so if these ips // match, the following for loop will be skipped. if (clientAddress.equals(serverAddress)) { return; } for (int i = 0; i < allowHosts.length; i++) { if (allowHosts[i].implies(clientAddress)) { return; } } throw new SecurityException("Host " + clientAddress.getHostAddress() + " is not authorized to access this service."); } private void parseAdminIPs(Properties props) throws ServiceException { LinkedList ipAddressMasksList = new LinkedList(); try { InetAddress[] localIps = InetAddress.getAllByName("localhost"); for (int i = 0; i < localIps.length; i++) { if (localIps[i] instanceof Inet4Address) { ipAddressMasksList.add(new ExactIPAddressPermission(localIps[i].getAddress())); } else { ipAddressMasksList.add(new ExactIPv6AddressPermission(localIps[i].getAddress())); } } } catch (UnknownHostException e) { throw new ServiceException("Could not get localhost inet address", e); } String ipString = props.getProperty("only_from"); if (ipString != null) { StringTokenizer st = new StringTokenizer(ipString, " "); while (st.hasMoreTokens()) { String mask = st.nextToken(); ipAddressMasksList.add(IPAddressPermissionFactory.getIPAddressMask(mask)); } } allowHosts = (IPAddressPermission[]) ipAddressMasksList.toArray(new IPAddressPermission[ipAddressMasksList.size()]); } public void init(Properties props) throws Exception { parseAdminIPs(props); next.init(props); } public void start() throws ServiceException { next.start(); } public void stop() throws ServiceException { next.stop(); } public String getName() { return next.getName(); } public String getIP() { return next.getIP(); } public int getPort() { return next.getPort(); } } StartWithIPAddressPermission.java000066400000000000000000000055131156157346200362010ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.net.InetAddress; import java.net.Inet4Address; /** * @version $Revision$ $Date$ */ public class StartWithIPAddressPermission implements IPAddressPermission { private static final Pattern MASK_VALIDATOR = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.0$"); public static boolean canSupport(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); return matcher.matches(); } private final byte[] bytes; public StartWithIPAddressPermission(String mask) { Matcher matcher = MASK_VALIDATOR.matcher(mask); if (false == matcher.matches()) { throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); } Byte[] tmpBytes = new Byte[4]; boolean isWildCard = false; int size = 0; for (int i = 0; i < 3; i++) { String group = matcher.group(i + 1); if (group.equals("0")) { isWildCard = true; } else if (isWildCard) { throw new IllegalArgumentException("0 at position " + size + " in mask"); } else { int value = Integer.parseInt(group); if (value < 0 || 255 < value) { throw new IllegalArgumentException("byte #" + i + " is not valid."); } tmpBytes[i] = new Byte((byte) value); size++; } } bytes = new byte[size]; for (int i = 0; i < bytes.length; i++) { bytes[i] = tmpBytes[i].byteValue(); } } public boolean implies(InetAddress address) { if (false == address instanceof Inet4Address) { return false; } byte[] byteAddress = address.getAddress(); for (int i = 0; i < bytes.length; i++) { if (byteAddress[i] != bytes[i]) { return false; } } return true; } } activemq-activeio-3.1.1/activeio-core/src/main/resources/000077500000000000000000000000001156157346200234165ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/000077500000000000000000000000001156157346200245565ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/000077500000000000000000000000001156157346200264015ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/000077500000000000000000000000001156157346200271705ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/000077500000000000000000000000001156157346200304115ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/000077500000000000000000000000001156157346200322145ustar00rootroot00000000000000000077500000000000000000000000001156157346200335455ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channeldatagram000066400000000000000000000001421156157346200352450ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelSyncChannelFactory.class=org.apache.activeio.packet.sync.datagram.DatagramSocketSyncChannelFactorymulticast000066400000000000000000000001441156157346200354740ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelSyncChannelFactory.class=org.apache.activeio.packet.sync.multicast.MulticastSocketSyncChannelFactorynio000066400000000000000000000002511156157346200342530ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelSyncChannelFactory.class=org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory AsyncChannelFactory.class=org.apache.activeio.packet.async.nio.NIOAsyncChannelFactorynio-async000066400000000000000000000001251156157346200353660ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelAsyncChannelFactory.class=org.apache.activeio.packet.async.nio.NIOAsyncChannelFactorynio-sync000066400000000000000000000001221156157346200352220ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelSyncChannelFactory.class=org.apache.activeio.packet.sync.nio.NIOSyncChannelFactorysocket000066400000000000000000000001301156157346200347520ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelSyncChannelFactory.class=org.apache.activeio.packet.sync.socket.SocketSyncChannelFactoryssl000066400000000000000000000001301156157346200342630ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelSyncChannelFactory.class=org.apache.activeio.packet.sync.ssl.SslSocketSyncChannelFactoryvmpipe000066400000000000000000000001351156157346200347670ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channelAsyncChannelFactory.class=org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelFactory activemq-activeio-3.1.1/activeio-core/src/test/000077500000000000000000000000001156157346200214375ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/000077500000000000000000000000001156157346200223605ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/000077500000000000000000000000001156157346200231475ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/000077500000000000000000000000001156157346200243705ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/000077500000000000000000000000001156157346200261735ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/PacketDataTest.java000066400000000000000000000030061156157346200316760ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio; import java.io.IOException; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.PacketData; import junit.framework.TestCase; /** */ public class PacketDataTest extends TestCase { ByteArrayPacket packet = new ByteArrayPacket(new byte[200]); PacketData data = new PacketData(packet); public void testInteger() throws IOException { data.writeInt(Integer.MAX_VALUE); data.writeInt(Integer.MIN_VALUE); data.writeInt(551); packet.flip(); assertEquals(Integer.MAX_VALUE, data.readInt()); assertEquals(Integer.MIN_VALUE, data.readInt()); assertEquals(551, data.readInt()); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/000077500000000000000000000000001156157346200276455ustar00rootroot00000000000000JournalPerfToolSupport.java000066400000000000000000000123531156157346200351170ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import org.apache.activeio.journal.InvalidRecordLocationException; import org.apache.activeio.journal.Journal; import org.apache.activeio.journal.JournalEventListener; import org.apache.activeio.journal.RecordLocation; import org.apache.activeio.packet.ByteArrayPacket; /** * Provides the base class uses to run performance tests against a Journal. * Should be subclassed to customize for specific journal implementation. * * @version $Revision: 1.1 $ */ abstract public class JournalPerfToolSupport implements JournalEventListener { private JournalStatsFilter journal; private Random random = new Random(); private byte data[]; private int workerCount=0; private PrintWriter statWriter; // Performance test Options // The output goes here: protected File journalDirectory = new File("journal-logs"); protected File statCSVFile = new File("stats.csv");; // Controls how often we start a new batch of workers. protected int workerIncrement=5; protected long incrementDelay=1000*20; protected boolean verbose=true; protected int initialWorkers=10; // Worker configuration. protected int recordSize=1024; protected int syncFrequency=15; protected int workerThinkTime=100; private final class Worker implements Runnable { public void run() { int i=random.nextInt()%syncFrequency; while(true) { boolean sync=false; if( syncFrequency>=0 && (i%syncFrequency)==0 ) { sync=true; } try { journal.write(new ByteArrayPacket(data), sync); Thread.sleep(workerThinkTime); } catch (Exception e) { e.printStackTrace(); return; } i++; } } } /** * @throws IOException * */ protected void exec() throws Exception { System.out.println("Client threads write records using: Record Size: "+recordSize+", Sync Frequency: "+syncFrequency+", Worker Think Time: "+workerThinkTime); // Create the record and fill it with some values. data = new byte[recordSize]; for (int i = 0; i < data.length; i++) { data[i] = (byte)i; } if( statCSVFile!=null ) { statWriter = new PrintWriter(new FileOutputStream(statCSVFile)); statWriter.println("Threads,Throughput (k/s),Forcd write latency (ms),Throughput (records/s)"); } if( journalDirectory.exists() ) { deleteDir(journalDirectory); } journal = new JournalStatsFilter(createJournal()).enableDetailedStats(verbose); journal.setJournalEventListener(this); try { System.out.println("Starting "+initialWorkers+" Workers..."); for(int i=0;i =0 && (i%syncFrequency)==0 ) { sync=true; } try { journal.write(new ByteArrayPacket(data), sync); Thread.sleep(writeWorkerThinkTime); } catch (Exception e) { e.printStackTrace(); return; } i++; } } } private final class ReadWorker implements Runnable { AtomicLong counter=new AtomicLong(); public void run() { while(true) { try { RecordLocation pos = null; while( (pos=journal.getNextRecordLocation(pos))!=null ) { Packet packet = journal.read(pos); counter.addAndGet(packet.limit()); Thread.sleep(readWorkerThinkTime); } } catch (Throwable e) { e.printStackTrace(); } } } } /** * @throws IOException * */ protected void exec() throws Exception { System.out.println("Client threads write records using: Record Size: "+recordSize+", Sync Frequency: "+syncFrequency+", Worker Think Time: "+readWorkerThinkTime); // Create the record and fill it with some values. data = new byte[recordSize]; for (int i = 0; i < data.length; i++) { data[i] = (byte)i; } if( statCSVFile!=null ) { statWriter = new PrintWriter(new FileOutputStream(statCSVFile)); statWriter.println("Threads,Write Throughput (k/s),Forced Write latency (ms), Write Throughput (records/s),Read Throughput (k/s),Read latency (ms),Read Throughput (records/s)"); } if( journalDirectory.exists() ) { deleteDir(journalDirectory); } journal = new JournalStatsFilter(createJournal()).enableDetailedStats(verbose); journal.setJournalEventListener(this); try { System.out.println("Starting "+initialWriteWorkers+" Write Workers..."); for(int i=0;i next. * @param next */ public JournalStatsFilter(Journal next) { this.next = next; } /** * @see org.codehaus.activemq.journal.Journal#write(byte[], boolean) */ public RecordLocation write(Packet data, boolean sync) throws IOException { //writeWaitTimeStat long start = System.currentTimeMillis(); RecordLocation answer = next.write(data, sync); long end = System.currentTimeMillis(); writeRecordsCounter.increment(); writeBytesCounter.add(data.remaining()); if( sync ) synchedWriteLatency.addTime(end-start); else unsynchedWriteLatency.addTime(end-start); return answer; } /** * @see org.codehaus.activemq.journal.Journal#read(org.codehaus.activemq.journal.RecordLocation) */ public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException { long start = System.currentTimeMillis(); Packet answer = next.read(location); long end = System.currentTimeMillis(); readRecordsCounter.increment(); readBytesCounter.add(answer.remaining()); readLatency.addTime(end-start); return answer; } /** * @see org.codehaus.activemq.journal.Journal#setMark(org.codehaus.activemq.journal.RecordLocation, boolean) */ public void setMark(RecordLocation recordLocator, boolean force) throws InvalidRecordLocationException, IOException { next.setMark(recordLocator, force); } /** * @see org.codehaus.activemq.journal.Journal#getMark() */ public RecordLocation getMark() { return next.getMark(); } /** * @see org.codehaus.activemq.journal.Journal#close() */ public void close() throws IOException { next.close(); } /** * @see org.codehaus.activemq.journal.Journal#setJournalEventListener(org.codehaus.activemq.journal.JournalEventListener) */ public void setJournalEventListener(JournalEventListener eventListener) { next.setJournalEventListener(eventListener); } /** * @see org.codehaus.activemq.journal.Journal#getNextRecordLocation(org.codehaus.activemq.journal.RecordLocation) */ public RecordLocation getNextRecordLocation(RecordLocation lastLocation) throws IOException, InvalidRecordLocationException { long start = System.currentTimeMillis(); RecordLocation rc = next.getNextRecordLocation(lastLocation); long end = System.currentTimeMillis(); cursorCounter.increment(); cursorLatency.addTime(end-start); return rc; } /** * Writes the gathered statistics to the out object. * * @param out */ public void dump(IndentPrinter out) { out.printIndent(); out.println("Journal Stats {"); out.incrementIndent(); out.printIndent(); out.println("Write Throughput : "+ getWriteThroughputKps() +" k/s and " + getWriteThroughputRps() +" records/s" ); out.printIndent(); out.println("Write Latency with force : "+ getAvgSyncedLatencyMs() +" ms" ); out.printIndent(); out.println("Write Latency without force: "+ getAvgUnSyncedLatencyMs() +" ms" ); out.printIndent(); out.println("Read Throughput : "+ getReadThroughputKps() +" k/s and " + getReadThroughputRps() +" records/s" ); out.printIndent(); out.println("Read Latency : "+getAvgReadLatencyMs()+" ms" ); out.printIndent(); out.println("Cursor Latency : "+ getAvgCursorLatencyMs() +" ms" ); out.printIndent(); out.println("Raw Stats {"); out.incrementIndent(); out.printIndent(); out.println(writeRecordsCounter); out.printIndent(); out.println(writeBytesCounter); out.printIndent(); out.println(writeLatency); out.incrementIndent(); out.printIndent(); out.println(synchedWriteLatency); out.printIndent(); out.println(unsynchedWriteLatency); out.decrementIndent(); out.printIndent(); out.println(readBytesCounter); out.printIndent(); out.println(readLatency); out.decrementIndent(); out.printIndent(); out.println("}"); out.decrementIndent(); out.printIndent(); out.println("}"); } /** * Dumps the stats to a String. * * @see java.lang.Object#toString() */ public String toString() { if( detailedStats ) { StringWriter w = new StringWriter(); PrintWriter pw = new PrintWriter(w); dump(new IndentPrinter(pw, " ")); return w.getBuffer().toString(); } else { StringWriter w = new StringWriter(); PrintWriter pw = new PrintWriter(w); IndentPrinter out = new IndentPrinter(pw, " "); out.printIndent(); out.println("Write Throughput : "+ getWriteThroughputKps() +" k/s and " + getWriteThroughputRps() +" records/s"); out.printIndent(); out.println("Write Latency with force : "+getAvgSyncedLatencyMs()+" ms" ); out.printIndent(); out.println("Write Latency without force: "+getAvgUnSyncedLatencyMs()+" ms" ); out.printIndent(); out.println("Read Throughput : "+ getReadThroughputKps() +" k/s and " + getReadThroughputRps() +" records/s"); out.printIndent(); out.println("Read Latency : "+getAvgReadLatencyMs()+" ms" ); out.printIndent(); out.println("Cursor Latency : "+ getAvgCursorLatencyMs() +" ms" ); return w.getBuffer().toString(); } } /** * @param detailedStats true if details stats should be displayed by toString() and dump * @return */ public JournalStatsFilter enableDetailedStats(boolean detailedStats) { this.detailedStats = detailedStats; return this; } /** * Gets the average throughput in k/s. * * @return the average throughput in k/s. */ public double getWriteThroughputKps() { long totalTime = writeBytesCounter.getLastSampleTime()-writeBytesCounter.getStartTime(); return (((double)writeBytesCounter.getCount()/(double)totalTime)/(double)1024)*1000; } /** * Gets the average throughput in records/s. * * @return the average throughput in records/s. */ public double getWriteThroughputRps() { long totalTime = writeRecordsCounter.getLastSampleTime()-writeRecordsCounter.getStartTime(); return (((double)writeRecordsCounter.getCount()/(double)totalTime))*1000; } /** * Gets the average throughput in k/s. * * @return the average throughput in k/s. */ public double getReadThroughputKps() { long totalTime = readBytesCounter.getLastSampleTime()-readBytesCounter.getStartTime(); return (((double)readBytesCounter.getCount()/(double)totalTime)/(double)1024)*1000; } /** * Gets the average throughput in records/s. * * @return the average throughput in records/s. */ public double getReadThroughputRps() { long totalTime = readRecordsCounter.getLastSampleTime()-readRecordsCounter.getStartTime(); return (((double)readRecordsCounter.getCount()/(double)totalTime))*1000; } /** * Gets the average number of writes done per second * * @return the average number of writes in w/s. */ public double getWritesPerSecond() { return writeLatency.getAveragePerSecond(); } /** * Gets the average sync write latency in ms. * * @return the average sync write latency in ms. */ public double getAvgCursorLatencyMs() { return cursorLatency.getAverageTime(); } /** * Gets the average sync write latency in ms. * * @return the average sync write latency in ms. */ public double getAvgSyncedLatencyMs() { return synchedWriteLatency.getAverageTime(); } /** * Gets the average read latency in ms. * * @return the average sync write latency in ms. */ public double getAvgReadLatencyMs() { return readLatency.getAverageTime(); } /** * Gets the average non sync write latency in ms. * * @return the average non sync write latency in ms. */ public double getAvgUnSyncedLatencyMs() { return unsynchedWriteLatency.getAverageTime(); } /** * Resets the stats sample. */ public void reset() { writeLatency.reset(); writeBytesCounter.reset(); writeRecordsCounter.reset(); synchedWriteLatency.reset(); unsynchedWriteLatency.reset(); readLatency.reset(); readBytesCounter.reset(); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/active/000077500000000000000000000000001156157346200311205ustar00rootroot00000000000000DataStruturesTest.java000066400000000000000000000034171156157346200353630ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import org.apache.activeio.journal.active.Location; import junit.framework.TestCase; /** * Tests the data structures used JournalImpl * * @version $Revision: 1.1 $ */ public class DataStruturesTest extends TestCase { synchronized public void testRecordLocationImplComparison() throws IOException { Location l1 = new Location(0, 1); Location l2 = new Location(0, 2); Location l3 = new Location(0, 3); assertTrue( l1.compareTo(l2)<0 ); // Sort them using a list. Put them in the wrong order. ArrayList l = new ArrayList(); l.add(l2); l.add(l3); l.add(l1); Collections.sort(l); // Did they get sorted to the correct order? assertSame( l.get(0), l1 ); assertSame( l.get(1), l2 ); assertSame( l.get(2), l3 ); } } JournalImplTest.java000066400000000000000000000125671156157346200350130ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.File; import java.io.IOException; import junit.framework.TestCase; import org.apache.activeio.journal.InvalidRecordLocationException; import org.apache.activeio.journal.Journal; import org.apache.activeio.journal.RecordLocation; import org.apache.activeio.journal.active.JournalImpl; import org.apache.activeio.journal.active.Location; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.Packet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Tests the JournalImpl * * @version $Revision: 1.1 $ */ public class JournalImplTest extends TestCase { Log log = LogFactory.getLog(JournalImplTest.class); int size = 1024*10; int logFileCount=2; File logDirectory = new File("test-logfile"); private JournalImpl journal; /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { if( logDirectory.exists() ) { deleteDir(logDirectory); } assertTrue("Could not delete directory: "+logDirectory.getCanonicalPath(), !logDirectory.exists() ); journal = new JournalImpl(logDirectory,logFileCount, size, logDirectory); } /** */ private void deleteDir(File f) { File[] files = f.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; file.delete(); } f.delete(); } protected void tearDown() throws Exception { journal.close(); if( logDirectory.exists() ) deleteDir(logDirectory); assertTrue( !logDirectory.exists() ); } public void testLogFileCreation() throws IOException { RecordLocation mark = journal.getMark(); assertNull(mark); } public void testAppendAndRead() throws InvalidRecordLocationException, InterruptedException, IOException { Packet data1 = createPacket("Hello World 1"); RecordLocation location1 = journal.write( data1, false); Packet data2 = createPacket("Hello World 2"); RecordLocation location2 = journal.write( data2, false); Packet data3 = createPacket("Hello World 3"); RecordLocation location3 = journal.write( data3, false); // Now see if we can read that data. Packet data; data = journal.read(location2); assertEquals( data2, data); data = journal.read(location1); assertEquals( data1, data); data = journal.read(location3); assertEquals( data3, data); // Can we cursor the data? RecordLocation l=journal.getNextRecordLocation(null); assertEquals(0, l.compareTo(location1)); data = journal.read(l); assertEquals( data1, data); l=journal.getNextRecordLocation(l); assertEquals(0, l.compareTo(location2)); data = journal.read(l); assertEquals( data2, data); l=journal.getNextRecordLocation(l); assertEquals(0, l.compareTo(location3)); data = journal.read(l); assertEquals( data3, data); l=journal.getNextRecordLocation(l); assertNull(l); log.info(journal); } public void testCanReadFromArchivedLogFile() throws InvalidRecordLocationException, InterruptedException, IOException { Packet data1 = createPacket("Hello World 1"); RecordLocation location1 = journal.write( data1, false); Location pos; do { Packet p = createPacket("<<>>"); pos = (Location) journal.write( p, false); journal.setMark(pos, false); } while( pos.getLogFileId() < 5 ); Packet p = createPacket("<<>>"); pos = (Location) journal.write( p, true); // Now see if we can read that first packet. Packet data; data = journal.read(location1); assertEquals( data1, data); } /** * @param string * @return */ private Packet createPacket(String string) { return new ByteArrayPacket(string.getBytes()); } public static void assertEquals(Packet arg0, Packet arg1) { assertEquals(arg0.sliceAsBytes(), arg1.sliceAsBytes()); } public static void assertEquals(byte[] arg0, byte[] arg1) { if( arg0==null ^ arg1==null ) fail("Not equal: "+arg0+" != "+arg1); if( arg0==null ) return; if( arg0.length!=arg1.length) fail("Array lenght not equal: "+arg0.length+" != "+arg1.length); for( int i=0; i 0 ) { tool.journalDirectory = new File(args[0]); } if( args.length > 1 ) { tool.workerIncrement = Integer.parseInt(args[1]); } if( args.length > 2 ) { tool.incrementDelay = Long.parseLong(args[2]); } if( args.length > 3 ) { tool.verbose = Boolean.getBoolean(args[3]); } if( args.length > 4 ) { tool.recordSize = Integer.parseInt(args[4]); } if( args.length > 5 ) { tool.syncFrequency = Integer.parseInt(args[5]); } if( args.length > 6 ) { tool.workerThinkTime = Integer.parseInt(args[6]); } if( args.length > 7 ) { tool.logFileCount = Integer.parseInt(args[7]); } if( args.length > 8 ) { tool.logFileSize = Integer.parseInt(args[8]); } tool.exec(); } /** * @throws IOException * @see org.apache.activeio.journal.JournalPerfToolSupport#createJournal() */ public Journal createJournal() throws IOException { return new JournalImpl( this.journalDirectory, logFileCount, logFileSize); } } JournalRWPerfTool.java000066400000000000000000000050221156157346200352410ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.File; import java.io.IOException; import org.apache.activeio.journal.Journal; import org.apache.activeio.journal.JournalRWPerfToolSupport; /** * A Performance statistics gathering tool for the JournalImpl based Journal. * * @version $Revision: 1.1 $ */ public class JournalRWPerfTool extends JournalRWPerfToolSupport { private int logFileSize = 1024*1024*50; private int logFileCount = 4; public static void main(String[] args) throws Exception { JournalRWPerfTool tool = new JournalRWPerfTool(); tool.initialWriteWorkers=10; tool.syncFrequency=15; tool.writeWorkerIncrement=0; tool.writeWorkerThinkTime=0; tool.verbose=false; tool.incrementDelay=5*1000; if( args.length > 0 ) { tool.journalDirectory = new File(args[0]); } if( args.length > 1 ) { tool.writeWorkerIncrement = Integer.parseInt(args[1]); } if( args.length > 2 ) { tool.incrementDelay = Long.parseLong(args[2]); } if( args.length > 3 ) { tool.verbose = Boolean.getBoolean(args[3]); } if( args.length > 4 ) { tool.recordSize = Integer.parseInt(args[4]); } if( args.length > 5 ) { tool.syncFrequency = Integer.parseInt(args[5]); } if( args.length > 6 ) { tool.writeWorkerThinkTime = Integer.parseInt(args[6]); } if( args.length > 7 ) { tool.logFileCount = Integer.parseInt(args[7]); } if( args.length > 8 ) { tool.logFileSize = Integer.parseInt(args[8]); } tool.exec(); } /** * @throws IOException * @see org.apache.activeio.journal.JournalPerfToolSupport#createJournal() */ public Journal createJournal() throws IOException { return new JournalImpl( this.journalDirectory, logFileCount, logFileSize); } } LogFileManagerTest.java000066400000000000000000000111651156157346200353640ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/active/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import junit.framework.TestCase; import org.apache.activeio.journal.InvalidRecordLocationException; import org.apache.activeio.journal.active.BatchedWrite; import org.apache.activeio.journal.active.Location; import org.apache.activeio.journal.active.LogFileManager; import org.apache.activeio.journal.active.Record; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.ByteBufferPacket; /** * Tests the LogFile used by JournalImpl * * @version $Revision: 1.1 $ */ public class LogFileManagerTest extends TestCase { int size = 1024 * 512; int logFileCount = 4; File logDirectory = new File("test-logfile"); private LogFileManager logFile; /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { if (logDirectory.exists()) { deleteDir(logDirectory); } assertTrue(!logDirectory.exists()); logFile = new LogFileManager(logDirectory, logFileCount, size, null); } /** */ private void deleteDir(File f) { File[] files = f.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; file.delete(); } f.delete(); } protected void tearDown() throws Exception { logFile.dispose(); if (logDirectory.exists()) deleteDir(logDirectory); assertTrue(!logDirectory.exists()); } public void testLogFileCreation() throws IOException { assertTrue(logFile.canActivateNextLogFile()); assertEquals(null,logFile.getFirstActiveLogLocation()); assertNull(logFile.getLastMarkedRecordLocation()); assertEquals(new Location(0, 0),logFile.getNextAppendLocation()); } public void testAppendAndRead() throws IOException, InvalidRecordLocationException, InterruptedException { System.out.println("Initial:"+logFile.getNextAppendLocation()); appendHelloRecord(1001); Location loc2 = logFile.getNextAppendLocation(); appendHelloRecord(2002); appendHelloRecord(3003); appendHelloRecord(3004); Location loc3 = logFile.getNextDataRecordLocation(loc2); assertTrue(loc3.getLogFileOffset() > loc2.getLogFileOffset()); Location loc4 = logFile.getNextDataRecordLocation(loc3); assertTrue(loc4.getLogFileOffset() > loc3.getLogFileOffset()); } public void testRollOver() throws IOException, InvalidRecordLocationException, InterruptedException { int lastId = logFile.getNextAppendLocation().getLogFileId(); int counter = 0; for (int i = 0; i < logFileCount; i++) { counter += 500; appendHelloRecord(counter); if (i + 1 == logFileCount) { assertFalse(logFile.canActivateNextLogFile()); } else { assertTrue(logFile.canActivateNextLogFile()); logFile.activateNextLogFile(); assertEquals(lastId + 1, logFile.getNextAppendLocation().getLogFileId()); lastId = logFile.getNextAppendLocation().getLogFileId(); } } } /** * @param i * @throws IOException * @throws InterruptedException */ private void appendHelloRecord(int i) throws IOException, InterruptedException { byte data[] = ("Hello World: " + i).getBytes(); Record batchedRecord = new Record(LogFileManager.DATA_RECORD_TYPE, new ByteArrayPacket(data), null); batchedRecord.setLocation(logFile.getNextAppendLocation()); BatchedWrite write = new BatchedWrite(new ByteBufferPacket(ByteBuffer.allocate(1024))); write.append(batchedRecord,null, true); write.flip(); logFile.append(write); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/howl/000077500000000000000000000000001156157346200306165ustar00rootroot00000000000000JournalPerfTool.java000066400000000000000000000053651156157346200345000ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/journal/howl/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.howl; import java.io.File; import org.apache.activeio.journal.Journal; import org.apache.activeio.journal.JournalPerfToolSupport; import org.apache.activeio.journal.howl.HowlJournal; import org.objectweb.howl.log.Configuration; /** * A Performance statistics gathering tool for the HOWL based Journal. * * @version $Revision: 1.1 $ */ public class JournalPerfTool extends JournalPerfToolSupport { private int maxLogFiles= 2; private int bufferSize = 1024*4; private int maxBuffers = 20; private int maxBlocksPerFile = 100; public static void main(String[] args) throws Exception { try { JournalPerfTool tool = new JournalPerfTool(); if( args.length > 0 ) { tool.journalDirectory = new File(args[0]); } if( args.length > 1 ) { tool.workerIncrement = Integer.parseInt(args[1]); } if( args.length > 2 ) { tool.incrementDelay = Long.parseLong(args[2]); } if( args.length > 3 ) { tool.verbose = Boolean.getBoolean(args[3]); } if( args.length > 4 ) { tool.recordSize = Integer.parseInt(args[4]); } if( args.length > 5 ) { tool.syncFrequency = Integer.parseInt(args[5]); } if( args.length > 6 ) { tool.workerThinkTime = Integer.parseInt(args[6]); } if( args.length > 7 ) { tool.maxLogFiles = Integer.parseInt(args[7]); } if( args.length > 8 ) { tool.bufferSize = Integer.parseInt(args[8]); } if( args.length > 9 ) { tool.maxBuffers = Integer.parseInt(args[9]); } if( args.length > 10 ) { tool.maxBlocksPerFile = Integer.parseInt(args[10]); } tool.exec(); } catch (Throwable e) { e.printStackTrace(); } } public Journal createJournal() throws Exception { Configuration c = new Configuration(); c.setLogFileDir(journalDirectory.getPath()); c.setMaxLogFiles(maxLogFiles); c.setBufferSize(bufferSize); c.setMaxBuffers(maxBuffers); c.setMaxBlocksPerFile(maxBlocksPerFile); return new HowlJournal( c ); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/packet/000077500000000000000000000000001156157346200274425ustar00rootroot00000000000000AppendedPacketTest.java000066400000000000000000000024431156157346200337410ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/packet/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import org.apache.activeio.packet.AppendedPacket; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.Packet; /** */ public class AppendedPacketTest extends PacketTestSupport { Packet createTestPacket(int capacity) { int c1 = capacity/2; int c2 = capacity-c1; return AppendedPacket.join( new ByteArrayPacket(new byte[c1]), new ByteArrayPacket(new byte[c2])); } } ByteArrayPacketTest.java000066400000000000000000000021311156157346200341150ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/packet/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import org.apache.activeio.packet.ByteArrayPacket; import org.apache.activeio.packet.Packet; /** */ public class ByteArrayPacketTest extends PacketTestSupport { Packet createTestPacket(int capacity) { return new ByteArrayPacket(new byte[capacity]); } } ByteBufferPacketTest.java000066400000000000000000000022041156157346200342510ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/packet/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.nio.ByteBuffer; import org.apache.activeio.packet.ByteBufferPacket; import org.apache.activeio.packet.Packet; /** */ public class ByteBufferPacketTest extends PacketTestSupport { Packet createTestPacket(int capacity) { return new ByteBufferPacket(ByteBuffer.allocate(capacity)); } } PacketTestSupport.java000066400000000000000000000116201156157346200336720ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/packet/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.packet; import java.util.Arrays; import org.apache.activeio.packet.Packet; import junit.framework.TestCase; /** */ abstract public class PacketTestSupport extends TestCase { abstract Packet createTestPacket(int capacity); public void testInit() { Packet packet = createTestPacket(100); assertEquals( 100, packet.capacity() ); assertEquals( 0, packet.position()); assertEquals( 100, packet.limit() ); assertEquals( 100, packet.remaining() ); assertTrue( packet.hasRemaining() ); } public void testPosition() { Packet packet = createTestPacket(100); packet.position(10); assertEquals( 10, packet.position() ); } public void testLimit() { Packet packet = createTestPacket(100); packet.limit(10); assertEquals( 10, packet.limit() ); } public void testRemaining() { Packet packet = createTestPacket(100); packet.position(5); packet.limit(95); assertEquals(90, packet.remaining()); assertTrue(packet.hasRemaining()); packet.position(5); packet.limit(5); assertEquals(0, packet.remaining()); assertFalse(packet.hasRemaining()); } public void testFlip() { Packet packet = createTestPacket(100); packet.position(95); packet.flip(); assertEquals(0, packet.position()); assertEquals(95, packet.limit()); } public void testClear() { Packet packet = createTestPacket(100); packet.position(5); packet.limit(95); packet.clear(); assertEquals(0, packet.position()); assertEquals(100, packet.limit()); } public void testDuplicate() { Packet packet = createTestPacket(100); packet.position(5); packet.limit(95); Packet packet2 = packet.duplicate(); packet2.position(10); packet2.limit(20); assertEquals(5, packet.position()); assertEquals(95, packet.limit()); assertEquals(10, packet2.position()); assertEquals(20, packet2.limit()); } public void testRewind() { Packet packet = createTestPacket(100); packet.position(5); packet.limit(95); packet.rewind(); assertEquals(0, packet.position()); assertEquals(95, packet.limit()); } public void testSlice() { Packet packet = createTestPacket(100); packet.position(5); packet.limit(95); Packet packet2 = packet.slice(); assertEquals(0, packet2.position()); assertEquals(90, packet2.capacity()); assertEquals(90, packet2.limit()); } public void testWriteAndReadByte() { Packet packet = createTestPacket(256); for(int i=0; i < 256; i++) { assertTrue(packet.write(i)); } assertFalse(packet.write(0)); packet.flip(); for(int i=0; i < 256; i++) { assertEquals(i, packet.read()); } assertEquals(-1, packet.read()); } public void testWriteAndReadBulkByte() { byte data[] = new byte[10]; Packet packet = createTestPacket(data.length*10); for(int i=0; i < 10; i++) { Arrays.fill(data,(byte)i); assertEquals(data.length, packet.write(data,0,data.length)); } assertEquals(-1, packet.write(data,0,data.length)); byte buffer[] = new byte[data.length]; packet.flip(); for(int i=0; i < 10; i++) { assertEquals(buffer.length, packet.read(buffer,0,buffer.length)); Arrays.fill(data,(byte)i); assertEquals(buffer, data); } assertEquals(-1, packet.read(buffer,0,buffer.length)); } public void assertEquals(byte buffer[], byte data[]) { assertEquals(buffer.length, data.length); for (int i = 0; i < data.length; i++) { assertEquals(buffer[i], data[i]); } } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/stats/000077500000000000000000000000001156157346200273315ustar00rootroot00000000000000CountStatisticImpl.java000066400000000000000000000056421156157346200337260ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/stats/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.stats; import java.util.concurrent.atomic.AtomicLong; import javax.management.j2ee.statistics.CountStatistic; /** * Shamelessly taken from the ActiveMQ project ( http://activemq.com ) * A count statistic implementation * * @version $Revision: 1.1 $ */ public class CountStatisticImpl extends StatisticImpl implements CountStatistic { private final AtomicLong counter = new AtomicLong(0); private CountStatisticImpl parent; public CountStatisticImpl(CountStatisticImpl parent, String name, String description) { this(name, description); this.parent = parent; } public CountStatisticImpl(String name, String description) { this(name, "count", description); } public CountStatisticImpl(String name, String unit, String description) { super(name, unit, description); } public void reset() { super.reset(); counter.set(0); } public long getCount() { return counter.get(); } public void setCount(long count) { counter.set(count); } public void add(long amount) { counter.addAndGet(amount); updateSampleTime(); if (parent != null) { parent.add(amount); } } public void increment() { counter.incrementAndGet(); updateSampleTime(); if (parent != null) { parent.increment(); } } public void subtract(long amount) { counter.addAndGet(-amount); updateSampleTime(); if (parent != null) { parent.subtract(amount); } } public void decrement() { counter.decrementAndGet(); updateSampleTime(); if (parent != null) { parent.decrement(); } } public CountStatisticImpl getParent() { return parent; } public void setParent(CountStatisticImpl parent) { this.parent = parent; } protected void appendFieldDescription(StringBuffer buffer) { buffer.append(" count: "); buffer.append(Long.toString(counter.get())); super.appendFieldDescription(buffer); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/stats/IndentPrinter.java000066400000000000000000000041561156157346200327670ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.stats; import java.io.PrintWriter; /** * A helper class for printing indented text * * @version $Revision: 1.1 $ */ public class IndentPrinter { private int indentLevel; private String indent; private PrintWriter out; public IndentPrinter() { this(new PrintWriter(System.out), " "); } public IndentPrinter(PrintWriter out) { this(out, " "); } public IndentPrinter(PrintWriter out, String indent) { this.out = out; this.indent = indent; } public void println(Object value) { out.print(value.toString()); out.println(); } public void println(String text) { out.print(text); out.println(); } public void print(String text) { out.print(text); } public void printIndent() { for (int i = 0; i < indentLevel; i++) { out.print(indent); } } public void println() { out.println(); } public void incrementIndent() { ++indentLevel; } public void decrementIndent() { --indentLevel; } public int getIndentLevel() { return indentLevel; } public void setIndentLevel(int indentLevel) { this.indentLevel = indentLevel; } public void flush() { out.flush(); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/stats/StatisticImpl.java000066400000000000000000000054241156157346200327720ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.stats; import javax.management.j2ee.statistics.Statistic; /** * Shamelessly taken from the ActiveMQ project ( http://activemq.com ) * * Base class for a Statistic implementation * @version $Revision: 1.1 $ */ public class StatisticImpl implements Statistic { private String name; private String unit; private String description; private long startTime; private long lastSampleTime; public StatisticImpl(String name, String unit, String description) { this.name = name; this.unit = unit; this.description = description; startTime = System.currentTimeMillis(); lastSampleTime = startTime; } public synchronized void reset() { startTime = System.currentTimeMillis(); lastSampleTime = startTime; } protected synchronized void updateSampleTime() { lastSampleTime = System.currentTimeMillis(); } public synchronized String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(name); buffer.append("{"); appendFieldDescription(buffer); buffer.append(" }"); return buffer.toString(); } public String getName() { return name; } public String getUnit() { return unit; } public String getDescription() { return description; } public synchronized long getStartTime() { return startTime; } public synchronized long getLastSampleTime() { return lastSampleTime; } protected synchronized void appendFieldDescription(StringBuffer buffer) { buffer.append(" unit: "); buffer.append(unit); buffer.append(" startTime: "); //buffer.append(new Date(startTime)); buffer.append(startTime); buffer.append(" lastSampleTime: "); //buffer.append(new Date(lastSampleTime)); buffer.append(lastSampleTime); buffer.append(" description: "); buffer.append(description); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/stats/TimeStatisticImpl.java000066400000000000000000000117131156157346200336070ustar00rootroot00000000000000/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.stats; import javax.management.j2ee.statistics.TimeStatistic; /** * Shamelessly taken from the ActiveMQ project ( http://activemq.com ) * A time statistic implementation * * @version $Revision: 1.1 $ */ public class TimeStatisticImpl extends StatisticImpl implements TimeStatistic { private long count; private long maxTime; private long minTime; private long totalTime; private TimeStatisticImpl parent; public TimeStatisticImpl(String name, String description) { this(name, "millis", description); } public TimeStatisticImpl(TimeStatisticImpl parent, String name, String description) { this(name, description); this.parent = parent; } public TimeStatisticImpl(String name, String unit, String description) { super(name, unit, description); } public synchronized void reset() { super.reset(); count = 0; maxTime = 0; minTime = 0; totalTime = 0; } public synchronized long getCount() { return count; } public synchronized void addTime(long time) { count++; totalTime += time; if (time > maxTime) { maxTime = time; } if (time < minTime || minTime == 0) { minTime = time; } updateSampleTime(); if (parent != null) { parent.addTime(time); } } /** * @return the maximum time of any step */ public long getMaxTime() { return maxTime; } /** * @return the minimum time of any step */ public synchronized long getMinTime() { return minTime; } /** * @return the total time of all the steps added together */ public synchronized long getTotalTime() { return totalTime; } /** * @return the average time calculated by dividing the * total time by the number of counts */ public synchronized double getAverageTime() { if (count == 0) { return 0; } double d = totalTime; return d / count; } /** * @return the average time calculated by dividing the * total time by the number of counts but excluding the * minimum and maximum times. */ public synchronized double getAverageTimeExcludingMinMax() { if (count <= 2) { return 0; } double d = totalTime - minTime - maxTime; return d / (count - 2); } /** * @return the average number of steps per second */ public double getAveragePerSecond() { double d = 1000; double averageTime = getAverageTime(); if (averageTime == 0) { return 0; } return d / averageTime; } /** * @return the average number of steps per second excluding the min & max values */ public double getAveragePerSecondExcludingMinMax() { double d = 1000; double average = getAverageTimeExcludingMinMax(); if (average == 0) { return 0; } return d / average; } public TimeStatisticImpl getParent() { return parent; } public void setParent(TimeStatisticImpl parent) { this.parent = parent; } protected synchronized void appendFieldDescription(StringBuffer buffer) { buffer.append(" count: "); buffer.append(Long.toString(count)); buffer.append(" maxTime: "); buffer.append(Long.toString(maxTime)); buffer.append(" minTime: "); buffer.append(Long.toString(minTime)); buffer.append(" totalTime: "); buffer.append(Long.toString(totalTime)); buffer.append(" averageTime: "); buffer.append(Double.toString(getAverageTime())); buffer.append(" averageTimeExMinMax: "); buffer.append(Double.toString(getAverageTimeExcludingMinMax())); buffer.append(" averagePerSecond: "); buffer.append(Double.toString(getAveragePerSecond())); buffer.append(" averagePerSecondExMinMax: "); buffer.append(Double.toString(getAveragePerSecondExcludingMinMax())); super.appendFieldDescription(buffer); } } activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/stats/package.html000066400000000000000000000016061156157346200316150ustar00rootroot00000000000000

Some Statistic helper classes.

activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/xnet/000077500000000000000000000000001156157346200271515ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/xnet/hba/000077500000000000000000000000001156157346200277035ustar00rootroot00000000000000ServiceAccessControllerTest.java000077500000000000000000000237751156157346200361360ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/xnet/hba/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; import junit.framework.TestCase; import org.apache.activeio.xnet.ServerService; import org.apache.activeio.xnet.ServiceException; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.activeio.xnet.hba.IPAddressPermissionFactory; import org.apache.activeio.xnet.hba.ServiceAccessController; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Properties; public class ServiceAccessControllerTest extends TestCase { public void testWrongExactIPAddressPermission1() throws Exception { try { IPAddressPermissionFactory.getIPAddressMask("121.122.123.a"); fail(); } catch (IllegalArgumentException e) { } } public void testWrongExactIPAddressPermission2() throws Exception { try { IPAddressPermissionFactory.getIPAddressMask("121.122.123.256"); fail(); } catch (IllegalArgumentException e) { } } public void testExactIPAddressPermission() throws Exception { IPAddressPermission permission = IPAddressPermissionFactory.getIPAddressMask("121.122.123.124"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 124}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 125}))); } public void testWrongStartWithIPAddressPermission1() throws Exception { try { IPAddressPermissionFactory.getIPAddressMask("121.0.123.0"); fail(); } catch (IllegalArgumentException e) { } } public void testStartWithIPAddressPermission() throws Exception { IPAddressPermission permission = IPAddressPermissionFactory.getIPAddressMask("121.122.0.0"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 124}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{121, 123, 123, 124}))); } public void testFactorizedIPAddressPermission() throws Exception { IPAddressPermission permission = IPAddressPermissionFactory.getIPAddressMask("121.122.123.{1,2,3}"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 1}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 2}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 3}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, 4}))); permission = IPAddressPermissionFactory.getIPAddressMask("121.122.{1,2,3}"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 1, 1}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 2, 2}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 3, 3}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 4, 3}))); } public void testNetmaskIPAddressPermission() throws Exception { IPAddressPermission permission = IPAddressPermissionFactory.getIPAddressMask("121.122.123.254/31"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, (byte) 254}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, (byte) 255}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, (byte) 253}))); permission = IPAddressPermissionFactory.getIPAddressMask("121.122.123.254/255.255.255.254"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, (byte) 254}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, (byte) 255}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{121, 122, 123, (byte) 253}))); } public void testExactIPv6AddressPermission() throws Exception { IPAddressPermission permission = IPAddressPermissionFactory.getIPAddressMask("101:102:103:104:105:106:107:108"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 9}))); } public void testNetmaskIPv6AddressPermission() throws Exception { IPAddressPermission permission = IPAddressPermissionFactory.getIPAddressMask("101:102:103:104:105:106:107:FFFE/127"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, (byte) 255, (byte) 254}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, (byte) 255, (byte) 255}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, (byte) 255, (byte) 253}))); permission = IPAddressPermissionFactory.getIPAddressMask("101:102:103:104:105:106:107:FFFE/FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFE"); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, (byte) 255, (byte) 254}))); assertTrue(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, (byte) 255, (byte) 255}))); assertFalse(permission.implies(InetAddress.getByAddress(new byte[]{1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, (byte) 255, (byte) 253}))); } public void testServiceOKWithConstructor() throws Exception { IPAddressPermission[] masks = new IPAddressPermission[]{ IPAddressPermissionFactory.getIPAddressMask("121.122.{56,57}") }; MockServerService mockServerService = new MockServerService(); ServiceAccessController controller = new ServiceAccessController(null, mockServerService, masks); executeTestServiceOK(mockServerService, controller); } public void testServiceNOK() throws Exception { IPAddressPermission[] masks = new IPAddressPermission[]{ IPAddressPermissionFactory.getIPAddressMask("121.122.{56,57}") }; MockServerService mockServerService = new MockServerService(); ServiceAccessController controller = new ServiceAccessController(null, mockServerService, masks); executeTestServiceNOK(controller); } public void testServiceOKWithInit() throws Exception { Properties properties = new Properties(); properties.put("only_from", "121.122.{56,57}"); MockServerService mockServerService = new MockServerService(); ServiceAccessController controller = new ServiceAccessController(mockServerService); controller.init(properties); executeTestServiceOK(mockServerService, controller); } public void testServiceNOKWithInit() throws Exception { Properties properties = new Properties(); properties.put("only_from", "121.122.{56,57}"); MockServerService mockServerService = new MockServerService(); ServiceAccessController controller = new ServiceAccessController(mockServerService); controller.init(properties); executeTestServiceOK(mockServerService, controller); } private void executeTestServiceOK(MockServerService mockServerService, ServiceAccessController controller) throws UnknownHostException, ServiceException, IOException { MockSocket mockSocket = new MockSocket(InetAddress.getByAddress(new byte[]{121, 122, 56, 123})); controller.service(mockSocket); assertSame(mockSocket, mockServerService.socket); mockSocket = new MockSocket(InetAddress.getByAddress(new byte[]{121, 122, 57, 123})); controller.service(mockSocket); assertSame(mockSocket, mockServerService.socket); } private void executeTestServiceNOK(ServiceAccessController controller) throws UnknownHostException, ServiceException, IOException { MockSocket mockSocket = new MockSocket(InetAddress.getByAddress(new byte[]{121, 122, 58, 123})); try { controller.service(mockSocket); fail(); } catch (SecurityException e) { } } private static class MockSocket extends Socket { private final InetAddress address; private MockSocket(InetAddress address) { this.address = address; } public InetAddress getInetAddress() { return address; } } private static class MockServerService implements ServerService { private Socket socket; public void init(Properties props) throws Exception { } public void start() throws ServiceException { throw new AssertionError(); } public void stop() throws ServiceException { throw new AssertionError(); } public String getIP() { throw new AssertionError(); } public int getPort() { throw new AssertionError(); } public void service(Socket socket) throws ServiceException, IOException { this.socket = socket; } public String getName() { throw new AssertionError(); } } } activemq-activeio-3.1.1/activeio-core/src/test/resources/000077500000000000000000000000001156157346200234515ustar00rootroot00000000000000activemq-activeio-3.1.1/activeio-core/src/test/resources/client.keystore000066400000000000000000000012061156157346200265150ustar00rootroot00000000000000mykeyڟ tX.509H0D0B0  *H 0i1 0 UUS1 0 UCA1 0 ULA10U  activemq.org10U  activemq.org10U localhost0 050203234520Z 050504234520Z0i1 0 UUS1 0 UCA1 0 ULA10U  activemq.org10U  activemq.org10U localhost00  *H 0vwo-?ˀ,vb;=gVcpe,9rv2tg .jvOICGp/P'Aޡ!X*ᇵ4QJ.'O$-+ĎxV3QJ0  *H R~HU+TU't((s"s-`e:`LG ?6bcZV*SI#H_n*a=1^?w>%E']ɘ.E)s;'3?activemq-activeio-3.1.1/activeio-core/src/test/resources/log4j.properties000066400000000000000000000030231156157346200266040ustar00rootroot00000000000000## --------------------------------------------------------------------------- ## Licensed to the Apache Software Foundation (ASF) under one or more ## contributor license agreements. See the NOTICE file distributed with ## this work for additional information regarding copyright ownership. ## The ASF licenses this file to You under the Apache License, Version 2.0 ## (the "License"); you may not use this file except in compliance with ## the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## --------------------------------------------------------------------------- # # The logging properties used during tests.. # log4j.rootLogger=INFO, out # CONSOLE appender not used by default log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n # File appender log4j.appender.out=org.apache.log4j.FileAppender log4j.appender.out.layout=org.apache.log4j.PatternLayout log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n log4j.appender.out.file=${basedir}/target/test.log log4j.appender.out.append=true activemq-activeio-3.1.1/activeio-core/src/test/resources/server.keystore000066400000000000000000000025101156157346200265440ustar00rootroot00000000000000mykeyڝ00 +*]X[`zM-8s FP䎑`p1,Ðf[%7\odjP.=+Xa rcR': k]~j%$WA8<'QM-EU/j fX  6Aѩ rwa\(Hd uXZNxp@Cb-]#WWO3x'#` ׅ^=Hu'aX +Kx$cko"{4Β$>c!Vw|x("e\;$,<vYjo3zw=rg]=ieRRK%lcE.~ࠊC}(Ւ电/% {x+iXw骙;BSϳ{ߩka)g/]Wl\U~Yk(S+#>n6e-E%?w>%E']ɘԲJ$t~Q:MlYactivemq-activeio-3.1.1/pom.xml000066400000000000000000000250431156157346200164610ustar00rootroot00000000000000 org.apache apache 6 4.0.0 org.apache.activemq activeio-parent 3.1.1 pom ActiveIO activeio-core 2.0.9 http://activemq.apache.org/ 2005 Development List dev-subscribe@activemq.apache.org dev-unsubscribe@activemq.apache.org dev@activemq.apache.org org.apache.geronimo.specs geronimo-j2ee-management_1.1_spec 1.0.1 howl howl-logger ${howl-version} commons-logging commons-logging ${commons-logging-version} activeio Apache ActiveMQ ActiveIO scp://people.apache.org/x1/www/activemq.apache.org 0.1.8 1.1 1.0.0 * org.apache.activeio* !* ${activeio.osgi.export.pkg}*;version=${activeio.osgi.export.version} ${project.version} ${activeio.osgi.import.pkg} ${groupId}.${artifactId} activeio.website ${staging.siteURL}/${siteId}/maven/${version} scm:svn:https://svn.apache.org/repos/asf/activemq/activeio/tags/activeio-3.1.1 scm:svn:https://svn.apache.org/repos/asf/activemq/activeio/tags/activeio-3.1.1 http://svn.apache.org/viewcvs.cgi/activemq/activeio/tags/activeio-3.1.1 org.apache.maven.plugins maven-assembly-plugin 2.2-beta-4 gnu org.apache.maven.plugins maven-eclipse-plugin 2.4 true true org.apache.maven.plugins maven-jar-plugin true true org.apache.maven.plugins maven-release-plugin true false clean install deploy org.apache.maven.plugins maven-surefire-plugin true once -enableassertions false org.apache.felix maven-bundle-plugin 1.0.0 org.codehaus.mojo ianal-maven-plugin 1.0-alpha-1 org.codehaus.mojo rat-maven-plugin 1.0-alpha-3 false org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 true true true true org.apache.maven.plugins maven-enforcer-plugin validate enforce [2.0.9,) org.codehaus.mojo ianal-maven-plugin verify-legal-files true org.apache.felix maven-bundle-plugin ${felix-version} true ${artifactId} ${activemq.osgi.symbolic.name} ${activemq.osgi.export} ${activemq.osgi.import} ${activemq.osgi.private.pkg} Apache ActiveMQ ${project.version} org.apache.maven.plugins maven-checkstyle-plugin org.apache.maven.plugins maven-javadoc-plugin http://java.sun.com/j2ee/1.5/docs/api http://java.sun.com/j2se/1.5.0/docs/api org.apache.maven.plugins maven-jxr-plugin org.apache.maven.plugins maven-pmd-plugin org.apache.maven.plugins maven-surefire-report-plugin org.codehaus.mojo cobertura-maven-plugin org.codehaus.mojo taglist-maven-plugin apache-release apache-release org.apache.maven.plugins maven-assembly-plugin single package true source-release org.apache.geronimo.genesis apache-source-release-assembly-descriptor 2.0