pax_global_header 0000666 0000000 0000000 00000000064 11561573462 0014524 g ustar 00root root 0000000 0000000 52 comment=2cba9fe74a3492b9cc35fa53a5baa4d020b62c84
activemq-activeio-3.1.1/ 0000775 0000000 0000000 00000000000 11561573462 0015140 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/LICENSE 0000664 0000000 0000000 00000026137 11561573462 0016156 0 ustar 00root root 0000000 0000000
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/NOTICE 0000664 0000000 0000000 00000000265 11561573462 0016047 0 ustar 00root root 0000000 0000000 Apache 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/ 0000775 0000000 0000000 00000000000 11561573462 0017671 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/pom.xml 0000664 0000000 0000000 00000005324 11561573462 0021212 0 ustar 00root root 0000000 0000000
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/ 0000775 0000000 0000000 00000000000 11561573462 0027612 5 ustar 00root root 0000000 0000000 InvalidRecordLocationException.java 0000664 0000000 0000000 00000003112 11561573462 0036470 0 ustar 00root root 0000000 0000000 activemq-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 forserialVersionUID
*/
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.java 0000664 0000000 0000000 00000011713 11561573462 0032072 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000002716 11561573462 0034526 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000002216 11561573462 0033365 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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/ 0000775 0000000 0000000 00000000000 11561573462 0031065 5 ustar 00root root 0000000 0000000 BatchedWrite.java 0000664 0000000 0000000 00000007261 11561573462 0034224 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000014002 11561573462 0034066 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000040442 11561573462 0034111 0 ustar 00root root 0000000 0000000 activemq-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:
* 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/ 0000775 0000000 0000000 00000000000 11561573462 0030563 5 ustar 00root root 0000000 0000000 HowlJournal.java 0000664 0000000 0000000 00000015104 11561573462 0033614 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000004000 11561573462 0035070 0 ustar 00root root 0000000 0000000 activemq-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.html 0000664 0000000 0000000 00000001756 11561573462 0033055 0 ustar 00root root 0000000 0000000A 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.html 0000664 0000000 0000000 00000001703 11561573462 0032074 0 ustar 00root root 0000000 0000000Provides 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/ 0000775 0000000 0000000 00000000000 11561573462 0027626 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java 0000664 0000000 0000000 00000004206 11561573462 0033442 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000002420 11561573462 0033257 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000001715 11561573462 0034247 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000002314 11561573462 0034101 0 ustar 00root root 0000000 0000000 activemq-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.html 0000664 0000000 0000000 00000002136 11561573462 0032111 0 ustar 00root root 0000000 0000000This 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/ 0000775 0000000 0000000 00000000000 11561573462 0027407 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/packet/AppendedPacket.java 0000664 0000000 0000000 00000015416 11561573462 0033131 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000014677 11561573462 0033323 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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 abyte[]
.
*
* @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.java0000664 0000000 0000000 00000020236 11561573462 0033442 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000003071 11561573462 0034213 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000011765 11561573462 0032317 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000002377 11561573462 0032657 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000007016 11561573462 0032034 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000007241 11561573462 0032504 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000006322 11561573462 0032632 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000004473 11561573462 0031471 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000032136 11561573462 0032260 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000010170 11561573462 0032312 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.html 0000664 0000000 0000000 00000001613 11561573462 0031671 0 ustar 00root root 0000000 0000000
Implementations of the Packet class.
activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ 0000775 0000000 0000000 00000000000 11561573462 0027116 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/java/org/apache/activeio/xnet/ServerService.java 0000664 0000000 0000000 00000002757 11561573462 0032563 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000013544 11561573462 0032514 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000004355 11561573462 0033247 0 ustar 00root root 0000000 0000000 /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS 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 toException
.
*
*/
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.java 0000664 0000000 0000000 00000007470 11561573462 0032531 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000010757 11561573462 0032225 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000002227 11561573462 0032535 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.java 0000664 0000000 0000000 00000006404 11561573462 0033755 0 ustar 00root root 0000000 0000000 activemq-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/ 0000775 0000000 0000000 00000000000 11561573462 0027650 5 ustar 00root root 0000000 0000000 ExactIPAddressPermission.java 0000664 0000000 0000000 00000004645 11561573462 0035321 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000004734 11561573462 0035574 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000007571 11561573462 0036350 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000002031 11561573462 0034317 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000002352 11561573462 0035474 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000003452 11561573462 0035657 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000006427 11561573462 0035657 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000006553 11561573462 0036133 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000010501 11561573462 0035217 0 ustar 00root root 0000000 0000000 activemq-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.java 0000664 0000000 0000000 00000005513 11561573462 0036201 0 ustar 00root root 0000000 0000000 activemq-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/ 0000775 0000000 0000000 00000000000 11561573462 0023416 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/ 0000775 0000000 0000000 00000000000 11561573462 0024556 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/ 0000775 0000000 0000000 00000000000 11561573462 0026401 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/ 0000775 0000000 0000000 00000000000 11561573462 0027170 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/ 0000775 0000000 0000000 00000000000 11561573462 0030411 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/ 0000775 0000000 0000000 00000000000 11561573462 0032214 5 ustar 00root root 0000000 0000000 0000775 0000000 0000000 00000000000 11561573462 0033545 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel datagram 0000664 0000000 0000000 00000000142 11561573462 0035245 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel SyncChannelFactory.class=org.apache.activeio.packet.sync.datagram.DatagramSocketSyncChannelFactory multicast 0000664 0000000 0000000 00000000144 11561573462 0035474 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel SyncChannelFactory.class=org.apache.activeio.packet.sync.multicast.MulticastSocketSyncChannelFactory nio 0000664 0000000 0000000 00000000251 11561573462 0034253 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel SyncChannelFactory.class=org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory
AsyncChannelFactory.class=org.apache.activeio.packet.async.nio.NIOAsyncChannelFactory nio-async 0000664 0000000 0000000 00000000125 11561573462 0035366 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel AsyncChannelFactory.class=org.apache.activeio.packet.async.nio.NIOAsyncChannelFactory nio-sync 0000664 0000000 0000000 00000000122 11561573462 0035222 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel SyncChannelFactory.class=org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory socket 0000664 0000000 0000000 00000000130 11561573462 0034752 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel SyncChannelFactory.class=org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory ssl 0000664 0000000 0000000 00000000130 11561573462 0034263 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel SyncChannelFactory.class=org.apache.activeio.packet.sync.ssl.SslSocketSyncChannelFactory vmpipe 0000664 0000000 0000000 00000000135 11561573462 0034767 0 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/main/resources/META-INF/services/org/apache/activeio/channel AsyncChannelFactory.class=org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelFactory
activemq-activeio-3.1.1/activeio-core/src/test/ 0000775 0000000 0000000 00000000000 11561573462 0021437 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/test/java/ 0000775 0000000 0000000 00000000000 11561573462 0022360 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/test/java/org/ 0000775 0000000 0000000 00000000000 11561573462 0023147 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/ 0000775 0000000 0000000 00000000000 11561573462 0024370 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/ 0000775 0000000 0000000 00000000000 11561573462 0026173 5 ustar 00root root 0000000 0000000 activemq-activeio-3.1.1/activeio-core/src/test/java/org/apache/activeio/PacketDataTest.java 0000664 0000000 0000000 00000003006 11561573462 0031676 0 ustar 00root root 0000000 0000000 /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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/ 0000775 0000000 0000000 00000000000 11561573462 0027645 5 ustar 00root root 0000000 0000000 JournalPerfToolSupport.java 0000664 0000000 0000000 00000012353 11561573462 0035117 0 ustar 00root root 0000000 0000000 activemq-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