code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;
import org.xsocket.MaxReadSizeExceededException;
/**
* Reads and processes the incoming data. This method will be called
* each time when data is available or the connection is closed. Because
* this depends on the underlying tcp protocol, it is not predictable
* how often and when this method will be call. Please note, that on network level
* data can be fragmented on several TCP packets as well as data can
* be bundled into one TCP packet. <br><br>
*
* Performing a write operation like <code>connection.write("hello it's me. What I have to say is.")</code>
* on the client side doesn�t mean that exact one onData call occurs on
* the server side. A common pattern to solve this is to identify logical
* parts by a delimiter or a leading length field.
* xSocket provides methods to support this pattern. E.g. the {@link INonBlockingConnection#readStringByDelimiter(String)}
* method only returns a record if the whole part (identified by the delimiter) has
* been received, or if not, a BufferUnderflowException will be thrown. In
* contrast to {@link IBlockingConnection}, a {@link INonBlockingConnection} read
* method always returns immediately and could thrown a BufferUnderflowException.
* The {@link BufferUnderflowException} will be swallowed by the framework, if
* the DataHandler doesn�t catch this exception. It is a common pattern
* not to handle such an exception by the DataHandler.
*
* <pre>
* public final class MyHandler implements IDataHandler, IConnectionScoped {
* ...
* public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
* ...
* // BufferUnderflowException will been thrown if delimiter has not been found.
* // A MaxReadSizeExceededException will be thrown if the max read size has been exceeded. Not handling this exception causes
* // that the server closes the underlying connection
* String command = connection.readStringByDelimiter("\r\n", "US-ASCII", 5000);
* ...
* connection.write(response, "US-ASCII");
* return true;
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public interface IDataHandler extends IHandler {
/**
* processes the incoming data based on the given connection. <br><br>
*
* Please note, that the <code>onData</code> call back method can also be called
* for if an connection will be closed. In this case the <code>isOpen</code> call
* within the <code>onData</code> Method will return false. Reading of already
* received data will not fail.
* To detect if a connection has been closed the callback method <code>onDisconnect</code>
* should be implemented. The correct call back order will be managed by the xSocket.
*
* @param connection the underlying connection
* @return true for positive result of handling, false for negative result of handling.
* The return value will be used by the {@link HandlerChain} to interrupted
* the chaining (if result is true)
* @throws IOException If some other I/O error occurs. Throwing this exception causes that the underlying connection will be closed.
* @throws BufferUnderflowException if more incoming data is required to process (e.g. delimiter hasn't yet received -> readByDelimiter methods or size of the available, received data is smaller than the required size -> readByLength). The BufferUnderflowException will be swallowed by the framework
* @throws ClosedChannelException if the connection is closed
* @throws MaxReadSizeExceededException if the max read size has been reached (e.g. by calling method {@link INonBlockingConnection#readStringByDelimiter(String, int)}).
* Throwing this exception causes that the underlying connection will be closed.
* @throws RuntimeException if an runtime exception occurs. Throwing this exception causes that the underlying connection will be closed. *
*/
boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IDataHandler.java | Java | art | 5,461 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.Executor;
import org.xsocket.connection.IConnection.FlushMode;
/**
* A server accepts new incoming connections, and delegates the handling of the
* {@link INonBlockingConnection} to the assigned handler.
*
* The server includes dispatchers, which are responsible to perform the
* socket I/O operations. A connection is assigned to one dispatcher. <br>
* To handle application-relevant events like <code>onData</code>,
* <code>onClose</code> or <code>onConnect</code> the appropriated callback method
* of the assigned {@link IHandler} will be called. The supported callback
* methods of the handler will be analyzed by using reflection during the server start-up
* phase. The callback method will be marked by implementing the specific interface
* like {@link IDataHandler} or {@link IConnectHandler}. Often a
* handler will implement several handler interfaces.<br>
* <br>
* E.g.
* <pre>
* ...
* IServer smtpServer = new Server(25, new SmtpProtcolHandler());
*
* smtpServer.start();
* ...
*
*
* // Handler definition
* class SmtpProtcolHandler implements IDataHandler, IConnectHandler {
*
* SessionData sessionData = (SessionData) connection.getAttachment();
*
* String cmd = connection.readStringByDelimiter("\r\n").toUpperCase();
*
* if (cmd.startsWith("HELO")) {
* connection.write("250 SMTP Service\r\n");
*
* } else if(cmd.equals("DATA")) {
* String msgId = connection.getId() + "." + sessionData.nextId();
* File msgFile = new File(msgFileDir + File.separator + msgId + ".msg");
*
* connection.setHandler(new DataHandler(msgFile, this));
* connection.write("354 Enter message, ending with \".\"\r\n");
*
* } else {
*
* ...
* }
*
* ...
* }
* </pre>
*
*
* @author grro@xsocket.org
*/
public interface IServer extends Runnable, Closeable {
/**
* the default idle timeout
*/
public static final int DEFAULT_IDLE_TIMEOUT_SEC = 1 * 60 * 60; // one hour
/**
* the default connection timeout
*/
public static final int DEFAULT_CONNECTION_TIMEOUT_SEC = Integer.MAX_VALUE; // no timeout
public static final String SO_RCVBUF = IConnection.SO_RCVBUF;
public static final String SO_REUSEADDR = IConnection.SO_REUSEADDR;
public static final int DEFAULT_READ_TRANSFER_PREALLOCATION_SIZE = 65536;
public static final int DEFAULT_READ_TRANSFER_PREALLOCATION_MIN_SIZE = 64;
public static final boolean DEFAULT_READ_TRANSFER_USE_DIRECT = true;
/**
* signals, if service is running
*
* @return true, if the server is running
*/
boolean isOpen();
/**
* starts the given server within a dedicated thread. This method blocks
* until the server is open.
*
* @throws SocketTimeoutException is the timeout has been reached
*/
void start() throws IOException;
/**
* returns the idle timeout in millis.
*
* @return idle timeout in millis
*/
long getIdleTimeoutMillis();
/**
* sets the idle timeout in millis
*
* @param timeoutInSec idle timeout in millis
*/
void setIdleTimeoutMillis(long timeoutInMillis);
/**
* gets the connection timeout
*
* @return connection timeout
*/
long getConnectionTimeoutMillis();
/**
* sets the max time for a connections. By
* exceeding this time the connection will be
* terminated
*
* @param timeoutSec the connection timeout in millis
*/
void setConnectionTimeoutMillis(long timeoutMillis);
/**
* set the send delay time for a connection. Data to write will be buffered
* internally and be written to the underlying subsystem
* based on the given write rate.
* The write methods will <b>not</b> block for this time. <br>
*
* By default the write transfer rate is set with UNLIMITED <br><br>
*
* Reduced write transfer is only supported for FlushMode.ASYNC. see
* {@link INonBlockingConnection#setFlushmode(org.xsocket.connection.IConnection.FlushMode))}
*
* @param bytesPerSecond the transfer rate of the outgoing data
* @throws IOException If some other I/O error occurs
*/
void setWriteTransferRate(int bytesPerSecond) throws IOException;
/**
* set the read rate. By default the read transfer rate is set with UNLIMITED <br><br>
*
* @param bytesPerSecond the transfer rate of the outgoing data
* @throws IOException If some other I/O error occurs
*/
// public void setReadTransferRate(int bytesPerSecond) throws IOException;
/**
* get the server port
*
* @return the server port
*/
int getLocalPort();
/**
* return the worker pool
*
* @return the worker pool
*/
Executor getWorkerpool();
/**
* sets the worker pool
* @param workerpool the workerpool
*/
void setWorkerpool(Executor workerpool);
/**
* gets the handler
* @return the handler
*/
IHandler getHandler();
/**
*
* sets the flush mode for new connections. See {@link INonBlockingConnection#setFlushmode(FlushMode)}
* for more information
*
* @param flusmode the flush mode
*/
void setFlushmode(FlushMode flusmode);
/**
* return the flush mode for new connections
*
* @return the flush mode
*/
FlushMode getFlushmode();
/**
* set autoflush for new connections. See {@link IReadWriteableConnection#setAutoflush(boolean)}
* for more information
*
* @param autoflush true if autoflush should be activated
*/
void setAutoflush(boolean autoflush);
/**
* get autoflush. See {@link IReadWriteableConnection#setAutoflush(boolean)}
* for more information
*
* @return true, if autoflush is activated
*/
boolean getAutoflush();
/**
* adds a listener
* @param listener gthe listener to add
*/
void addListener(IServerListener listener);
/**
* removes a listener
* @param listener the listener to remove
* @return true, is the listener has been removed
*/
boolean removeListener(IServerListener listener);
/**
* get the local address
* @return the local address
*/
InetAddress getLocalAddress();
/**
* returns the vlaue of a option
*
* @param name the name of the option
* @return the value of the option
* @throws IOException In an I/O error occurs
*/
Object getOption(String name) throws IOException;
/**
* set the log message, which will be printed out during the start up
*
* @param message the startUp log message
*/
void setStartUpLogMessage(String message);
/**
* returns the startUp log message
*
* @return the startUp log message
*/
String getStartUpLogMessage();
/**
* Returns an unmodifiable map of the options supported by this endpont.
*
* The key in the returned map is the name of a option, and its value
* is the type of the option value. The returned map will never contain null keys or values.
*
* @return An unmodifiable map of the options supported by this channel
*/
@SuppressWarnings("unchecked")
Map<String, Class> getOptions();
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IServer.java | Java | art | 8,524 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Call back interface to notify io events of the {@link IIoHandler}. The IIoHandler
* is responsible to notify the events in the occured order. <br><br>
*
*
*
* @author grro@xsocket.org
*/
interface IIoHandlerCallback {
/**
* notifies that data has been read from the socket. <br><br>
*
* @param data the received data
* @param size the received data size
*
*/
void onData(ByteBuffer[] data, int size);
/**
* notifies that data read taks has been completed <br><br>
*
*/
void onPostData();
/**
* notifies that the underlying connection has been established. <br>
*
*/
void onConnect();
/**
* notifies that the underlying connection has not been established caused by an error
*
* @param ioe the error
*/
void onConnectException(IOException ioe);
/**
* notifies that the underlying connection has been disconnected (closed).<br>
*
*/
void onDisconnect();
/**
* notifies that the connection has to be closed (connection is corrupt,
* selector has be closed, ...). This call back method will NOT be called in the case of
* idle or connection time out.<br><br>
*
*/
void onConnectionAbnormalTerminated();
/**
* notifies that data has been written on the socket.<br><br>
*
* @param data the written data
*/
void onWritten(ByteBuffer data);
/**
* notifies that an error has been occurred by writing data on the socket.<br><br>
*
* @param ioe ioException an io exception
* @param data the data, which has been tried to write
*/
void onWriteException(IOException ioException, ByteBuffer data);
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IIoHandlerCallback.java | Java | art | 2,815 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
/**
* Call back handler. Example:
*
* <pre>
* class MyWriteCompletionHandler implements IWriteCompletionHandler {
*
* public void onWritten(int written) throws IOException {
* // ...
* }
*
* public void onException(IOException ioe) {
* // ...
* }
* }
*
*
* ReadableByteChannel channel = ...
* INonBlockingConnection con = ...
* MyWriteCompletionHandler writeCompletionHandler = new MyWriteCompletionHandler();
*
* con.setFlushmode(FlushMode.ASYNC);
* con.write(transferBuffer, writeCompletionHandler); // returns immediately
*
* // ...
*
* </pre>
*
* @author grro@xsocket.org
*/
public interface IWriteCompletionHandler {
/**
* call back, which will be called after the data is written
*
* @param written the written size
* @throws IOException if an exception occurs. By throwing this
* exception the connection will be closed by xSocket
*/
public void onWritten(int written) throws IOException;
/**
* call back to sginal a write error
*
* @param ioe the exception
*/
public void onException(IOException ioe);
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IWriteCompletionHandler.java | Java | art | 2,286 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.Flushable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import org.xsocket.IDataSink;
import org.xsocket.IDataSource;
import org.xsocket.MaxReadSizeExceededException;
/**
* A connection which accesses the underlying channel in a non-blocking manner. Every read I/O operation
* will block until it completes. The blocking behavior of write operations will be controlled by the
* flush configuration.
*
* @author grro@xsocket.org
*/
public interface IBlockingConnection extends IConnection, IDataSource, IDataSink, GatheringByteChannel, ReadableByteChannel, WritableByteChannel, Flushable {
public static final int DEFAULT_READ_TIMEOUT = Integer.MAX_VALUE;
/**
* set autoflush. If autoflush is activated, each write call
* will cause a flush. <br><br>
*
* @param autoflush true if autoflush should be activated
*/
void setAutoflush(boolean autoflush);
/**
* get autoflush
*
* @return true, if autoflush is activated
*/
boolean isAutoflush();
/**
* flush the send buffer. The method call will block until
* the outgoing data has been flushed into the underlying
* os-specific send buffer.
*
* @throws IOException If some other I/O error occurs
* @throws SocketTimeoutException If the timeout has been reached
* @throws ClosedChannelException if the underlying channel is closed
*/
void flush() throws ClosedChannelException, IOException, SocketTimeoutException;
/**
* ad hoc activation of a secured mode (SSL). By performing of this
* method all remaining data to send will be flushed.
* After this all data will be sent and received in the secured mode
*
* @throws IOException If some other I/O error occurs
*/
void activateSecuredMode() throws IOException;
/**
* ad hoc deactivation of a secured mode (SSL). By performing of this
* method all remaining data to send will be flushed.
* After this all data will be sent and received in the plain mode
*
* @throws IOException If some other I/O error occurs
*/
void deactivateSecuredMode() throws IOException;
/**
* returns if the connection is in secured mode
* @return true, if the connection is in secured mode
*/
boolean isSecure();
/**
* returns the size of the data which have already been written, but not
* yet transferred to the underlying socket.
*
* @return the size of the pending data to write
*/
int getPendingWriteDataSize();
/**
* set the timeout for calling read methods in millis
*
* @param timeout the timeout in millis
* @throws IOException If some other I/O error occurs
*/
void setReadTimeoutMillis(int timeout) throws IOException;
/**
* get the timeout for calling read methods in millis
*
* @return the timeout in millis
* @throws IOException If some other I/O error occurs
*/
int getReadTimeoutMillis() throws IOException;
/**
* suspend receiving data from the underlying subsystem
*
* @throws IOException If some other I/O error occurs
*/
void suspendReceiving() throws IOException;
/**
* resume receiving data from the underlying subsystem
*
* @throws IOException If some other I/O error occurs
*/
void resumeReceiving() throws IOException;
/**
* returns true if receiving is suspended
*
* @return true, if receiving is suspended
*/
boolean isReceivingSuspended();
/**
* returns the ByteBuffer to the <i>top</i> of the read queue.
*
* @param buffers the buffers to return
* @throws IOException if an exception occurs
*/
void unread(ByteBuffer[] buffers) throws IOException;
/**
* returns the ByteBuffer to the <i>top</i> of the read queue.
*
* @param buffer the buffer to return
* @throws IOException if an exception occurs
*/
void unread(ByteBuffer buffer) throws IOException;
/**
* returns the bytes to the <i>top</i> of the read queue.
*
* @param bytes the bytes to return
* @throws IOException if an exception occurs
*/
void unread(byte[] bytes) throws IOException;
/**
* returns the text to the <i>top</i> of the read queue.
*
* @param text the text to return
* @throws IOException if an exception occurs
*/
void unread(String text) throws IOException;
/**
* Resets to the marked write position. If the connection has been marked,
* then attempt to reposition it at the mark.
*
* @return true, if reset was successful
*/
boolean resetToWriteMark();
/**
* Resets to the marked read position. If the connection has been marked,
* then attempt to reposition it at the mark.
*
* @return true, if reset was successful
*/
boolean resetToReadMark();
/**
* Marks the write position in the connection.
*/
void markWritePosition();
/**
* Marks the read position in the connection. Subsequent calls to resetToReadMark() will attempt
* to reposition the connection to this point.
*
*/
void markReadPosition();
/**
* remove the read mark
*/
void removeReadMark();
/**
* remove the write mark
*/
void removeWriteMark();
/**
* gets the encoding (used by string related methods like write(String) ...)
*
* @return the encoding
*/
String getEncoding();
/**
* sets the encoding (used by string related methods like write(String) ...)
*
* @param encoding the encoding
*/
void setEncoding(String encoding);
/**
* write a message
*
* @param message the message to write
* @param encoding the encoding which should be used th encode the chars into byte (e.g. `US-ASCII` or `UTF-8`)
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(String message, String encoding) throws IOException, BufferOverflowException;
/**
* writes a byte buffer array. Typically this write mthod will be used in async flush mode
*
* @param buffers the buffers to write
* @param writeCompletionHandler the completionHandler
* @throws IOException If some I/O error occurs
*/
void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a byte buffer. Typically this write mthod will be used in async flush mode
*
* @param buffer the buffer to write
* @param writeCompletionHandler the completionHandler
* @throws IOException If some I/O error occurs
*/
void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a list of bytes to the data sink. Typically this write mthod will be used in async flush mode
*
* @param buffers the bytes to write
* @param writeCompletionHandler the completionHandler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a byte buffer array. Typically this write mthod will be used in async flush mode
*
* @param srcs the buffers
* @param offset the offset
* @param length the length
* @param writeCompletionHandler the completionHandler
* @throws IOException If some I/O error occurs
*/
void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes bytes to the data sink
*
* @param bytes the bytes to write
* @param writeCompletionHandler the completion handler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes bytes to the data sink. Typically this write mthod will be used in async flush mode
*
* @param bytes the bytes to write
* @param offset the offset of the sub array to be used; must be non-negative and no larger than array.length. The new buffer`s position will be set to this value.
* @param length the length of the sub array to be used; must be non-negative and no larger than array.length - offset. The new buffer`s limit will be set to offset + length.
* @param writeCompletionHandler the completion handler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a message. Typically this write mthod will be used in async flush mode
*
* @param message the message to write
* @param encoding the encoding which should be used th encode the chars into byte (e.g. `US-ASCII` or `UTF-8`)
* @param writeCompletionHandler the completion handler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* read a ByteBuffer by using a delimiter. The default encoding will be used to decode the delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @return the ByteBuffer
* @throws BufferUnderflowException If not enough data is available
* @throws IOException If some other I/O error occurs
*/
ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, SocketTimeoutException;
/**
* read a ByteBuffer by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding of the delimiter
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the ByteBuffer
* @throws BufferUnderflowException If not enough data is available
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
*/
ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, SocketTimeoutException;
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @return the read bytes
* @throws BufferUnderflowException If not enough data is available
* @throws IOException If some other I/O error occurs
*/
byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException;
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the read bytes
* @throws BufferUnderflowException If not enough data is available
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
*/
byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, SocketTimeoutException;
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @return the string
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException If not enough data is available
* @throws UnsupportedEncodingException if the given encoding is not supported
*/
String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException;
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the string
* @throws BufferUnderflowException If not enough data is available
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found * @throws ClosedConnectionException If the underlying socket is already closed
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException If the given encoding is not supported
*/
String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException;
/**
* read a string by using a length definition
*
* @param length the amount of bytes to read.
* @param encoding the encoding to use
* @return the string
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException If not enough data is available
* @throws UnsupportedEncodingException if the given encoding is not supported
* @throws IllegalArgumentException, if the length parameter is negative
*/
String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, SocketTimeoutException;
/**
* transfer the data of the file channel to this data sink
*
* @param source the source channel
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
long transferFrom(FileChannel source) throws IOException, BufferOverflowException;
/**
* get the max app read buffer size. If the read buffer size exceeds this limit the
* connection will stop receiving data. The read buffer size can be higher the limit
* (max size = maxReadBufferThreshold + socket read buffer size * 2)
*
* @return the max read buffer threshold
*/
int getMaxReadBufferThreshold();
/**
* set the max app read buffer threshold
* @param maxSize the max read buffer threshold
*/
void setMaxReadBufferThreshold(int size);
/**
* see {@link INonBlockingConnection#getFlushmode()}
*/
void setFlushmode(FlushMode flushMode);
/**
* see {@link INonBlockingConnection#setFlushmode(FlushMode)}
*/
FlushMode getFlushmode();
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IBlockingConnection.java | Java | art | 18,028 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
/**
*
* @author grro@xsocket.org
*/
interface IExecutor {
void performNonThreaded(Runnable task);
void performMultiThreaded(Runnable task);
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IExecutor.java | Java | art | 1,206 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnection.FlushMode;
/**
* implementation base of a data stream.
*
* <br/><br/><b>This is a xSocket internal class and subject to change</b>
*
* @author grro@xsocket.org
*/
public abstract class AbstractNonBlockingStream implements WritableByteChannel, Closeable {
private static final Logger LOG = Logger.getLogger(AbstractNonBlockingStream.class.getName());
private final ReadQueue readQueue = new ReadQueue();
private final WriteQueue writeQueue = new WriteQueue();
static final int TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE = IoProvider.getTransferByteBufferMaxSize();
private final AtomicReference<String> defaultEncodingRef = new AtomicReference<String>(IConnection.INITIAL_DEFAULT_ENCODING);
// open flag
private final AtomicBoolean isOpen = new AtomicBoolean(true);
//flushing
private final AtomicBoolean autoflush = new AtomicBoolean(IConnection.DEFAULT_AUTOFLUSH);
private final AtomicReference<FlushMode> flushmodeRef = new AtomicReference<FlushMode>(IConnection.DEFAULT_FLUSH_MODE);
// attachment
private AtomicReference<Object> attachmentRef = new AtomicReference<Object>(null);
// illegal async write detection support
private boolean isSuppressReuseBufferWarning = IoProvider.getSuppressReuseBufferWarning();
private WeakReference<ByteBuffer> previousWriteByteBuffer;
private WeakReference<ByteBuffer[]> previousWriteByteBuffers;
private WeakReference<ByteBuffer[]> previousWriteByteBuffers2;
public void close() throws IOException {
isOpen.set(false);
}
private void closeSilence() {
try {
close();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing connection " + this + " " + ioe.toString());
}
}
}
/**
* Attaches the given object to this connection
*
* @param obj The object to be attached; may be null
* @return The previously-attached object, if any, otherwise null
*/
public final void setAttachment(Object obj) {
attachmentRef.set(obj);
}
/**
* Retrieves the current attachment.
*
* @return The object currently attached to this key, or null if there is no attachment
*/
public final Object getAttachment() {
return attachmentRef.get();
}
/**
* sets the default encoding
*
* @param defaultEncoding the default encoding
*/
public final void setEncoding(String defaultEncoding) {
this.defaultEncodingRef.set(defaultEncoding);
}
/**
* gets the default encoding
*
* @return the default encoding
*/
public final String getEncoding() {
return defaultEncodingRef.get();
}
/**
* see {@link IConnection#setFlushmode(FlushMode)}
*/
public void setFlushmode(FlushMode flushMode) {
this.flushmodeRef.set(flushMode);
}
/**
* see {@link IConnection#getFlushmode()}
*/
public final FlushMode getFlushmode() {
return flushmodeRef.get();
}
/**
* set true if ReuseBufferWarning is suppressed
*
* @param isSuppressReuseBufferWarning true if ReuseBufferWarning is suppressed
*/
protected final void setSuppressReuseBufferWarning(boolean isSuppressReuseBufferWarning) {
this.isSuppressReuseBufferWarning = isSuppressReuseBufferWarning;
}
/**
* return true if ReuseBufferWaring is suppresses
*
* @return true if ReuseBufferWaring is suppresses
*/
protected final boolean isSuppressReuseBufferWarning() {
return isSuppressReuseBufferWarning;
}
/**
* returns the default chunk size for writing
*
* @return write chunk size
*/
protected int getWriteTransferChunkeSize() {
return 8196;
}
/**
* set autoflush. If autoflush is activated, each write call
* will cause a flush. <br><br>
*
* @param autoflush true if autoflush should be activated
*/
public final void setAutoflush(boolean autoflush) {
this.autoflush.set(autoflush);
}
/**
* get autoflush
*
* @return true, if autoflush is activated
*/
public final boolean isAutoflush() {
return autoflush.get();
}
/**
* returns true, if the underlying data source is open
*
* @return true, if the underlying data source is open
*/
protected abstract boolean isMoreInputDataExpected();
/**
* returns true, if the underlying data sink is open
*
* @return true, if the underlying data sink is open
*/
protected abstract boolean isDataWriteable();
/**
* Returns the index of the first occurrence of the given string.
*
* @param str any string
* @return if the string argument occurs as a substring within this object, then
* the index of the first character of the first such substring is returned;
* if it does not occur as a substring, -1 is returned.
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int indexOf(String str) throws IOException, ClosedChannelException {
return indexOf(str, getEncoding());
}
/**
* Returns the index of the first occurrence of the given string.
*
* @param str any string
* @param encoding the encoding to use
* @return if the string argument occurs as a substring within this object, then
* the index of the first character of the first such substring is returned;
* if it does not occur as a substring, -1 is returned.
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int indexOf(String str, String encoding) throws IOException, ClosedChannelException {
ensureStreamIsOpen();
return readQueue.retrieveIndexOf(str.getBytes(encoding), Integer.MAX_VALUE);
}
/**
* get the number of available bytes to read
*
* @return the number of available bytes or -1 if the end of stream is reached
* @throws IOException if an exception has been occurred
*/
public int available() {
if (!isOpen.get()) {
return -1;
}
int size = readQueue.getSize();
if (size == 0) {
if (isMoreInputDataExpected()) {
return 0;
} else {
return -1;
}
}
return size;
}
/**
* returns the read queue size without additional check
*
* @return the read queue size
*/
protected int getReadQueueSize() {
return readQueue.getSize();
}
/**
* get the version of read buffer. The version number increases, if
* the read buffer queue has been modified
*
*/
public int getReadBufferVersion() {
return readQueue.geVersion();
}
/**
* notification method which will be called after data has been read internally
*
* @param readBufs the read buffers
* @param the buffers to return to the caller
* @throws IOException If some other I/O error occurs
*/
protected ByteBuffer[] onRead(ByteBuffer[] readBufs) throws IOException {
return readBufs;
}
public void unread(ByteBuffer[] buffers) throws IOException {
if ((buffers == null) || (buffers.length == 0)) {
return;
}
readQueue.unread(buffers);
}
public void unread(ByteBuffer buffer) throws IOException {
if (buffer == null) {
return;
}
unread(new ByteBuffer[] { buffer });
}
public void unread(byte[] bytes) throws IOException {
unread(ByteBuffer.wrap(bytes));
}
public void unread(String text) throws IOException {
unread(DataConverter.toByteBuffer(text, getEncoding()));
}
/**
* read a byte
*
* @return the byte value
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public byte readByte() throws IOException, BufferUnderflowException, ClosedChannelException {
return readSingleByteBuffer(1).get();
}
/**
* read a short value
*
* @return the short value
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public short readShort() throws IOException, BufferUnderflowException, ClosedChannelException {
return readSingleByteBuffer(2).getShort();
}
/**
* read an int
*
* @return the int value
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public int readInt() throws IOException, BufferUnderflowException, ClosedChannelException {
return readSingleByteBuffer(4).getInt();
}
/**
* read a long
*
* @return the long value
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public long readLong() throws IOException, BufferUnderflowException, ClosedChannelException {
return readSingleByteBuffer(8).getLong();
}
/**
* read a double
*
* @return the double value
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public double readDouble() throws IOException, BufferUnderflowException, ClosedChannelException {
return readSingleByteBuffer(8).getDouble();
}
/**
* see {@link ReadableByteChannel#read(ByteBuffer)}
*/
public int read(ByteBuffer buffer) throws IOException, ClosedChannelException {
int size = buffer.remaining();
int available = available();
if ((available == 0) && !isMoreInputDataExpected()) {
closeSilence();
return -1;
}
if (available < size) {
size = available;
}
if (size > 0) {
copyBuffers(readByteBufferByLength(size), buffer);
}
if (size == -1) {
closeSilence();
}
return size;
}
private void copyBuffers(ByteBuffer[] source, ByteBuffer target) {
for (ByteBuffer buf : source) {
if (buf.hasRemaining()) {
target.put(buf);
}
}
}
/**
* read a ByteBuffer by using a delimiter. The default encoding will be used to decode the delimiter
* To avoid memory leaks the {@link IReadWriteableConnection#readByteBufferByDelimiter(String, int)} method is generally preferable
* <br>
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @return the ByteBuffer
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter) throws IOException, BufferUnderflowException, ClosedChannelException {
return readByteBufferByDelimiter(delimiter, getEncoding());
}
/**
* read a ByteBuffer by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the ByteBuffer
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, ClosedChannelException {
return readByteBufferByDelimiter(delimiter, getEncoding(), maxLength);
}
/**
* read a ByteBuffer by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the delimiter encoding
* @return the ByteBuffer
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, ClosedChannelException {
return readByteBufferByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* read a ByteBuffer by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the delimiter encoding
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the ByteBuffer
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, ClosedChannelException {
ensureStreamIsOpen();
int version = getReadBufferVersion();
try {
ByteBuffer[] buffers = readQueue.readByteBufferByDelimiter(delimiter.getBytes(encoding), maxLength);
return onRead(buffers);
} catch (MaxReadSizeExceededException mre) {
if (isMoreInputDataExpected()) {
throw mre;
} else {
closeSilence();
throw new ClosedChannelException();
}
} catch (BufferUnderflowException bue) {
if (isMoreInputDataExpected() || (version != getReadBufferVersion())) {
throw bue;
} else {
closeSilence();
throw new ExtendedClosedChannelException("channel is closed (read buffer size=" + readQueue.getSize() + ")");
}
}
}
/**
* read a ByteBuffer
*
* @param length the length could be negative, in this case a empty array will be returned
* @return the ByteBuffer
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public ByteBuffer[] readByteBufferByLength(int length) throws IOException, BufferUnderflowException, ClosedChannelException {
ensureStreamIsOpen();
if (length <= 0) {
if (!isMoreInputDataExpected()) {
closeSilence();
throw new ClosedChannelException();
}
return onRead(new ByteBuffer[0]);
}
int version = getReadBufferVersion();
try {
ByteBuffer[] buffers = readQueue.readByteBufferByLength(length);
return onRead(buffers);
} catch (BufferUnderflowException bue) {
if (isMoreInputDataExpected() || (version != getReadBufferVersion())) {
throw bue;
} else {
closeSilence();
throw new ClosedChannelException();
}
}
}
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @return the read bytes
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public byte[] readBytesByDelimiter(String delimiter) throws IOException, BufferUnderflowException, ClosedChannelException {
return readBytesByDelimiter(delimiter, getEncoding());
}
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the read bytes
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public byte[] readBytesByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, ClosedChannelException {
return readBytesByDelimiter(delimiter, getEncoding(), maxLength);
}
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the delimiter encoding
* @return the read bytes
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, ClosedChannelException {
return readBytesByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the delimiter encoding
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the read bytes
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, ClosedChannelException {
return DataConverter.toBytes(readByteBufferByDelimiter(delimiter, encoding, maxLength));
}
/**
* read bytes by using a length definition
*
* @param length the amount of bytes to read
* @return the read bytes
* @throws IOException If some other I/O error occurs
* @throws IllegalArgumentException, if the length parameter is negative
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public byte[] readBytesByLength(int length) throws IOException, BufferUnderflowException, ClosedChannelException {
return DataConverter.toBytes(readByteBufferByLength(length));
}
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @return the string
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException if the default encoding is not supported
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public String readStringByDelimiter(String delimiter) throws IOException, BufferUnderflowException, UnsupportedEncodingException, ClosedChannelException {
return readStringByDelimiter(delimiter, Integer.MAX_VALUE);
}
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the string
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException If the given encoding is not supported
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public String readStringByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, ClosedChannelException {
return readStringByDelimiter(delimiter, getEncoding(), maxLength);
}
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param encoding the encoding
* @return the string
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException If the given encoding is not supported
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, ClosedChannelException {
return readStringByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param encoding the encoding
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the string
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException If the given encoding is not supported
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, ClosedChannelException {
return DataConverter.toString(readByteBufferByDelimiter(delimiter, encoding, maxLength), encoding);
}
/**
* read a string by using a length definition
*
* @param length the amount of bytes to read
* @return the string
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException if the given encoding is not supported
* @throws IllegalArgumentException, if the length parameter is negative
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public String readStringByLength(int length) throws IOException, BufferUnderflowException, UnsupportedEncodingException, ClosedChannelException {
return readStringByLength(length, getEncoding());
}
/**
* read a string by using a length definition
*
* @param length the amount of bytes to read
* @param encoding the encoding
* @return the string
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException if the given encoding is not supported
* @throws IllegalArgumentException, if the length parameter is negative
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, ClosedChannelException {
return DataConverter.toString(readByteBufferByLength(length), encoding);
}
/**
* transfer the data of the this source channel to the given data sink
*
* @param dataSink the data sink
* @param length the size to transfer
*
* @return the number of transfered bytes
* @throws ClosedChannelException If either this channel or the target channel is closed
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
public long transferTo(WritableByteChannel target, int length) throws IOException, ClosedChannelException, BufferUnderflowException, ClosedChannelException {
if (length > 0) {
long written = 0;
int available = available();
if (available < length) {
length = available;
}
ByteBuffer[] buffers = readByteBufferByLength(length);
for (ByteBuffer buffer : buffers) {
while(buffer.hasRemaining()) {
written += target.write(buffer);
}
}
return written;
} else {
return 0;
}
}
/**
* read a byte buffer by length. If the underlying data is fragmented over several ByteBuffer,
* the ByteBuffers will be merged
*
* @param length the length
* @return the byte buffer
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException if not enough data is available
* @throws ClosedChannelException If the stream is closed
*/
protected ByteBuffer readSingleByteBuffer(int length) throws IOException, ClosedChannelException, BufferUnderflowException, ClosedChannelException {
ensureStreamIsOpen();
int version = getReadBufferVersion();
try {
ByteBuffer buffer = readQueue.readSingleByteBuffer(length);
return DataConverter.toByteBuffer(new ByteBuffer[] { buffer });
} catch (BufferUnderflowException bue) {
if (isMoreInputDataExpected() || (version != getReadBufferVersion())) {
throw bue;
} else {
closeSilence();
throw new ClosedChannelException();
}
}
}
/**
* writes a byte to the data sink
*
* @param b the byte to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(byte b) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
writeQueue.append(DataConverter.toByteBuffer(b));
onWriteDataInserted();
return 1;
}
/**
* writes bytes to the data sink
*
* @param bytes the bytes to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(byte... bytes) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
if (bytes.length > 0) {
writeQueue.append(DataConverter.toByteBuffer(bytes));
onWriteDataInserted();
return bytes.length;
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("warning length of byte array to send is 0");
}
return 0;
}
}
/**
* writes bytes to the data sink
*
* @param bytes the bytes to write
* @param offset The offset of the sub array to be used; must be non-negative and no larger than array.length. The new buffer`s position will be set to this value.
* @param length The length of the sub array to be used; must be non-negative and no larger than array.length - offset. The new buffer`s limit will be set to offset + length.
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(byte[] bytes, int offset, int length) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
if (bytes.length > 0) {
ByteBuffer buffer = DataConverter.toByteBuffer(bytes, offset, length);
int written = buffer.remaining();
writeQueue.append(buffer);
onWriteDataInserted();
return written;
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("warning length of buffer array to send is 0");
}
return 0;
}
}
/**
* writes a short to the data sink
*
* @param s the short value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(short s) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
writeQueue.append(DataConverter.toByteBuffer(s));
onWriteDataInserted();
return 2;
}
/**
* writes a int to the data sink
*
* @param i the int value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(int i) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
writeQueue.append(DataConverter.toByteBuffer(i));
onWriteDataInserted();
return 4;
}
/**
* writes a long to the data sink
*
* @param l the int value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public final int write(long l) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
writeQueue.append(DataConverter.toByteBuffer(l));
onWriteDataInserted();
return 8;
}
/**
* writes a double to the data sink
*
* @param d the int value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(double d) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
writeQueue.append(DataConverter.toByteBuffer(d));
onWriteDataInserted();
return 8;
}
/**
* writes a message
*
* @param message the message to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(String message) throws IOException, BufferOverflowException, ClosedChannelException {
return write(message, getEncoding());
}
/**
* writes a message
*
* @param message the message to write
* @param encoding the encoding
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public int write(String message, String encoding) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
ByteBuffer buffer = DataConverter.toByteBuffer(message, encoding);
int written = buffer.remaining();
writeQueue.append(buffer);
onWriteDataInserted();
return written;
}
/**
* writes a list of bytes to the data sink
*
* @param buffers the bytes to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public long write(List<ByteBuffer> buffers) throws IOException, BufferOverflowException, ClosedChannelException {
if (buffers == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("warning buffer list to send is null");
}
return 0;
}
return write(buffers.toArray(new ByteBuffer[buffers.size()]));
}
/**
* see {@link GatheringByteChannel#write(ByteBuffer[], int, int)} and
* {@link INonBlockingConnection#setFlushmode(FlushMode)}
*/
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException, ClosedChannelException {
if (srcs == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("warning buffer array to send is null");
}
return 0;
}
if ((getFlushmode() == FlushMode.ASYNC) && (previousWriteByteBuffers2 != null)) {
ByteBuffer[] previous = previousWriteByteBuffers2.get();
if ((previous != null) && (previous == srcs)) {
LOG.warning("reuse of the byte buffer by calling the write(ByteBuffer[], ...) method in FlushMode.ASYNC can lead to race conditions (Hint: use FlushMode.SYNC)");
}
}
long written = write(DataConverter.toByteBuffers(srcs, offset, length));
if (flushmodeRef.get() == FlushMode.ASYNC) {
previousWriteByteBuffers2 = new WeakReference<ByteBuffer[]>(srcs);
}
return written;
}
/**
* see {@link GatheringByteChannel#write(ByteBuffer[])} and
* {@link INonBlockingConnection#setFlushmode(FlushMode)}
*/
public long write(ByteBuffer[] buffers) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
if (!isSuppressReuseBufferWarning && (getFlushmode() == FlushMode.ASYNC) && (previousWriteByteBuffers != null)) {
ByteBuffer[] previous = previousWriteByteBuffers.get();
if ((previous != null) && (previous == buffers)) {
LOG.warning("reuse of the byte buffer by calling the write(ByteBuffer[]) method in FlushMode.ASYNC can lead to race conditions (Hint: use FlushMode.SYNC)");
}
}
if ((buffers == null) || (buffers.length == 0)) {
return 0;
}
long written = 0;
for (ByteBuffer buffer : buffers) {
int size = buffer.remaining();
if (size > 0) {
onPreWrite(size);
writeQueue.append(buffer);
written += size;
onWriteDataInserted();
}
}
if (flushmodeRef.get() == FlushMode.ASYNC) {
previousWriteByteBuffers = new WeakReference<ByteBuffer[]>(buffers);
}
return written;
}
/**
* see {@link WritableByteChannel#write(ByteBuffer)} and
* {@link INonBlockingConnection#setFlushmode(FlushMode)}
*/
public int write(ByteBuffer buffer) throws IOException, BufferOverflowException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
if (!isSuppressReuseBufferWarning && (getFlushmode() == FlushMode.ASYNC) && (previousWriteByteBuffer != null)) {
ByteBuffer previous = previousWriteByteBuffer.get();
if ((previous != null) && (previous == buffer)) {
LOG.warning("reuse of the byte buffer by calling the write(ByteBuffer) method in FlushMode.ASYNC can lead to race conditions (Hint: use FlushMode.SYNC or deactivate log out put by setting system property " + IoProvider.SUPPRESS_REUSE_BUFFER_WARNING_KEY + " to true)");
}
}
if (buffer == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("warning buffer is null");
}
return 0;
}
int size = buffer.remaining();
if (size > 0) {
onPreWrite(size);
writeQueue.append(buffer);
onWriteDataInserted();
}
if (flushmodeRef.get() == FlushMode.ASYNC) {
previousWriteByteBuffer = new WeakReference<ByteBuffer>(buffer);
}
return size;
}
/**
* call back method which will be called before writing data into the write queue
*
* @param size the size to write
* @throws BufferOverflowException if the write buffer max size is exceeded
*/
protected void onPreWrite(int size) throws BufferOverflowException {
}
/**
* transfer the data of the file channel to this data sink
*
* @param fileChannel the file channel
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public long transferFrom(FileChannel fileChannel) throws ClosedChannelException, IOException, SocketTimeoutException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
if (getFlushmode() == FlushMode.SYNC) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("tranfering file by using MappedByteBuffer (MAX_MAP_SIZE=" + TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE + ")");
}
final long size = fileChannel.size();
long remaining = size;
long offset = 0;
long length = 0;
do {
if (remaining > TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE) {
length = TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE;
} else {
length = remaining;
}
MappedByteBuffer buffer = fileChannel.map(MapMode.READ_ONLY, offset, length);
long written = write(buffer);
offset += written;
remaining -= written;
} while (remaining > 0);
return size;
} else {
return transferFrom((ReadableByteChannel) fileChannel);
}
}
/**
* transfer the data of the source channel to this data sink
*
* @param source the source channel
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public long transferFrom(ReadableByteChannel source) throws IOException, BufferOverflowException, ClosedChannelException {
return transferFrom(source, TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE);
}
/**
* transfer the data of the source channel to this data sink
*
* @param source the source channel
* @param chunkSize the chunk size to use
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
* @throws ClosedChannelException If the stream is closed
*/
public long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException, BufferOverflowException, ClosedChannelException {
return transfer(source, this, chunkSize);
}
private long transfer(ReadableByteChannel source, WritableByteChannel target, int chunkSize) throws IOException, ClosedChannelException {
ensureStreamIsOpenAndWritable();
long transfered = 0;
int read = 0;
do {
ByteBuffer transferBuffer = ByteBuffer.allocate(chunkSize);
read = source.read(transferBuffer);
if (read > 0) {
if (transferBuffer.remaining() == 0) {
transferBuffer.flip();
target.write(transferBuffer);
} else {
transferBuffer.flip();
target.write(transferBuffer.slice());
}
transfered += read;
}
} while (read > 0);
return transfered;
}
/**
* Marks the read position in the connection. Subsequent calls to resetToReadMark() will attempt
* to reposition the connection to this point.
*
*/
public final void markReadPosition() {
readQueue.markReadPosition();
}
/**
* Marks the write position in the connection.
*/
public final void markWritePosition() {
if (isAutoflush()) {
throw new UnsupportedOperationException("write mark is only supported for mode autoflush off");
}
writeQueue.markWritePosition();
}
/**
* Resets to the marked write position. If the connection has been marked,
* then attempt to reposition it at the mark.
*
* @return true, if reset was successful
*/
public final boolean resetToWriteMark() {
return writeQueue.resetToWriteMark();
}
/**
* Resets to the marked read position. If the connection has been marked,
* then attempt to reposition it at the mark.
*
* @return true, if reset was successful
*/
public final boolean resetToReadMark() {
return readQueue.resetToReadMark();
}
/**
* remove the read mark
*/
public final void removeReadMark() {
readQueue.removeReadMark();
}
/**
* remove the write mark
*/
public final void removeWriteMark() {
writeQueue.removeWriteMark();
}
/**
* resets the stream
*
* @return true, if the stream has been reset
*/
protected boolean reset() {
readQueue.reset();
writeQueue.reset();
defaultEncodingRef.set(IConnection.INITIAL_DEFAULT_ENCODING);
autoflush.set(IConnection.DEFAULT_AUTOFLUSH);
flushmodeRef.set(IConnection.DEFAULT_FLUSH_MODE);
attachmentRef.set(null);
return true;
}
/**
* notification, that data has been inserted
*
* @throws IOException if an exception occurs
* @throws ClosedChannelException if the stream is closed
*/
protected void onWriteDataInserted() throws IOException, ClosedChannelException {
}
/**
* gets the write buffer size
*
* @return the write buffer size
*/
protected final int getWriteBufferSize() {
return writeQueue.getSize();
}
/**
* returns if the write buffer is empty
* @return true, if the write buffer is empty
*/
protected final boolean isWriteBufferEmpty() {
return writeQueue.isEmpty();
}
/**
* drains the write buffer
*
* @return the write buffer content
*/
protected ByteBuffer[] drainWriteQueue() {
return writeQueue.drain();
}
/**
* drains the read buffer
*
* @return the read buffer content
*/
protected ByteBuffer[] drainReadQueue() {
return readQueue.readAvailable();
}
/**
* copies the read buffer
*
* @return the read buffer content
*/
protected ByteBuffer[] copyReadQueue() {
return readQueue.copyAvailable();
}
/**
* returns if the read buffer is empty
*
* @return true, if the read buffer is empty
*/
protected final boolean isReadBufferEmpty() {
return readQueue.isEmpty();
}
/**
* append data to the read buffer
*
* @param data the data to append
*/
protected final void appendDataToReadBuffer(ByteBuffer[] data, int size) {
readQueue.append(data, size);
onPostAppend();
}
protected void onPostAppend() {
}
/**
* prints the read buffer content
*
* @param encoding the encoding
* @return the read buffer content
*/
protected final String printReadBuffer(String encoding) {
return readQueue.toString(encoding);
}
/**
* prints the write buffer content
*
* @param encoding the encoding
* @return the write buffer content
*/
protected final String printWriteBuffer(String encoding) {
return writeQueue.toString(encoding);
}
private void ensureStreamIsOpen() throws ClosedChannelException {
if (!isOpen.get()) {
throw new ExtendedClosedChannelException("channel is closed (read buffer size=" + readQueue.getSize() + ")");
}
}
private void ensureStreamIsOpenAndWritable() throws ClosedChannelException {
if (!isOpen.get()) {
throw new ExtendedClosedChannelException("could not write. Channel is closed (" + getInfo() + ")");
}
if(!isDataWriteable()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("is not writeable clsoing connection " + getInfo());
}
closeSilence();
throw new ExtendedClosedChannelException("could not write. channel is close or not initialized (" + getInfo() + ")");
}
}
/**
* returns a info string
* @return a info string
*/
protected String getInfo() {
return "readBufferSize=" + readQueue.getSize();
}
public static interface ISink {
/**
* clean the sink
*/
void reset();
/**
* returns true, if empty
*
* @return true, if empty
*/
boolean isEmpty();
/**
* return the current size
*
* @return the current size
*/
int getSize();
void append(ByteBuffer data);
/**
* append a list of byte buffer to this sink. By adding a list,
* the list becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the list of ByteBuffer
*/
void append(ByteBuffer[] bufs);
/**
* drain the sink
*
* @return the queue content
*/
ByteBuffer[] drain();
ByteBuffer[] copy();
String toString(String encoding);
}
public static interface ISource {
/**
* clean the source
*/
void reset();
/**
* return a int, which represent the version.
* this value will increase with modification
*
* @return the modify version
*/
int getVersion(boolean mark);
void setVersion(int version);
/**
* return the current size
*
* @return the current size
*/
int getSize();
/**
* append a byte buffer array to this source. By adding a array,
* the array becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the ByteBuffers
* @param size the size
*/
void append(ByteBuffer[] bufs, int size);
void addFirst(ByteBuffer[] bufs);
/**
* drain the source
*
* @return the content
*/
ByteBuffer[] drain();
ByteBuffer[] copy();
/**
* read bytes
*
* @param length the length
* @return the read bytes
* @throws BufferUnderflowException if the buffer`s limit has been reached
*/
ByteBuffer readSingleByteBuffer(int length) throws BufferUnderflowException;
ByteBuffer[] readByteBufferByLength(int length) throws BufferUnderflowException;
ByteBuffer[] readByteBufferByDelimiter(byte[] delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException;
/**
* return the index of the delimiter or -1 if the delimiter has not been found
*
* @param delimiter the delimiter
* @param maxReadSize the max read size
* @return the position of the first delimiter byte
* @throws IOException in an exception occurs
* @throws MaxReadSizeExceededException if the max read size has been reached
*/
int retrieveIndexOf(byte[] delimiter, int maxReadSize) throws IOException, MaxReadSizeExceededException;
String toString(String encoding);
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/AbstractNonBlockingStream.java | Java | art | 51,110 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.BufferUnderflowException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.ILifeCycle;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.Resource;
/**
* Implements a handler chain. Each handler of the chain will be called (in the registering order),
* until one handler signal by the return value true, that the event has been handled. In
* this case the remaining handlers will not be called. <br><br>
*
* Nested chains is not supported yet
*
* <br>
* E.g.
* <pre>
* ...
* HandlerChain tcpBasedSpamfilter = new HandlerChain();
* tcpBasedSpamfilter.addLast(new BlackIPFilter());
* tcpBasedSpamfilter.addLast(new FirstConnectRefuseFilter());
*
* HandlerChain mainChain = new HandlerChain();
* mainChain.addLast(tcpBasedSpamfilter);
* mainChain.addLast(new SmtpProtocolHandler());
*
* IMultithreadedServer smtpServer = new MultithreadedServer(port, mainChain);
* StreamUtils.start(server);
* ...
*
* </pre>
*
*
* @author grro@xsocket.org
*/
public final class HandlerChain implements IHandler, IConnectHandler, IDataHandler, IDisconnectHandler, IConnectionTimeoutHandler, IIdleTimeoutHandler, ILifeCycle {
private static final Logger LOG = Logger.getLogger(HandlerChain.class.getName());
@Resource
private Server server = null;
private final List<WeakReference<HandlerChain>> enclosingChains = new ArrayList<WeakReference<HandlerChain>>();
private final HandlerInfo handlerInfo = new HandlerInfo();
// handlers
private final List<IHandler> handlers = new ArrayList<IHandler>();
private boolean isUnsynchronized = false;
private final List<ILifeCycle> lifeCycleChain = new ArrayList<ILifeCycle>();
private boolean isOnConnectPathMultithreaded = false;
private final List<IConnectHandler> connectHandlerChain = new ArrayList<IConnectHandler>();
private boolean isOnDataPathMultithreaded = false;
private final List<IDataHandler> dataHandlerChain = new ArrayList<IDataHandler>();
private boolean isOnDisconnectPathMultithreaded = false;
private final List<IDisconnectHandler> disconnectHandlerChain = new ArrayList<IDisconnectHandler>();
private boolean isOnIdleTimeoutPathMultithreaded = false;
private final List<IIdleTimeoutHandler> idleTimeoutHandlerChain = new ArrayList<IIdleTimeoutHandler>();
private boolean isOnConnectionTimeoutPathMultithreaded = false;
private final List<IConnectionTimeoutHandler> connectionTimeoutHandlerChain = new ArrayList<IConnectionTimeoutHandler>();
/*
* the execution mode will NOT be determined by annotations. In contrast to other handler
* this handler tpye is well known. To determine the execution mode the getHandlerInfo
* will used
*/
/**
* constructor
*
*/
public HandlerChain() {
}
IHandlerInfo getHandlerInfo() {
return handlerInfo;
}
/**
* constructor
*
* @param handlers the initial handlers
*/
public HandlerChain(List<IHandler> handlers) {
for (IHandler hdl : handlers) {
addLast(hdl);
}
}
public void onInit() {
for (IHandler handler : handlers) {
ConnectionUtils.injectServerField(server, handler);
}
for (ILifeCycle lifeCycle : lifeCycleChain) {
lifeCycle.onInit();
}
}
public void onDestroy() throws IOException {
for (ILifeCycle lifeCycle : lifeCycleChain) {
lifeCycle.onDestroy();
}
}
/**
* add a handler to the end og the chain
*
* @param handler the handler to add
*/
public void addLast(IHandler handler) {
if (handler instanceof HandlerChain) {
((HandlerChain) handler).registerChildChain(this);
}
handlers.add(handler);
computePath();
}
private void registerChildChain(HandlerChain handlerChain) {
enclosingChains.add(new WeakReference<HandlerChain>((handlerChain)));
}
private void computePath() {
lifeCycleChain.clear();
connectHandlerChain.clear();
isOnConnectPathMultithreaded = false;
dataHandlerChain.clear();
isOnDataPathMultithreaded = false;
disconnectHandlerChain.clear();
isOnDisconnectPathMultithreaded = false;
idleTimeoutHandlerChain.clear();
isOnIdleTimeoutPathMultithreaded = false;
connectionTimeoutHandlerChain.clear();
isOnConnectionTimeoutPathMultithreaded = false;
isUnsynchronized = true;
for (IHandler handler : handlers) {
IHandlerInfo handlerInfo = ConnectionUtils.getHandlerInfo(handler);
isUnsynchronized = isUnsynchronized && handlerInfo.isUnsynchronized();
if (handlerInfo.isLifeCycle()) {
lifeCycleChain.add((ILifeCycle) handler);
}
// nested chain?
if (handler instanceof HandlerChain) {
IHandlerInfo nestedInfo = ((HandlerChain) handler).getHandlerInfo();
isOnConnectPathMultithreaded = isOnConnectPathMultithreaded || nestedInfo.isConnectHandlerMultithreaded();
isOnDataPathMultithreaded = isOnDataPathMultithreaded || nestedInfo.isDataHandlerMultithreaded();
isOnDisconnectPathMultithreaded = isOnDisconnectPathMultithreaded || nestedInfo.isDisconnectHandlerMultithreaded();
isOnIdleTimeoutPathMultithreaded = isOnIdleTimeoutPathMultithreaded || nestedInfo.isIdleTimeoutHandlerMultithreaded();
isOnConnectionTimeoutPathMultithreaded = isOnConnectionTimeoutPathMultithreaded || nestedInfo.isConnectionTimeoutHandlerMultithreaded();
dataHandlerChain.add((IDataHandler) handler);
disconnectHandlerChain.add((IDisconnectHandler) handler);
idleTimeoutHandlerChain.add((IIdleTimeoutHandler) handler);
connectionTimeoutHandlerChain.add((IConnectionTimeoutHandler) handler);
// ... no
} else {
if (handlerInfo.isConnectHandler()) {
connectHandlerChain.add((IConnectHandler) handler);
isOnConnectPathMultithreaded = isOnConnectPathMultithreaded || handlerInfo.isConnectHandlerMultithreaded();
}
if (handlerInfo.isDataHandler()) {
dataHandlerChain.add((IDataHandler) handler);
isOnDataPathMultithreaded = isOnDataPathMultithreaded || handlerInfo.isDataHandlerMultithreaded();
}
if (handlerInfo.isDisconnectHandler()) {
disconnectHandlerChain.add((IDisconnectHandler) handler);
isOnDisconnectPathMultithreaded = isOnDisconnectPathMultithreaded || handlerInfo.isDisconnectHandlerMultithreaded();
}
if (handlerInfo.isIdleTimeoutHandler()) {
idleTimeoutHandlerChain.add((IIdleTimeoutHandler) handler);
isOnIdleTimeoutPathMultithreaded = isOnIdleTimeoutPathMultithreaded || handlerInfo.isIdleTimeoutHandlerMultithreaded();
}
if (handlerInfo.isConnectionTimeoutHandler()) {
connectionTimeoutHandlerChain.add((IConnectionTimeoutHandler) handler);
isOnConnectionTimeoutPathMultithreaded = isOnConnectionTimeoutPathMultithreaded || handlerInfo.isConnectionTimeoutHandlerMultithreaded();
}
}
}
for (WeakReference<HandlerChain> handlerChainRef : enclosingChains) {
HandlerChain handlerChain = handlerChainRef.get();
if (handlerChain != null) {
handlerChain.computePath();
}
}
}
/**
* {@inheritDoc}
*/
public boolean onConnect(final INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (connectHandlerChain.isEmpty()) {
return false;
}
for (IConnectHandler connectHandler : connectHandlerChain) {
boolean result = connectHandler.onConnect(connection);
if (result == true) {
return true;
}
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean onData(final INonBlockingConnection connection) throws IOException {
if (dataHandlerChain.isEmpty()) {
return false;
}
for (IDataHandler dataHandler : dataHandlerChain) {
boolean result = dataHandler.onData(connection);
if (result == true) {
return true;
}
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean onDisconnect(final INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (disconnectHandlerChain.isEmpty()) {
return false;
}
for (IDisconnectHandler disconnectHandler : disconnectHandlerChain) {
boolean result = disconnectHandler.onDisconnect(connection);
if (result == true) {
return true;
}
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean onIdleTimeout(final INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (idleTimeoutHandlerChain.isEmpty()) {
return false;
}
for (IIdleTimeoutHandler idleTimeoutHandler : idleTimeoutHandlerChain) {
boolean result = idleTimeoutHandler.onIdleTimeout(connection);
if (result == true) {
return true;
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because idle timeout has been occured and timeout handler returns true)");
}
connection.close();
return true;
}
/**
* {@inheritDoc}
*/
public boolean onConnectionTimeout(final INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (connectionTimeoutHandlerChain.isEmpty()) {
return false;
}
for (IConnectionTimeoutHandler connectionTimeoutHandler : connectionTimeoutHandlerChain) {
boolean result = connectionTimeoutHandler.onConnectionTimeout(connection);
if (result == true) {
return true;
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because coonection timeout has been occured and timeout handler returns true)");
}
connection.close();
return true;
}
private class HandlerInfo implements IHandlerInfo {
public boolean isConnectionScoped() {
return false;
}
public boolean isConnectExceptionHandler() {
return false;
}
public boolean isConnectExceptionHandlerMultithreaded() {
return false;
}
public boolean isConnectHandler() {
return true;
}
public boolean isConnectHandlerMultithreaded() {
return isOnConnectionTimeoutPathMultithreaded;
}
public boolean isConnectionTimeoutHandler() {
return true;
}
public boolean isConnectionTimeoutHandlerMultithreaded() {
return isOnConnectionTimeoutPathMultithreaded;
}
public boolean isDataHandler() {
return true;
}
public boolean isDataHandlerMultithreaded() {
return isOnDataPathMultithreaded;
}
public boolean isDisconnectHandler() {
return true;
}
public boolean isDisconnectHandlerMultithreaded() {
return isOnDisconnectPathMultithreaded;
}
public boolean isIdleTimeoutHandler() {
return true;
}
public boolean isIdleTimeoutHandlerMultithreaded() {
return isOnIdleTimeoutPathMultithreaded;
}
public boolean isLifeCycle() {
return true;
}
public boolean isUnsynchronized() {
return isUnsynchronized;
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/HandlerChain.java | Java | art | 13,471 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* monitored selector
*
* @author grro@xsocket.org
*/
abstract class MonitoredSelector {
private static final Logger LOG = Logger.getLogger(MonitoredSelector.class.getName());
private static final boolean IS_LOOPING_CHECK_ACTIVATED = Boolean.parseBoolean(System.getProperty("org.xsocket.connection.selector.looping.check", "true"));
private static final boolean IS_REINIT_ACTIVATED = Boolean.parseBoolean(System.getProperty("org.xsocket.connection.selector.looping.reinit", "true"));
private static final long LOG_PERIOD_MILLIS = 5 * 1000;
private static final int LOOPING_DETECTED_WAIT_TIME_MILLIS = 100;
private static final int ZERO_COUNTER_THRESHOLD = 100;
private static final int ZERO_COUNTER_TIME_THRESHOLD_MILLIS = 100;
private int zeroCounter = 0;
private long lastTimeEventCountIsZero = 0;
private long lastTimeSpinningLog = 0;
final protected void checkForLooping(int eventCount) {
checkForLooping(eventCount, 0);
}
final protected void checkForLooping(int eventCount, long lastTimeWokeUpManually) {
if (IS_LOOPING_CHECK_ACTIVATED) {
if (eventCount == 0) {
zeroCounter++;
if (zeroCounter == 1) {
lastTimeEventCountIsZero = System.currentTimeMillis();
return;
} else {
// zero count threshold reached?
if (zeroCounter > ZERO_COUNTER_THRESHOLD) {
long current = System.currentTimeMillis();
// threashold within time period?
if ((current < (lastTimeEventCountIsZero + ZERO_COUNTER_TIME_THRESHOLD_MILLIS)) &&
(current < (lastTimeWokeUpManually + ZERO_COUNTER_TIME_THRESHOLD_MILLIS))) {
if (current > (lastTimeSpinningLog + LOG_PERIOD_MILLIS)) {
lastTimeSpinningLog = current;
LOG.warning("looping selector? (" + getNumRegisteredHandles() + " keys)\r\n" + printRegistered());
}
if (IS_REINIT_ACTIVATED) {
try {
reinit();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("could not re-init selector " + ioe.toString());
}
}
}
try {
Thread.sleep(LOOPING_DETECTED_WAIT_TIME_MILLIS);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
zeroCounter = 0;
}
}
} else {
zeroCounter = 0;
}
}
}
abstract int getNumRegisteredHandles();
abstract String printRegistered();
abstract void reinit() throws IOException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/MonitoredSelector.java | Java | art | 4,785 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.xsocket.DataConverter;
import org.xsocket.connection.AbstractNonBlockingStream.ISink;
/**
* the WriteQueue
*
* @author grro
*/
final class WriteQueue implements Cloneable {
// queue
private final Queue queue = new Queue();
// mark support
private RewriteableBuffer writeMarkBuffer = null;
private boolean isWriteMarked = false;
public void reset() {
queue.reset();
writeMarkBuffer = null;
isWriteMarked = false;
}
/**
* returns true, if empty
*
* @return true, if empty
*/
public boolean isEmpty() {
return queue.isEmpty() && (writeMarkBuffer == null);
}
/**
* return the current size
*
* @return the current size
*/
public int getSize() {
int size = queue.getSize();
if (writeMarkBuffer != null) {
size += writeMarkBuffer.size();
}
return size;
}
/**
* drain the queue
*
* @return the queue content
*/
public ByteBuffer[] drain() {
return queue.drain();
}
/**
* append a byte buffer to this queue.
*
* @param data the ByteBuffer to append
*/
public void append(ByteBuffer data) {
if (data == null) {
return;
}
if (isWriteMarked) {
writeMarkBuffer.append(data);
} else {
queue.append(data);
}
}
/**
* append a list of byte buffer to this queue. By adding a list,
* the list becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the list of ByteBuffer
*/
public void append(ByteBuffer[] bufs) {
if (bufs == null) {
return;
}
if (bufs.length < 1) {
return;
}
if (isWriteMarked) {
for (ByteBuffer buffer : bufs) {
writeMarkBuffer.append(buffer);
}
} else {
queue.append(bufs);
}
}
/**
* mark the current write position
*/
public void markWritePosition() {
removeWriteMark();
isWriteMarked = true;
writeMarkBuffer = new RewriteableBuffer();
}
/**
* remove write mark
*/
public void removeWriteMark() {
if (isWriteMarked) {
isWriteMarked = false;
append(writeMarkBuffer.drain());
writeMarkBuffer = null;
}
}
/**
* reset the write position the the saved mark
*
* @return true, if the write position has been marked
*/
public boolean resetToWriteMark() {
if (isWriteMarked) {
writeMarkBuffer.resetWritePosition();
return true;
} else {
return false;
}
}
@Override
protected Object clone() throws CloneNotSupportedException {
WriteQueue copy = new WriteQueue();
copy.queue.append(this.queue.copy());
if (this.writeMarkBuffer != null) {
copy.writeMarkBuffer = (RewriteableBuffer) this.writeMarkBuffer.clone();
}
return copy;
}
/**
* {@inheritDoc}
*/
public String toString(String encoding) {
return queue.toString(encoding);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return queue.toString();
}
private static final class RewriteableBuffer implements Cloneable {
private ArrayList<ByteBuffer> bufs = new ArrayList<ByteBuffer>();
private int writePosition = 0;
public void append(ByteBuffer buffer) {
if (buffer.remaining() < 1) {
return;
}
if (writePosition == bufs.size()) {
bufs.add(buffer);
writePosition++;
} else {
ByteBuffer currentBuffer = bufs.remove(writePosition);
if (currentBuffer.remaining() == buffer.remaining()) {
bufs.add(writePosition, buffer);
writePosition++;
} else if (currentBuffer.remaining() > buffer.remaining()) {
currentBuffer.position(currentBuffer.position() + buffer.remaining());
bufs.add(writePosition, currentBuffer);
bufs.add(writePosition, buffer);
writePosition++;
} else { // currentBuffer.remaining() < buffer.remaining()
bufs.add(writePosition, buffer);
writePosition++;
int bytesToRemove = buffer.remaining() - currentBuffer.remaining();
while (bytesToRemove > 0) {
// does tailing buffers exits?
if (writePosition < bufs.size()) {
ByteBuffer buf = bufs.remove(writePosition);
if (buf.remaining() > bytesToRemove) {
buf.position(buf.position() + bytesToRemove);
bufs.add(writePosition, buf);
} else {
bytesToRemove -= buf.remaining();
}
// ...no
} else {
bytesToRemove = 0;
}
}
}
}
}
public void resetWritePosition() {
writePosition = 0;
}
public ByteBuffer[] drain() {
ByteBuffer[] result = bufs.toArray(new ByteBuffer[bufs.size()]);
bufs.clear();
writePosition = 0;
return result;
}
public int size() {
int size = 0;
for (ByteBuffer buffer : bufs) {
size += buffer.remaining();
}
return size;
}
@Override
protected Object clone() throws CloneNotSupportedException {
RewriteableBuffer copy = (RewriteableBuffer) super.clone();
copy.bufs = new ArrayList<ByteBuffer>();
for (ByteBuffer buffer : this.bufs) {
copy.bufs.add(buffer.duplicate());
}
return copy;
}
}
private static final class Queue implements ISink {
private ByteBuffer[] buffers;
/**
* clean the queue
*/
public synchronized void reset() {
buffers = null;
}
/**
* returns true, if empty
*
* @return true, if empty
*/
public synchronized boolean isEmpty() {
return empty();
}
private boolean empty() {
return (buffers == null);
}
/**
* return the current size
*
* @return the current size
*/
public synchronized int getSize() {
if (empty()) {
return 0;
} else {
int size = 0;
if (buffers != null) {
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] != null) {
size += buffers[i].remaining();
}
}
}
return size;
}
}
public synchronized void append(ByteBuffer data) {
if (buffers == null) {
buffers = new ByteBuffer[1];
buffers[0] = data;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + 1];
System.arraycopy(buffers, 0, newBuffers, 0, buffers.length);
newBuffers[buffers.length] = data;
buffers = newBuffers;
}
}
/**
* append a list of byte buffer to this queue. By adding a list,
* the list becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the list of ByteBuffer
*/
public synchronized void append(ByteBuffer[] bufs) {
if (buffers == null) {
buffers = bufs;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + bufs.length];
System.arraycopy(buffers, 0, newBuffers, 0, buffers.length);
System.arraycopy(bufs, 0, newBuffers, buffers.length, bufs.length);
buffers = newBuffers;
}
}
/**
* drain the queue
*
* @return the queue content
*/
public synchronized ByteBuffer[] drain() {
ByteBuffer[] result = buffers;
buffers = null;
return result;
}
public synchronized ByteBuffer[] copy() {
return ConnectionUtils.copy(buffers);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return toString("US-ASCII");
}
/**
* {@inheritDoc}
*/
public synchronized String toString(String encoding) {
StringBuilder sb = new StringBuilder();
if (buffers != null) {
ByteBuffer[] copy = new ByteBuffer[buffers.length];
try {
for (int i = 0; i < copy.length; i++) {
if (buffers[i] != null) {
copy[i] = buffers[i].duplicate();
}
}
sb.append(DataConverter.toString(copy, encoding, Integer.MAX_VALUE));
} catch (UnsupportedEncodingException use) {
sb.append(DataConverter.toHexString(copy, Integer.MAX_VALUE));
}
}
return sb.toString();
}
}
} | zzh-simple-hr | Zxsocket/src/org/xsocket/connection/WriteQueue.java | Java | art | 9,507 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import org.xsocket.ILifeCycle;
/**
* Listener interface, which defines specific callback methods for a {@link IServer}
*
* @author grro@xsocket.org
*/
public interface IServerListener extends ILifeCycle {
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IServerListener.java | Java | art | 1,273 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.nio.channels.ClosedChannelException;
/**
* ClosedChannelException
*
* @author grro@xsocket.org
*/
final class ExtendedClosedChannelException extends ClosedChannelException {
private static final long serialVersionUID = -144048533396123717L;
private final String msg;
public ExtendedClosedChannelException(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return msg;
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/ExtendedClosedChannelException.java | Java | art | 1,492 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import org.xsocket.MaxReadSizeExceededException;
/**
* Thread-safe wrapper of a BlockingConnection
*
* @author grro@xsocket.org
*/
final class SynchronizedBlockingConnection extends AbstractSynchronizedConnection implements IBlockingConnection {
private final IBlockingConnection delegate;
public SynchronizedBlockingConnection(IBlockingConnection delegate) {
super(delegate);
this.delegate = delegate;
}
public void activateSecuredMode() throws IOException {
synchronized(delegate) {
delegate.activateSecuredMode();
}
}
public void deactivateSecuredMode() throws IOException {
synchronized(delegate) {
delegate.deactivateSecuredMode();
}
}
public void flush() throws ClosedChannelException, IOException, SocketTimeoutException {
synchronized(delegate) {
delegate.flush();
}
}
public String getEncoding() {
synchronized(delegate) {
return delegate.getEncoding();
}
}
public FlushMode getFlushmode() {
synchronized(delegate) {
return delegate.getFlushmode();
}
}
public int getMaxReadBufferThreshold() {
synchronized(delegate) {
return delegate.getMaxReadBufferThreshold();
}
}
public int getPendingWriteDataSize() {
synchronized(delegate) {
return delegate.getPendingWriteDataSize();
}
}
public int getReadTimeoutMillis() throws IOException {
synchronized(delegate) {
return delegate.getReadTimeoutMillis();
}
}
public boolean isAutoflush() {
synchronized(delegate) {
return delegate.isAutoflush();
}
}
public boolean isReceivingSuspended() {
synchronized(delegate) {
return delegate.isReceivingSuspended();
}
}
public boolean isSecure() {
synchronized(delegate) {
return delegate.isSecure();
}
}
public void markReadPosition() {
synchronized(delegate) {
delegate.markReadPosition();
}
}
public void markWritePosition() {
synchronized(delegate) {
delegate.markWritePosition();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, SocketTimeoutException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter, encoding);
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, SocketTimeoutException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter, encoding, maxLength);
}
}
public byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter, encoding);
}
}
public byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException, SocketTimeoutException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter, encoding, maxLength);
}
}
public String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter, encoding);
}
}
public String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter, encoding, maxLength);
}
}
public String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, SocketTimeoutException {
synchronized(delegate) {
return delegate.readStringByLength(length, encoding);
}
}
public void removeReadMark() {
synchronized(delegate) {
delegate.removeReadMark();
}
}
public void removeWriteMark() {
synchronized(delegate) {
delegate.removeWriteMark();
}
}
public boolean resetToReadMark() {
synchronized(delegate) {
return delegate.resetToReadMark();
}
}
public boolean resetToWriteMark() {
synchronized(delegate) {
return delegate.resetToWriteMark();
}
}
public void resumeReceiving() throws IOException {
synchronized(delegate) {
delegate.resumeReceiving();
}
}
public void setAutoflush(boolean autoflush) {
synchronized(delegate) {
delegate.setAutoflush(autoflush);
}
}
public void setEncoding(String encoding) {
synchronized(delegate) {
delegate.setEncoding(encoding);
}
}
public void setFlushmode(FlushMode flushMode) {
synchronized(delegate) {
delegate.setFlushmode(flushMode);
}
}
public void setMaxReadBufferThreshold(int size) {
synchronized(delegate) {
delegate.setMaxReadBufferThreshold(size);
}
}
public void setReadTimeoutMillis(int timeout) throws IOException {
synchronized(delegate) {
delegate.setReadTimeoutMillis(timeout);
}
}
public void suspendReceiving() throws IOException {
synchronized(delegate) {
delegate.suspendReceiving();
}
}
public long transferFrom(FileChannel source) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.transferFrom(source);
}
}
public void unread(ByteBuffer[] buffers) throws IOException {
synchronized(delegate) {
delegate.unread(buffers);
}
}
public void unread(ByteBuffer buffer) throws IOException {
synchronized(delegate) {
delegate.unread(buffer);
}
}
public void unread(byte[] bytes) throws IOException {
synchronized(delegate) {
delegate.unread(bytes);
}
}
public void unread(String text) throws IOException {
synchronized(delegate) {
delegate.unread(text);
}
}
public int write(String message, String encoding) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(message, encoding);
}
}
public void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(buffers, writeCompletionHandler);
}
}
public void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(buffer, writeCompletionHandler);
}
}
public void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(buffers, writeCompletionHandler);
}
}
public void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(srcs, offset, length);
}
}
public void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(bytes, writeCompletionHandler);
}
}
public void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(bytes, offset, length, writeCompletionHandler);
}
}
public void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(message, encoding, writeCompletionHandler);
}
}
public int read(ByteBuffer buffer) throws IOException {
synchronized(delegate) {
return delegate.read(buffer);
}
}
public byte readByte() throws IOException {
synchronized(delegate) {
return delegate.readByte();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter) throws IOException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter);
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, int maxLength) throws IOException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter, maxLength);
}
}
public ByteBuffer[] readByteBufferByLength(int length) throws IOException {
synchronized(delegate) {
return delegate.readByteBufferByLength(length);
}
}
public byte[] readBytesByDelimiter(String delimiter) throws IOException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter);
}
}
public byte[] readBytesByDelimiter(String delimiter, int maxLength) throws IOException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter, maxLength);
}
}
public byte[] readBytesByLength(int length) throws IOException {
synchronized(delegate) {
return delegate.readBytesByLength(length);
}
}
public double readDouble() throws IOException {
synchronized(delegate) {
return delegate.readDouble();
}
}
public int readInt() throws IOException {
synchronized(delegate) {
return delegate.readInt();
}
}
public long readLong() throws IOException {
synchronized(delegate) {
return delegate.readLong();
}
}
public short readShort() throws IOException {
synchronized(delegate) {
return delegate.readShort();
}
}
public String readStringByDelimiter(String delimiter) throws IOException, UnsupportedEncodingException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter);
}
}
public String readStringByDelimiter(String delimiter, int maxLength) throws IOException, UnsupportedEncodingException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter, maxLength);
}
}
public String readStringByLength(int length) throws IOException, BufferUnderflowException {
synchronized(delegate) {
return delegate.readStringByLength(length);
}
}
public long transferTo(WritableByteChannel target, int length) throws IOException, ClosedChannelException {
synchronized(delegate) {
return delegate.transferTo(target, length);
}
}
public long transferFrom(ReadableByteChannel source) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.transferFrom(source);
}
}
public long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.transferFrom(source, chunkSize);
}
}
public int write(byte b) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(b);
}
}
public int write(byte... bytes) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(bytes);
}
}
public int write(byte[] bytes, int offset, int length) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(bytes, offset, length);
}
}
public int write(ByteBuffer buffer) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(buffer);
}
}
public long write(ByteBuffer[] buffers) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(buffers);
}
}
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
synchronized(delegate) {
return delegate.write(srcs, offset, length);
}
}
public long write(List<ByteBuffer> buffers) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(buffers);
}
}
public int write(int i) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(i);
}
}
public int write(short s) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(s);
}
}
public int write(long l) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(l);
}
}
public int write(double d) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(d);
}
}
public int write(String message) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(message);
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/SynchronizedBlockingConnection.java | Java | art | 16,947 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.xsocket.DataConverter;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.SerializedTaskQueue;
import org.xsocket.connection.ConnectionManager.TimeoutMgmHandle;
import org.xsocket.connection.ConnectionUtils.CompletionHandlerInfo;
/**
* Implementation of the <code>INonBlockingConnection</code> interface. <br><br>
*
* Depending on the constructor parameter waitForConnect a newly created connection is in the open state.
* Write or read methods can be called immediately.
* Absence of the waitForConnect parameter is equals to waitForConnect==true.
*
* <br><br><b>The methods of this class are not thread-safe.</b>
*
* @author grro@xsocket.org
*/
public final class NonBlockingConnection extends AbstractNonBlockingStream implements INonBlockingConnection {
private static final Logger LOG = Logger.getLogger(NonBlockingConnection.class.getName());
public static final String SEND_TIMEOUT_KEY = "org.xsocket.connection.sendFlushTimeoutMillis";
public static final long DEFAULT_SEND_TIMEOUT_MILLIS = 60L * 1000L;
private static final boolean IS_SUPPRESS_SYNC_FLUSH_WARNING = IoProvider.getSuppressSyncFlushWarning();
private static final boolean IS_SUPPRESS_SYNC_FLUSH_COMPLITIONHANDLER_WARNING = IoProvider.getSuppressSyncFlushCompletionHandlerWarning();
private static Executor defaultWorkerPool;
private static IoConnector defaultConnector;
private static long sendTimeoutMillis = DEFAULT_SEND_TIMEOUT_MILLIS;
static {
try {
sendTimeoutMillis = Long.valueOf(System.getProperty(SEND_TIMEOUT_KEY, Long.toString(DEFAULT_SEND_TIMEOUT_MILLIS)));
} catch (Exception e) {
LOG.warning("invalid value for system property " + SEND_TIMEOUT_KEY + ": "
+ System.getProperty(SEND_TIMEOUT_KEY) + " (valid is a int value)"
+ " using default");
sendTimeoutMillis = DEFAULT_SEND_TIMEOUT_MILLIS;
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("non blocking connection send time out set with " + DataConverter.toFormatedDuration(sendTimeoutMillis));
}
}
private final boolean isServerSide;
// flags
private final AtomicBoolean isOpen = new AtomicBoolean(true);
private final AtomicBoolean isConnected = new AtomicBoolean(false);
private final AtomicBoolean isSuspended = new AtomicBoolean(false);
private final Object disconnectedGuard = false;
private final AtomicBoolean isDisconnected = new AtomicBoolean(false);
// connection manager
private static final ConnectionManager DEFAULT_CONNECTION_MANAGER = new ConnectionManager();
private TimeoutMgmHandle timeoutMgmHandle;
// io handler
private final IoHandlerCallback ioHandlerCallback = new IoHandlerCallback();
private IoChainableHandler ioHandler;
// app handler
private final AtomicReference<HandlerAdapter> handlerAdapterRef = new AtomicReference<HandlerAdapter>(null);
private final AtomicReference<IHandlerChangeListener> handlerReplaceListenerRef = new AtomicReference<IHandlerChangeListener>();
// execution
private Executor workerpool;
// task Queue
private final SerializedTaskQueue taskQueue = new SerializedTaskQueue();
// write transfer rate
private int bytesPerSecond = UNLIMITED;
// sync write support
private final SynchronWriter synchronWriter = new SynchronWriter();
// write thread handling
private final WriteCompletionManager writeCompletionManager = new WriteCompletionManager();
private final Object asyncWriteGuard = new Object();
// timeout support
private long idleTimeoutMillis = IConnection.MAX_TIMEOUT_MILLIS;
private long idleTimeoutDateMillis = Long.MAX_VALUE;
private long connectionTimeoutMillis = IConnection.MAX_TIMEOUT_MILLIS;
private long connectionTimeoutDateMillis = Long.MAX_VALUE;
private final AtomicBoolean idleTimeoutOccured = new AtomicBoolean(false);
private final AtomicBoolean connectionTimeoutOccured = new AtomicBoolean(false);
private final AtomicBoolean connectExceptionOccured = new AtomicBoolean(false);
// private final AtomicBoolean disconnectOccured = new AtomicBoolean(false);
// cached values
private Integer cachedSoSndBuf;
// max app buffer size
private final Object suspendGuard = new Object();
private Integer maxReadBufferSize;
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param hostname the remote host
* @param port the port of the remote host to connect
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(String hostname, int port) throws IOException {
this(InetAddress.getByName(hostname), port);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
* @param address the remote host
* @param port the port of the remote host to connect
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
* @param address the remote host address
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetSocketAddress address) throws IOException {
this(address, true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
* @param address the remote host
* @param port the port of the remote host to connect
* @param connectTimeoutMillis the timeout of the connect procedure
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, int connectTimeoutMillis) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, new HashMap<String, Object>(), null, false, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
* @param address the remote host
* @param port the port of the remote host to connect
* @param options the socket options
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, Map<String, Object> options) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, options, null, false, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
* @param address the remote host
* @param port the port of the remote host to connect
* @param connectTimeoutMillis the timeout of the connect procedure
* @param options the socket options
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, int connectTimeoutMillis, Map<String, Object> options) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, options, null, false, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param attachment the attacjment or <null>
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, Object attachment) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), attachment);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param connectTimeoutMillis the timeout of the connect procedure
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param waitForConnect true, if the constructor should block until the connection is established. If the connect fails, the handler's onData and onDisconnect method will be called (if present)
* @param connectTimeoutMillis the timeout of the connect procedure
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis) throws IOException {
this(new InetSocketAddress(address, port), waitForConnect, connectTimeoutMillis, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param sslContext the ssl context
* @param sslOn true, if ssl should be activated
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), sslContext, sslOn, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param sslContext the ssl context
* @param sslOn true, if ssl should be activated
* @param connectTimeoutMillis the timeout of the connect procedure
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, new HashMap<String, Object>(), sslContext, sslOn, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param sslContext the ssl context
* @param sslOn true, if ssl should be activated
* @param waitForConnect true, if the constructor should block until the connection is established. If the connect fails, the handler's onData and onDisconnect method will be called (if present)
* @param connectTimeoutMillis the timeout of the connect procedure
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(address, port), waitForConnect, connectTimeoutMillis, new HashMap<String, Object>(), sslContext, sslOn, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param options the socket options
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, Map<String, Object> options) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, options, null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param connectTimeoutMillis the timeout of the connect procedure
* @param options the socket options
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis, Map<String, Object> options) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, options, null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param waitForConnect true, if the constructor should block until the connection is established. If the connect fails, the handler's onData and onDisconnect method will be called (if present)
* @param connectTimeoutMillis the timeout of the connect procedure
* @param options the socket options
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis, Map<String, Object> options) throws IOException {
this(new InetSocketAddress(address, port), waitForConnect, connectTimeoutMillis, options, null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor <br><br>
*
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param hostname the remote host
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(String hostname, int port, IHandler appHandler) throws IOException {
this(new InetSocketAddress(hostname, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor <br><br>
*
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param hostname the remote host
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param workerPool the worker pool to use
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(String hostname, int port, IHandler appHandler, Executor workerPool) throws IOException {
this(new InetSocketAddress(hostname, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, workerPool, null);
}
/**
* constructor <br><br>
*
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
*
* @param hostname the remote host
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param options the socket options
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(String hostname, int port, IHandler appHandler, Map<String, Object> options) throws IOException {
this(new InetSocketAddress(hostname, port), true, Integer.MAX_VALUE, options, null, false, appHandler, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), sslContext, sslOn, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param options the socket options
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, options, sslContext, sslOn, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
* @param hostname the remote host
* @param port the remote port
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(String hostname, int port, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(hostname, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), sslContext, sslOn, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection.<br><br>
*
*
*
* @param hostname the remote host
* @param port the remote port
* @param options the socket options
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(String hostname, int port, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException {
this(new InetSocketAddress(hostname, port), true, Integer.MAX_VALUE, options, sslContext, sslOn, null, getDefaultWorkerpool(), null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param workerPool the worker pool to use
* @throws IOException If some other I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, Executor workerPool) throws IOException {
this(new InetSocketAddress(address, port), true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, workerPool, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param connectTimeoutMillis the timeout of the connect procedure
* @param workerPool the worker pool to use
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis, Executor workerPool) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, new HashMap<String, Object>(), null, false, appHandler, workerPool, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param waitForConnect true, if the constructor should block until the connection is established. If the connect fails, the handler's onData and onDisconnect method will be called (if present)
* @param connectTimeoutMillis the timeout of the connect procedure
* @param workerPool the worker pool to use
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis, Executor workerPool) throws IOException {
this(new InetSocketAddress(address, port), waitForConnect, connectTimeoutMillis, new HashMap<String, Object>(), null, false, appHandler, workerPool, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)r
* @param connectTimeoutMillis the timeout of the connect procedure
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @param workerPool the worker pool to use
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis, SSLContext sslContext, boolean sslOn, Executor workerPool) throws IOException {
this(new InetSocketAddress(address, port), true, connectTimeoutMillis, new HashMap<String, Object>(), sslContext, sslOn, appHandler, workerPool, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)r
* @param waitForConnect true, if the constructor should block until the connection is established. If the connect fails, the handler's onData and onDisconnect method will be called (if present)
* @param connectTimeoutMillis the timeout of the connect procedure
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @param workerPool the worker pool to use
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis, SSLContext sslContext, boolean sslOn, Executor workerPool) throws IOException {
this(new InetSocketAddress(address, port), waitForConnect, connectTimeoutMillis, new HashMap<String, Object>(), sslContext, sslOn, appHandler, workerPool, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param remoteAddress the remote address
* @param localAddress the localAddress
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)r
* @param waitForConnect true, if the constructor should block until the connection is established. If the connect fails, the handler's onData and onDisconnect method will be called (if present)
* @param connectTimeoutMillis the timeout of the connect procedure
* @param options the socket options
* @param sslContext the ssl context to use
* @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()})
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetSocketAddress remoteAddress, InetSocketAddress localAddress, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException {
this(remoteAddress, localAddress, waitForConnect, connectTimeoutMillis, options, sslContext, sslOn, appHandler, getDefaultWorkerpool(), DEFAULT_AUTOFLUSH, DEFAULT_FLUSH_MODE, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param autoflush the auto flush mode
* @param flushmode the flush mode
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean autoflush, FlushMode flushmode) throws IOException {
this(new InetSocketAddress(address, port), null, true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), autoflush, flushmode, null);
}
/**
* constructor. This constructor will be used to create a non blocking
* client-side connection. <br><br>
*
* @param address the remote address
* @param port the remote port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param autoflush the auto flush mode
* @param flushmode the flush mode
* @param attachment the attachment or <null>
* @throws IOException if a I/O error occurs
*/
public NonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean autoflush, FlushMode flushmode, Object attachment) throws IOException {
this(new InetSocketAddress(address, port), null, true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false, appHandler, getDefaultWorkerpool(), autoflush, flushmode, attachment);
}
/**
* intermediate client constructor, which uses a specific dispatcher
*/
NonBlockingConnection(InetSocketAddress remoteAddress, boolean waitForConnect, int connectTimeoutMillis, Map<String, Object> options, SSLContext sslContext, boolean sslOn, IHandler appHandler, Executor workerpool, Object attachment) throws IOException {
this(remoteAddress, null, waitForConnect, connectTimeoutMillis, options, sslContext, sslOn, appHandler, workerpool, DEFAULT_AUTOFLUSH, DEFAULT_FLUSH_MODE, attachment);
}
/**
* client constructor, which uses a specific dispatcher
*/
private NonBlockingConnection(InetSocketAddress remoteAddress, InetSocketAddress localAddress, boolean waitForConnect, int connectTimeoutMillis, final Map<String, Object> options, final SSLContext sslContext, boolean isSecured, IHandler appHdl, Executor workerpool, boolean autoflush, FlushMode flushmode, Object attachment) throws IOException {
setFlushmode(flushmode);
setAutoflush(autoflush);
setWorkerpool(workerpool);
setAttachment(attachment);
handlerAdapterRef.set(HandlerAdapter.newInstance(appHdl));
isServerSide = false;
SocketChannel channel = openSocket(localAddress, options);
IoConnector connector = getDefaultConnector();
// sync connect
if (waitForConnect && (connectTimeoutMillis > 0)) {
SyncIoConnectorCallback callback = new SyncIoConnectorCallback(remoteAddress, channel, sslContext, isSecured, connectTimeoutMillis);
connector.connectAsync(channel, remoteAddress, connectTimeoutMillis, callback);
callback.connect();
// async connect
} else {
IIoConnectorCallback callback = new AsyncIoConnectorCallback(remoteAddress, channel, sslContext, isSecured, connectTimeoutMillis);
connector.connectAsync(channel, remoteAddress, connectTimeoutMillis, callback);
}
}
private final class SyncIoConnectorCallback implements IIoConnectorCallback, IIoHandlerCallback {
private final AtomicBoolean isConnected = new AtomicBoolean(false);
private final InetSocketAddress remoteAddress;
private final SocketChannel channel;
private final SSLContext sslContext;
private final boolean isSecured;
private final long connectTimeoutMillis;
private boolean isOperationClosed = false;
private IOException ioe = null;
public SyncIoConnectorCallback(InetSocketAddress remoteAddress, SocketChannel channel, SSLContext sslContext, boolean isSecured, long connectTimeoutMillis) {
this.remoteAddress = remoteAddress;
this.channel = channel;
this.sslContext = sslContext;
this.isSecured = isSecured;
this.connectTimeoutMillis = connectTimeoutMillis;
}
void connect() throws IOException {
synchronized (this) {
while (!isOperationClosed) {
try {
wait(500);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
}
if (ioe != null) {
throw ioe;
}
}
private void notifyWaiting() {
synchronized (this) {
isOperationClosed = true;
this.notifyAll();
}
}
////////////////////////////////////
// IIoConnectorCallback methods
public void onConnectionEstablished() throws IOException {
assert (ConnectionUtils.isConnectorThread());
register(channel, sslContext, isSecured, this);
}
public void onConnectError(IOException ioe) {
this.ioe = ioe;
NonBlockingConnection.this.onConnectException(ioe);
notifyWaiting();
}
public void onConnectTimeout() {
this.ioe = new SocketTimeoutException("connect timeout " + DataConverter.toFormatedDuration(connectTimeoutMillis) + " occured by connecting " + remoteAddress);
NonBlockingConnection.this.onConnectException(ioe);
notifyWaiting();
}
////////////////
// IIoHandlerCallback methods
public void onConnect() {
if (!isConnected.getAndSet(true)) {
// assign the native callback handler
ioHandler.setPreviousCallback(ioHandlerCallback);
notifyWaiting();
ioHandlerCallback.onConnect();
}
}
public void onConnectException(IOException ioe) {
ioHandlerCallback.onConnectException(ioe);
}
public void onConnectionAbnormalTerminated() {
ioHandlerCallback.onConnectionAbnormalTerminated();
}
public void onData(ByteBuffer[] data, int size) {
ioHandlerCallback.onData(data, size);
}
public void onPostData() {
ioHandlerCallback.onPostData();
}
public void onWritten(ByteBuffer data) {
ioHandlerCallback.onWritten(data);
}
public void onWriteException(IOException ioException, ByteBuffer data) {
ioHandlerCallback.onWriteException(ioException, data);
}
public void onDisconnect() {
ioHandlerCallback.onDisconnect();
}
}
private final class AsyncIoConnectorCallback implements IIoConnectorCallback {
private final InetSocketAddress remoteAddress;
private final SocketChannel channel;
private final SSLContext sslContext;
private final boolean isSecured;
private final long connectTimeoutMillis;
public AsyncIoConnectorCallback(InetSocketAddress remoteAddress, SocketChannel channel, SSLContext sslContext, boolean isSecured, long connectTimeoutMillis) {
this.remoteAddress = remoteAddress;
this.channel = channel;
this.sslContext = sslContext;
this.isSecured = isSecured;
this.connectTimeoutMillis = connectTimeoutMillis;
}
public void onConnectionEstablished() throws IOException {
register(channel, sslContext, isSecured, ioHandlerCallback);
}
public void onConnectError(IOException ioe) {
onConnectException(ioe);
}
public void onConnectTimeout() {
onConnectException(new SocketTimeoutException("connect timeout " + DataConverter.toFormatedDuration(connectTimeoutMillis) + " occured by connecting " + remoteAddress));
}
}
/**
* server-side constructor
*/
protected NonBlockingConnection(ConnectionManager connectionManager, HandlerAdapter hdlAdapter) throws IOException {
handlerAdapterRef.set(hdlAdapter);
isServerSide = true;
isConnected.set(true);
timeoutMgmHandle = connectionManager.register(this);
}
/**
* will be used for client-side connections only
*/
private void register(SocketChannel channel, SSLContext sslContext, boolean isSecured, IIoHandlerCallback handleCallback) throws IOException, SocketTimeoutException {
IoChainableHandler ioHdl = createClientIoHandler(channel, sslContext, isSecured);
timeoutMgmHandle = DEFAULT_CONNECTION_MANAGER.register(this);
init(ioHdl, handleCallback);
// "true" set of the timeouts
setIdleTimeoutMillis(idleTimeoutMillis);
setConnectionTimeoutMillis(connectionTimeoutMillis);
}
SerializedTaskQueue getTaskQueue() {
return taskQueue;
}
long getLastTimeReceivedMillis() {
return ioHandler.getLastTimeReceivedMillis();
}
long getLastTimeSendMillis() {
return ioHandler.getLastTimeSendMillis();
}
/**
* {@inheritDoc}
*/
public int getMaxReadBufferThreshold() {
if (maxReadBufferSize == null) {
return Integer.MAX_VALUE;
} else {
return maxReadBufferSize;
}
}
/**
* {@inheritDoc}
*/
public void setMaxReadBufferThreshold(int size) {
if (size == Integer.MAX_VALUE) {
maxReadBufferSize = null;
} else {
maxReadBufferSize = size;
}
}
/**
* {@inheritDoc}
*/
/*void setMaxWriteBufferThreshold(int size) {
if (size == Integer.MAX_VALUE) {
maxWriteBufferSize = null;
} else {
maxWriteBufferSize = size;
}
}*/
/**
* returns the default workerpool
*
* @return the default worker pool
*/
synchronized static Executor getDefaultWorkerpool() {
if (defaultWorkerPool == null) {
defaultWorkerPool = Executors.newCachedThreadPool(new DefaultThreadFactory());
}
return defaultWorkerPool;
}
/**
* returns the default connector
*
* @return the default connector
*/
private synchronized static IoConnector getDefaultConnector() {
if (defaultConnector == null) {
defaultConnector = new IoConnector("default");
Thread t = new Thread(defaultConnector);
t.setDaemon(true);
t.start();
}
return defaultConnector;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean isMoreInputDataExpected() {
if (ioHandler != null) {
return ioHandler.isOpen();
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
protected boolean isDataWriteable() {
if (ioHandler != null) {
return ioHandler.isOpen();
} else {
return false;
}
}
void init(IoChainableHandler ioHandler) throws IOException, SocketTimeoutException {
init(ioHandler, ioHandlerCallback);
}
private void init(IoChainableHandler ioHandler, IIoHandlerCallback handlerCallback) throws IOException, SocketTimeoutException {
this.ioHandler = ioHandler;
ioHandler.init(handlerCallback);
isConnected.set(true);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] connection " + getId() + " created. IoHandler: " + ioHandler.toString());
}
}
/**
* {@inheritDoc}
*/
public void setHandler(IHandler hdl) throws IOException {
HandlerAdapter oldHandlerAdapter = handlerAdapterRef.get();
IHandlerChangeListener changeListener = handlerReplaceListenerRef.get();
// call old handler change listener
if ((changeListener != null) && (oldHandlerAdapter != null)) {
IHandler oldHandler = oldHandlerAdapter.getHandler();
changeListener.onHanderReplaced(oldHandler, hdl);
}
boolean isChangeListener = false;
if (hdl != null) {
isChangeListener = (hdl instanceof IHandlerChangeListener);
}
HandlerAdapter adapter = HandlerAdapter.newInstance(hdl);
boolean callDisconnect = false;
synchronized (disconnectedGuard) {
handlerAdapterRef.set(adapter);
if (isChangeListener) {
handlerReplaceListenerRef.set((IHandlerChangeListener) hdl);
}
if (isDisconnected.get()) {
callDisconnect = true;
}
}
// is data available
if (getReadQueueSize() > 0) {
adapter.onData(NonBlockingConnection.this, taskQueue, workerpool, false, false);
}
// is disconnected
if (callDisconnect) {
adapter.onDisconnect(NonBlockingConnection.this, taskQueue, workerpool, false);
}
}
/**
* {@inheritDoc}
*/
public IHandler getHandler() {
HandlerAdapter hdlAdapter = handlerAdapterRef.get();
if (hdlAdapter == null) {
return null;
} else {
return hdlAdapter.getHandler();
}
}
/**
* sets the worker pool
* @param workerpool the worker pool
*/
public void setWorkerpool(Executor workerpool) {
this.workerpool = workerpool;
}
/**
* gets the workerpool
*
* @return the workerpool
*/
public Executor getWorkerpool() {
return workerpool;
}
Executor getExecutor() {
return workerpool;
}
/**
* pool support (the connection- and idle timeout and handler will not be reset)
*
* @return true, if connection has been reset
*/
protected boolean reset() {
try {
if (writeCompletionManager.reset() == false) {
return false;
}
if (getReadQueueSize() > 0){
return false;
}
if (getPendingWriteDataSize() > 0){
return false;
}
if (!synchronWriter.isReusable()){
return false;
}
boolean isReset = ioHandler.reset();
if (!isReset) {
return false;
}
return super.reset();
} catch (Exception e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by reseting connection " + getId() + " " + e.toString());
}
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isOpen() {
if (isDisconnected.get() && (getReadQueueSize() == 0)) {
return false;
}
return isOpen.get();
}
public boolean isServerSide() {
return isServerSide;
}
boolean isConnected() {
return isConnected.get();
}
private void onData(ByteBuffer[] data, int size) {
/**
* if data is received, the data will be appended to the read buffer by
* using the super method appendDataToReadBuffer. Within the super method
* the onPostAppend method of this class will be called, before the
* super method returns.
*
* The onPostAppend method implementation checks if the max read buffer
* size is reached. If this is true, the receiving will be suspended
*
* The caller (e.g. IoSocketHandler) will always perform the onPostData method
* the after calling this method. Within the onPostData the handler's onData
* method will be called
*/
if (data != null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] adding " + size + " to read buffer");
}
appendDataToReadBuffer(data, size);
}
}
@Override
protected void onPostAppend() {
/**
* this method will be called within the I/O thread after the recevied data
* is append to the read buffer. Here it will be check if the max read buffer
* size is reached. If this is true, receiving will be suspended
*
* To avoid race conditions the code is protected by the suspend guard
*/
// auto suspend support?
if (maxReadBufferSize != null) {
// check if receiving has to be suspended
synchronized (suspendGuard) {
if (getReadQueueSize() >= maxReadBufferSize) {
try {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] suspending read, because max read buffers size " + maxReadBufferSize + " is execced (" + getReadQueueSize() + ")");
}
ioHandler.suspendRead();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by suspending read (cause by max read queue size " + maxReadBufferSize + " " + ioe.toString());
}
}
}
}
}
}
@Override
protected ByteBuffer[] onRead(ByteBuffer[] readBufs) throws IOException {
/**
* this method will be called after data is read from the read buffer.
* If the read buffer size lower than the max read buffer size
* the receiving will be resumed (if suspended)
*
* To avoid race conditions the code is protected by the suspend guard
*/
// auto suspend support?
if (maxReadBufferSize != null) {
// check if receiving has to be resumed
synchronized (suspendGuard) {
if (ioHandler.isReadSuspended() && ((getReadQueueSize() < maxReadBufferSize))) {
try {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] resuming read, because read buffer size is lower than max read buffers size " + maxReadBufferSize);
}
if (!isSuspended.get()) {
ioHandler.resumeRead();
}
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by suspending read (cause by max read queue size " + maxReadBufferSize + " " + ioe.toString());
}
}
}
}
}
return readBufs;
}
private void onPostData() {
/**
* This method will be called (by IoSocketHandler) after the onData method
* is called
*/
handlerAdapterRef.get().onData(NonBlockingConnection.this, taskQueue, workerpool, false, false);
}
private void onWritten(ByteBuffer data) {
synchronWriter.onWritten(data);
writeCompletionManager.onWritten(data);
}
private void onWriteException(IOException ioException, ByteBuffer data) {
isOpen.set(false);
synchronWriter.onException(ioException);
writeCompletionManager.onWriteException(ioException, data);
}
private void onConnect() {
try {
handlerAdapterRef.get().onConnect(NonBlockingConnection.this, taskQueue, workerpool, false);
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by performing onConnect callback on " + handlerAdapterRef.get() + " " + ioe.toString());
}
}
}
private void onConnectionAbnormalTerminated() {
forceClose();
}
private void onDisconnect() {
HandlerAdapter adapter = null;
synchronized (disconnectedGuard) {
if (!isDisconnected.getAndSet(true)) {
adapter = handlerAdapterRef.get();
}
}
isConnected.set(false);
TimeoutMgmHandle hdl = timeoutMgmHandle;
if (hdl != null) {
hdl.destroy();
}
if (adapter != null) {
// call first onData
adapter.onData(NonBlockingConnection.this, taskQueue, workerpool, true, false);
// then onDisconnect
adapter.onDisconnect(NonBlockingConnection.this, taskQueue, workerpool, false);
}
}
private void onConnectException(IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("connecting failed " + ioe.toString());
}
if (timeoutMgmHandle != null) {
timeoutMgmHandle.destroy();
}
if (!connectExceptionOccured.getAndSet(true)) {
try {
handlerAdapterRef.get().onConnectException(NonBlockingConnection.this, taskQueue, workerpool, ioe);
} catch (IOException e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by performing onDisconnect callback on " + handlerAdapterRef.get() + " " + e.toString());
}
}
}
}
boolean checkIdleTimeout(Long currentMillis) {
if ((idleTimeoutMillis != IConnection.MAX_TIMEOUT_MILLIS) && (getRemainingMillisToIdleTimeout(currentMillis) <= 0)) {
onIdleTimeout();
return true;
}
return false;
}
void onIdleTimeout() {
if (!idleTimeoutOccured.getAndSet(true)) {
try {
handlerAdapterRef.get().onIdleTimeout(NonBlockingConnection.this, taskQueue, workerpool);
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by performing onIdleTimeout callback on " + handlerAdapterRef.get() + " " + ioe.toString());
}
}
} else {
setIdleTimeoutMillis(IConnection.MAX_TIMEOUT_MILLIS);
}
}
boolean checkConnectionTimeout(Long currentMillis) {
if ((connectionTimeoutMillis != IConnection.MAX_TIMEOUT_MILLIS) && (getRemainingMillisToConnectionTimeout(currentMillis) <= 0)) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] connection timeout occured");
}
onConnectionTimeout();
return true;
}
return false;
}
private void onConnectionTimeout() {
if (!connectionTimeoutOccured.getAndSet(true)) {
try {
handlerAdapterRef.get().onConnectionTimeout(NonBlockingConnection.this, taskQueue, workerpool);
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by performing onConnectionTimeout callback on " + handlerAdapterRef.get() + " " + ioe.toString());
}
}
} else {
setConnectionTimeoutMillis(IConnection.MAX_TIMEOUT_MILLIS);
}
}
/**
* {@inheritDoc}
*/
public long getRemainingMillisToConnectionTimeout() {
return getRemainingMillisToConnectionTimeout(System.currentTimeMillis());
}
/**
* {@inheritDoc}
*/
public long getRemainingMillisToIdleTimeout() {
return getRemainingMillisToIdleTimeout(System.currentTimeMillis());
}
private long getRemainingMillisToConnectionTimeout(long currentMillis) {
return connectionTimeoutDateMillis - currentMillis;
}
public long getNumberOfReceivedBytes() {
return ioHandler.getNumberOfReceivedBytes();
}
public long getNumberOfSendBytes() {
return ioHandler.getNumberOfSendBytes();
}
private long getRemainingMillisToIdleTimeout(long currentMillis) {
long remaining = idleTimeoutDateMillis - currentMillis;
// time out not received
if (remaining > 0) {
return remaining;
// time out received
} else {
// ... but check if meantime data has been received!
return (Math.max(getLastTimeReceivedMillis(), getLastTimeSendMillis()) + idleTimeoutMillis) - currentMillis;
}
}
String getRegisteredOpsInfo() {
return ioHandler.getRegisteredOpsInfo();
}
/**
* {@inheritDoc}
*/
public void setWriteTransferRate(int bytesPerSecond) throws ClosedChannelException, IOException {
if ((bytesPerSecond != UNLIMITED) && ((getFlushmode() != FlushMode.ASYNC))) {
LOG.warning("setWriteTransferRate is only supported for FlushMode ASYNC. Ignore update of the transfer rate");
return;
}
if (this.bytesPerSecond == bytesPerSecond) {
return;
}
this.bytesPerSecond = bytesPerSecond;
ioHandler = ConnectionUtils.getIoProvider().setWriteTransferRate(ioHandler, bytesPerSecond);
}
/**
* {@inheritDoc}
*/
public int getWriteTransferRate() throws ClosedChannelException, IOException {
return bytesPerSecond;
}
/**
* {@inheritDoc}
*/
public boolean isSecuredModeActivateable() {
return ConnectionUtils.getIoProvider().isSecuredModeActivateable(ioHandler);
}
/**
* {@inheritDoc}
*/
public void activateSecuredMode() throws IOException {
boolean isPrestarted = ConnectionUtils.getIoProvider().preActivateSecuredMode(ioHandler);
if (isPrestarted) {
FlushMode currentFlushMode = getFlushmode();
setFlushmode(FlushMode.ASYNC);
internalFlush(null);
setFlushmode(currentFlushMode);
ByteBuffer[] buffer = readByteBufferByLength(available());
ConnectionUtils.getIoProvider().activateSecuredMode(ioHandler, buffer);
}
}
public void deactivateSecuredMode() throws IOException {
FlushMode currentFlushMode = getFlushmode();
setFlushmode(FlushMode.ASYNC);
internalFlush(null);
setFlushmode(currentFlushMode);
ConnectionUtils.getIoProvider().deactivateSecuredMode(ioHandler);
}
/**
* {@inheritDoc}
*/
public boolean isSecure() {
return ioHandler.isSecure();
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
try {
return super.readByteBufferByDelimiter(delimiter, encoding, maxLength);
} catch (MaxReadSizeExceededException mre) {
if (isOpen()) {
throw mre;
} else {
throw new ClosedChannelException();
}
} catch (BufferUnderflowException bue) {
if (isOpen()) {
throw bue;
} else {
throw new ClosedChannelException();
}
}
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByLength(int length) throws IOException, BufferUnderflowException {
try {
return super.readByteBufferByLength(length);
} catch (BufferUnderflowException bue) {
if (isOpen()) {
throw bue;
} else {
throw new ClosedChannelException();
}
}
}
/**
* {@inheritDoc}
*/
protected ByteBuffer readSingleByteBuffer(int length) throws IOException, ClosedChannelException, BufferUnderflowException {
try {
return super.readSingleByteBuffer(length);
} catch (BufferUnderflowException bue) {
if (isOpen()) {
throw bue;
} else {
throw new ClosedChannelException();
}
}
}
/**
* {@inheritDoc}
*
*/
public void setIdleTimeoutMillis(long timeoutMillis) {
idleTimeoutOccured.set(false);
if (timeoutMillis <= 0) {
LOG.warning("idle timeout " + timeoutMillis + " millis is invalid");
return;
}
this.idleTimeoutMillis = timeoutMillis;
this.idleTimeoutDateMillis = System.currentTimeMillis() + idleTimeoutMillis;
if (idleTimeoutDateMillis < 0) {
idleTimeoutDateMillis = Long.MAX_VALUE;
}
if ((timeoutMillis != IConnection.MAX_TIMEOUT_MILLIS) && (isConnected.get())) {
long period = idleTimeoutMillis;
if (idleTimeoutMillis > 500) {
period = idleTimeoutMillis / 5;
}
timeoutMgmHandle.updateCheckPeriod(period);
}
}
/**
* {@inheritDoc}
*/
public void setConnectionTimeoutMillis(long timeoutMillis) {
connectionTimeoutOccured.set(false);
if (timeoutMillis <= 0) {
LOG.warning("connection timeout " + timeoutMillis + " millis is invalid");
return;
}
this.connectionTimeoutMillis = timeoutMillis;
this.connectionTimeoutDateMillis = System.currentTimeMillis() + connectionTimeoutMillis;
if ((timeoutMillis != IConnection.MAX_TIMEOUT_MILLIS) && (isConnected.get())) {
long period = connectionTimeoutMillis;
if (connectionTimeoutMillis > 500) {
period = connectionTimeoutMillis / 5;
}
timeoutMgmHandle.updateCheckPeriod(period);
}
}
/**
* {@inheritDoc}
*/
public long getConnectionTimeoutMillis() {
return connectionTimeoutMillis;
}
/**
* {@inheritDoc}
*
*/
public long getIdleTimeoutMillis() {
return idleTimeoutMillis;
}
/**
* {@inheritDoc}
*/
public InetAddress getLocalAddress() {
return ioHandler.getLocalAddress();
}
/**
* {@inheritDoc}
*/
public String getId() {
return ioHandler.getId();
}
/**
* {@inheritDoc}
*/
public int getLocalPort() {
return ioHandler.getLocalPort();
}
/**
* {@inheritDoc}
*/
public InetAddress getRemoteAddress() {
return ioHandler.getRemoteAddress();
}
/**
* {@inheritDoc}
*/
public int getRemotePort() {
return ioHandler.getRemotePort();
}
/**
* {@inheritDoc}
*/
public int getPendingWriteDataSize() {
return getWriteBufferSize() + ioHandler.getPendingWriteDataSize();
}
/**
* {@inheritDoc}
*/
public void suspendReceiving() throws IOException {
synchronized (suspendGuard) {
ioHandler.suspendRead();
isSuspended.set(true);
}
}
/**
* {@inheritDoc}
*/
public boolean isReceivingSuspended() {
return isSuspended.get();
}
/**
* {@inheritDoc}
*/
public void resumeReceiving() throws IOException {
synchronized (suspendGuard) {
if (isReceivingSuspended()) {
ioHandler.resumeRead();
isSuspended.set(false);
if (getReadQueueSize() > 0) {
ioHandlerCallback.onPostData();
}
}
}
}
/**
* {@inheritDoc}
*/
public void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffer(message, encoding), writeCompletionHandler);
}
/**
* {@inheritDoc}
*/
public void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(ByteBuffer.wrap(bytes), writeCompletionHandler);
}
/**
* {@inheritDoc}
*/
public void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffer(bytes, offset, length), writeCompletionHandler);
}
/**
* {@inheritDoc}
*/
public void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffers(srcs, offset, length), writeCompletionHandler);
}
/**
* {@inheritDoc}
*/
public void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException {
if (!IS_SUPPRESS_SYNC_FLUSH_COMPLITIONHANDLER_WARNING && (getFlushmode() == FlushMode.SYNC)) {
String msg = "synchronized flush mode/completion handler combination could cause raced conditions (hint: set flush mode to ASYNC). This message can be suppressed by setting system property " + IoProvider.SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING_KEY;
LOG.warning("[" + getId() + "] " + msg);
}
synchronized (asyncWriteGuard) {
boolean isSuppressReuseBuffer = isSuppressReuseBufferWarning();
setSuppressReuseBufferWarning(true);
writeCompletionManager.registerCompletionHandler(writeCompletionHandler, buffer);
write(buffer);
setSuppressReuseBufferWarning(isSuppressReuseBuffer);
}
}
/**
* {@inheritDoc}
*/
public void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized (asyncWriteGuard) {
boolean isSuppressReuseBuffer = isSuppressReuseBufferWarning();
setSuppressReuseBufferWarning(true);
writeCompletionManager.registerCompletionHandler(writeCompletionHandler, buffers);
write(buffers);
setSuppressReuseBufferWarning(isSuppressReuseBuffer);
}
}
/**
* {@inheritDoc}
*/
public void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(buffers.toArray(new ByteBuffer[buffers.size()]), writeCompletionHandler);
}
public long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException, BufferOverflowException {
if (getFlushmode() == FlushMode.SYNC) {
return transferFromSync(source);
} else {
return super.transferFrom(source, chunkSize);
}
};
private long transferFromSync(ReadableByteChannel sourceChannel) throws ClosedChannelException, IOException, SocketTimeoutException, ClosedChannelException {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("transfering data by using WriteCompletionHandler");
}
boolean isSuppressReuseBufferWarning = isSuppressReuseBufferWarning();
try {
setSuppressReuseBufferWarning(true);
setFlushmode(FlushMode.ASYNC);
final Object guard = new Object();
final ByteBuffer copyBuffer = ByteBuffer.allocate(getSoSndBufSize());
final SendTask sendTask = new SendTask(guard, sourceChannel, copyBuffer);
sendTask.onWritten(0);
synchronized (guard) {
if (!sendTask.isComplete()) {
try {
guard.wait(sendTimeoutMillis);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
closeQuietly(NonBlockingConnection.this);
throw new SocketTimeoutException("timeout reached");
}
}
}
if (sendTask.getException() != null) {
throw sendTask.getException();
}
return sendTask.getWritten();
} finally {
setSuppressReuseBufferWarning(isSuppressReuseBufferWarning);
setFlushmode(FlushMode.SYNC);
}
}
@Execution(Execution.NONTHREADED)
private final class SendTask implements IWriteCompletionHandler {
private final Object guard;
private final ReadableByteChannel sourceChannel;
private final ByteBuffer copyBuffer;
private boolean isComplete = false;
private long written = 0;
private IOException ioe;
public SendTask(Object guard, ReadableByteChannel sourceChannel, ByteBuffer copyBuffer) {
this.guard = guard;
this.sourceChannel = sourceChannel;
this.copyBuffer = copyBuffer;
}
public void onWritten(int written) {
if (isComplete) {
return;
}
try {
copyBuffer.clear();
int read = sourceChannel.read(copyBuffer);
if (read > 0) {
copyBuffer.flip();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("writing next chunk (" + copyBuffer.remaining() + " bytes)");
}
write(copyBuffer, this);
if (!isAutoflush()) {
flush();
}
} else {
synchronized (guard) {
isComplete = true;
guard.notifyAll();
}
}
} catch (IOException ioe) {
onException(ioe);
}
}
public void onException(IOException ioe) {
if (isComplete) {
return;
}
this.ioe = ioe;
synchronized (guard) {
isComplete = true;
guard.notifyAll();
}
}
IOException getException() {
return ioe;
}
boolean isComplete() {
return isComplete;
}
long getWritten() {
return written;
}
}
private int getSoSndBufSize() throws IOException {
if (cachedSoSndBuf == null) {
cachedSoSndBuf = (Integer) getOption(SO_SNDBUF);
}
return cachedSoSndBuf;
}
/**
* {@inheritDoc}
*/
@Override
protected void onWriteDataInserted() throws IOException, ClosedChannelException {
if (isAutoflush()) {
internalFlush(null);
}
}
/**
* {@inheritDoc}
*/
public Object getOption(String name) throws IOException {
return ioHandler.getOption(name);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Map<String, Class> getOptions() {
return ioHandler.getOptions();
}
/**
* {@inheritDoc}
*/
public void setOption(String name, Object value) throws IOException {
if (name.equalsIgnoreCase(SO_SNDBUF)) {
cachedSoSndBuf = (Integer) value;
}
ioHandler.setOption(name, value);
}
@Override
protected int getWriteTransferChunkeSize() {
try {
return getSoSndBufSize();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by retrieving SoSndBufSize " + ioe.toString());
}
return super.getWriteTransferChunkeSize();
}
}
private void forceClose() {
try {
isOpen.set(false);
if (ioHandler != null) {
ioHandler.close(true);
}
writeCompletionManager.close();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Error occured by closing " + ioe.toString());
}
}
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
super.close();
if (isOpen.getAndSet(false)) {
if (getWriteTransferRate() != UNLIMITED) {
setWriteTransferRate(UNLIMITED);
}
synchronWriter.close();
ByteBuffer[] buffers = drainWriteQueue();
if (LOG.isLoggable(Level.FINE)) {
if (buffers != null) {
LOG.fine("[" + getId() + "] closing connection -> flush all remaining data: " + DataConverter.toString(ConnectionUtils.copy(buffers)));
} else {
LOG.fine("[" + getId() + "] closing connection (no remaining data)");
}
}
if (buffers != null) {
ioHandler.write(buffers);
ioHandler.flush();
}
if (ioHandler != null) {
ioHandler.close(false);
}
writeCompletionManager.close();
}
}
/**
* closes the connection quitly
*/
public void closeQuietly() {
closeQuietly(this);
}
/**
* {@inheritDoc}
*/
static void closeQuietly(INonBlockingConnection con) {
try {
con.close();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing connection " + con.getId() + " " + DataConverter.toString(ioe));
}
}
}
void performMultithreaded(Runnable task) {
taskQueue.performMultiThreaded(task, workerpool);
}
void performNonTHreeaded(Runnable task) {
taskQueue.performNonThreaded(task, workerpool);
}
/**
* {@inheritDoc}
*/
public void flush() throws ClosedChannelException, IOException {
internalFlush(null);
}
/**
* {@inheritDoc}
*/
void flush(List<ByteBuffer> recoveryBuffer) throws ClosedChannelException, IOException {
internalFlush(recoveryBuffer);
}
private void internalFlush(List<ByteBuffer> recoveryBuffer) throws ClosedChannelException, IOException {
if (!isOpen.get()) {
if (getReadQueueSize() > 0) {
throw new ClosedChannelException();
} else {
return;
}
}
removeWriteMark();
// is there data to flush?
if (!isWriteBufferEmpty()) {
// sync flush mode?
if (getFlushmode() == FlushMode.SYNC) {
synchronWriter.syncWrite(recoveryBuffer);
// ... no, async
} else {
ByteBuffer[] bufs = drainWriteQueue();
if ((bufs != null) && (recoveryBuffer != null)) {
for (ByteBuffer buf : bufs) {
recoveryBuffer.add(buf.duplicate());
}
}
ioHandler.write(bufs);
ioHandler.flush();
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] flushed");
}
}
private final class SynchronWriter {
private final AtomicBoolean isCallPendingRef = new AtomicBoolean(false);
private final ArrayList<ByteBuffer> pendingBuffers = new ArrayList<ByteBuffer>();
private IOException ioe = null;
private int countOnWritten = 0;
private int countOnException = 0;
private int countUnknownOnWritten = 0;
boolean isReusable() {
synchronized (this) {
return !isCallPendingRef.get();
}
}
void close() {
synchronized (this) {
pendingBuffers.clear();
}
}
void onWritten(ByteBuffer data) {
if (!isCallPendingRef.get()) {
return;
}
synchronized (this) {
countOnWritten++;
boolean isRemoved = pendingBuffers.remove(data);
if (!isRemoved) {
countUnknownOnWritten++;
}
if (pendingBuffers.isEmpty()) {
this.notifyAll();
}
}
}
public void onException(IOException ioe) {
if (isCallPendingRef.get()) {
return;
}
synchronized (this) {
countOnException++;
this.ioe = ioe;
pendingBuffers.clear();
this.notifyAll();
}
}
void syncWrite(List<ByteBuffer> recoveryBuffer) throws IOException, SocketTimeoutException {
if (!IS_SUPPRESS_SYNC_FLUSH_WARNING && ConnectionUtils.isDispatcherThread()) {
String msg = "synchronized flushing in NonThreaded mode could cause dead locks (hint: set flush mode to ASYNC). This message can be suppressed by setting system property " + IoProvider.SUPPRESS_SYNC_FLUSH_WARNING_KEY;
LOG.warning("[" + getId() + "] " + msg);
}
long start = System.currentTimeMillis();
synchronized (this) {
assert (pendingBuffers.isEmpty()) : "no pending buffers should exists";
isCallPendingRef.set(true);
// drain the queue
ByteBuffer[] data = drainWriteQueue();
if (data == null) {
return;
}
if (recoveryBuffer != null) {
for (ByteBuffer buf : data) {
recoveryBuffer.add(buf.duplicate());
}
}
try {
// add the data to write into the pending list
pendingBuffers.addAll(Arrays.asList(data));
// write the data and flush it
ioHandler.write(data);
ioHandler.flush();
// wait until the response is received
while (true) {
// all data written?
if (pendingBuffers.isEmpty()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] data written");
}
return;
// or got an exception?
} else if (ioe != null) {
throw ioe;
// no, check send timeout
} else {
long remainingTime = (start + sendTimeoutMillis) - System.currentTimeMillis();
if (remainingTime < 0) {
String msg = "[" + getId() + "] send timeout " + DataConverter.toFormatedDuration(sendTimeoutMillis) +
" reached. returning from sync flushing (countIsWritten=" + countOnWritten +
", countOnException=" + countOnException + ", sendBytes=" + ioHandler.getNumberOfSendBytes() +
", receivedBytes=" + ioHandler.getNumberOfReceivedBytes() +
", sendQueueSize=" + ioHandler.getPendingWriteDataSize() + ", countUnknownOnWritten=" + countUnknownOnWritten +
", " + ioHandler.getInfo() + ")";
if (LOG.isLoggable(Level.FINE)) {
LOG.fine(msg);
}
throw new SocketTimeoutException(msg);
}
// wait
try {
this.wait(remainingTime);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
}
} finally {
pendingBuffers.clear();
ioe = null;
countOnWritten = 0;
countOnException = 0;
isCallPendingRef.set(false);
}
} // synchronized
}
}
@Override
protected String getInfo() {
return toDetailedString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("id=" + getId());
try {
if (isOpen()) {
sb.append("remote=" + getRemoteAddress() + "(" + getRemoteAddress() + ":" + getRemotePort() + ")");
} else {
sb.append("(closed)");
}
} catch (Exception ignore) { }
return sb.toString();
}
String toDetailedString() {
if (isOpen()) {
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,S");
return "id=" + getId() + ", remote=" + getRemoteAddress().getCanonicalHostName() + "(" + getRemoteAddress() + ":" + getRemotePort() +
") lastTimeReceived=" + df.format(new Date(getLastTimeReceivedMillis())) + " reveived=" + getNumberOfReceivedBytes() +
" lastTimeSent=" + df.format(new Date(getLastTimeSendMillis())) +
" send=" + getNumberOfSendBytes() + " ops={" + getRegisteredOpsInfo() + "}";
} else {
return "id=" + getId() + " (closed)";
}
}
private static IoChainableHandler createClientIoHandler(SocketChannel channel, SSLContext sslContext, boolean sslOn) throws IOException {
if (sslContext != null) {
return ConnectionUtils.getIoProvider().createSSLClientIoHandler(channel, sslContext, sslOn);
} else {
return ConnectionUtils.getIoProvider().createClientIoHandler(channel);
}
}
private static SocketChannel openSocket(InetSocketAddress localAddress, Map<String ,Object> options) throws IOException {
SocketChannel channel = SocketChannel.open();
for (Entry<String, Object> entry : options.entrySet()) {
IoProvider.setOption(channel.socket(), entry.getKey(), entry.getValue());
}
if (localAddress != null) {
channel.socket().bind(localAddress);
}
return channel;
}
private final class IoHandlerCallback implements IIoHandlerCallback {
public void onWritten(ByteBuffer data) {
NonBlockingConnection.this.onWritten(data);
}
public void onWriteException(IOException ioException, ByteBuffer data) {
NonBlockingConnection.this.onWriteException(ioException, data);
}
public void onData(ByteBuffer[] data, int size) {
NonBlockingConnection.this.onData(data, size);
}
public void onPostData() {
NonBlockingConnection.this.onPostData();
}
public void onConnectionAbnormalTerminated() {
NonBlockingConnection.this.onConnectionAbnormalTerminated();
}
public void onConnect() {
NonBlockingConnection.this.onConnect();
}
public void onConnectException(IOException ioe) {
NonBlockingConnection.this.onConnectException(ioe);
}
public void onDisconnect() {
NonBlockingConnection.this.onDisconnect();
}
}
private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
namePrefix = "xNbcPool-" + POOL_NUMBER.getAndIncrement() + "-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
if (!t.isDaemon()) {
t.setDaemon(true);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
final class WriteCompletionManager {
// write completion handler support
private final Map<WriteCompletionHolder, List<ByteBuffer>> pendingCompletionConfirmations = new HashMap<WriteCompletionHolder, List<ByteBuffer>>();
private AtomicBoolean isWriteCompletionSupportActivated = new AtomicBoolean(false);
void registerCompletionHandler(IWriteCompletionHandler writeCompletionHandler, ByteBuffer... buffersToWrite) {
WriteCompletionHolder holder = new WriteCompletionHolder(writeCompletionHandler, buffersToWrite);
synchronized (this) {
isWriteCompletionSupportActivated.set(true);
pendingCompletionConfirmations.put(holder, new ArrayList<ByteBuffer>(Arrays.asList(buffersToWrite)));
}
if (LOG.isLoggable(Level.FINE)) {
int size = 0;
for (ByteBuffer byteBuffer : buffersToWrite) {
size += byteBuffer.remaining();
}
LOG.fine("[" + getId() + "] registering " + writeCompletionHandler.getClass().getSimpleName() + "#" + writeCompletionHandler.hashCode() + " waiting for " + size + " bytes");
}
}
void onWritten(ByteBuffer[] data) {
if (isWriteCompletionSupportActivated.get()) {
for (ByteBuffer byteBuffer : data) {
onWritten(byteBuffer);
}
}
}
private void onWritten(ByteBuffer data) {
WriteCompletionHolder holderToExecute = null;
if (data != null) {
synchronized (this) {
for (Entry<WriteCompletionHolder, List<ByteBuffer>> entry : pendingCompletionConfirmations.entrySet()) {
List<ByteBuffer> buffers = entry.getValue();
for (ByteBuffer buf : buffers) {
if (buf == data) {
buffers.remove(data);
break;
}
}
if (buffers.isEmpty()) {
holderToExecute = entry.getKey();
pendingCompletionConfirmations.remove(holderToExecute);
break;
}
}
}
}
if (holderToExecute != null) {
holderToExecute.performOnWritten();
}
}
void onWriteException(IOException ioException, ByteBuffer[] data) {
if (isWriteCompletionSupportActivated.get()) {
for (ByteBuffer byteBuffer : data) {
onWriteException(ioException, byteBuffer);
}
}
}
private void onWriteException(IOException ioException, ByteBuffer data) {
WriteCompletionHolder holderToExecute = null;
synchronized (this) {
if (data != null) {
outer : for (Entry<WriteCompletionHolder, List<ByteBuffer>> entry : pendingCompletionConfirmations.entrySet()) {
List<ByteBuffer> buffers = entry.getValue();
for (ByteBuffer buf : buffers) {
if (buf == data) {
holderToExecute = entry.getKey();
pendingCompletionConfirmations.remove(holderToExecute);
break outer;
}
}
}
}
}
if (holderToExecute != null) {
holderToExecute.performOnException(ioException);
}
}
boolean reset() {
synchronized (this) {
if (!pendingCompletionConfirmations.isEmpty()) {
for (WriteCompletionHolder handler : pendingCompletionConfirmations.keySet()) {
handler.callOnException(new ClosedChannelException());
}
pendingCompletionConfirmations.clear();
return false;
}
return true;
}
}
void close() {
synchronized (this) {
for (WriteCompletionHolder holder : pendingCompletionConfirmations.keySet()) {
holder.performOnException(new ExtendedClosedChannelException("[" + getId() + "] is closed"));
}
}
}
}
private final class WriteCompletionHolder implements Runnable {
private final IWriteCompletionHandler handler;
private final CompletionHandlerInfo handlerInfo;
private final int size;
public WriteCompletionHolder(IWriteCompletionHandler handler, ByteBuffer[] bufs) {
this.handler = handler;
this.handlerInfo = ConnectionUtils.getCompletionHandlerInfo(handler);
int l = 0;
for (ByteBuffer byteBuffer : bufs) {
l += byteBuffer.remaining();
}
size = l;
}
void performOnWritten() {
if (handlerInfo.isOnWrittenMultithreaded()) {
taskQueue.performMultiThreaded(this, getWorkerpool());
} else {
taskQueue.performNonThreaded(this, getWorkerpool());
}
}
public void run() {
callOnWritten();
}
private void callOnWritten() {
try {
handler.onWritten(size);
} catch (Exception e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by calling onWritten " + e.toString() + " closing connection");
}
closeQuietly(NonBlockingConnection.this);
}
}
void performOnException(final IOException ioe) {
if (handlerInfo.isOnExceptionMutlithreaded()) {
Runnable task = new Runnable() {
public void run() {
callOnException(ioe);
}
};
taskQueue.performMultiThreaded(task, workerpool);
} else {
Runnable task = new Runnable() {
public void run() {
callOnException(ioe);
}
};
taskQueue.performNonThreaded(task, workerpool);
}
}
private void callOnException(IOException ioe) {
handler.onException(ioe);
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/NonBlockingConnection.java | Java | art | 89,937 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
import org.xsocket.Execution;
import org.xsocket.ILifeCycle;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.SerializedTaskQueue;
/**
*
* @author grro@xsocket.org
*/
class HandlerAdapter {
private static final Logger LOG = Logger.getLogger(HandlerAdapter.class.getName());
private static final IHandler NULL_HANDLER = new NullHandler();
private static final HandlerAdapter NULL_HANDLER_ADAPTER = new HandlerAdapter(NULL_HANDLER, ConnectionUtils.getHandlerInfo(NULL_HANDLER));
private final IHandler handler;
private final IHandlerInfo handlerInfo;
HandlerAdapter(IHandler handler, IHandlerInfo handlerInfo) {
this.handler = handler;
this.handlerInfo = handlerInfo;
}
static HandlerAdapter newInstance(IHandler handler) {
if (handler == null) {
return NULL_HANDLER_ADAPTER;
} else {
IHandlerInfo handlerInfo = ConnectionUtils.getHandlerInfo(handler);
return new HandlerAdapter(handler, handlerInfo);
}
}
final IHandler getHandler() {
return handler;
}
final IHandlerInfo getHandlerInfo() {
return handlerInfo;
}
private static String printHandler(Object handler) {
return handler.getClass().getName() + "#" + handler.hashCode();
}
public boolean onConnect(final INonBlockingConnection connection, final SerializedTaskQueue taskQueue, final Executor workerpool, boolean isUnsynchronized) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (handlerInfo.isConnectHandler()) {
if (handlerInfo.isUnsynchronized() || (!getHandlerInfo().isConnectHandlerMultithreaded() && ConnectionUtils.isDispatcherThread())) {
performOnConnect(connection, taskQueue, (IConnectHandler) handler);
} else {
if (getHandlerInfo().isConnectHandlerMultithreaded()) {
taskQueue.performMultiThreaded(new PerformOnConnectTask(connection, taskQueue, (IConnectHandler) handler), workerpool);
} else {
if (isUnsynchronized) {
performOnConnect(connection, taskQueue, (IConnectHandler) handler);
} else {
taskQueue.performNonThreaded(new PerformOnConnectTask(connection, taskQueue, (IConnectHandler) handler), workerpool);
}
}
}
}
return true;
}
private static final class PerformOnConnectTask implements Runnable {
private final IConnectHandler handler;
private final INonBlockingConnection connection;
private final SerializedTaskQueue taskQueue;
public PerformOnConnectTask(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IConnectHandler handler) {
this.connection = connection;
this.taskQueue = taskQueue;
this.handler = handler;
}
public void run() {
performOnConnect(connection, taskQueue, handler);
}
}
private static boolean performOnConnect(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IConnectHandler handler) {
try {
handler.onConnect(connection);
} catch (MaxReadSizeExceededException mee) {
LOG.warning("[" + connection.getId() + "] closing connection because max readsize is reached by handling onConnect by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(mee));
closeSilence(connection);
} catch (BufferUnderflowException bue) {
// ignore
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because an error has been occured by handling onConnect by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(ioe));
}
closeSilence(connection);
} catch (Throwable t) {
LOG.warning("[" + connection.getId() + "] closing connection. Error occured by performing onConnect of " + printHandler(handler) + " " + DataConverter.toString(t));
closeSilence(connection);
}
return false;
}
public boolean onData(INonBlockingConnection connection, SerializedTaskQueue taskQueue, Executor workerpool, boolean ignoreException, boolean isUnsynchronized) {
if (handlerInfo.isDataHandler()) {
if (handlerInfo.isUnsynchronized()) {
performOnData(connection, taskQueue, ignoreException, (IDataHandler) handler);
} else {
if (getHandlerInfo().isDataHandlerMultithreaded()) {
taskQueue.performMultiThreaded(new PerformOnDataTask(connection, taskQueue, ignoreException, (IDataHandler) handler), workerpool);
} else {
if (isUnsynchronized) {
performOnData(connection, taskQueue, ignoreException, (IDataHandler) handler);
} else {
taskQueue.performNonThreaded(new PerformOnDataTask(connection, taskQueue, ignoreException, (IDataHandler) handler), workerpool);
}
}
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] assigned handler " + printHandler(handler) + " is not a data handler");
}
}
return true;
}
private static final class PerformOnDataTask implements Runnable {
private final IDataHandler handler;
private final INonBlockingConnection connection;
private final SerializedTaskQueue taskQueue;
private final boolean ignoreException;
public PerformOnDataTask(INonBlockingConnection connection, SerializedTaskQueue taskQueue, boolean ignoreException, IDataHandler handler) {
this.connection = connection;
this.taskQueue = taskQueue;
this.ignoreException = ignoreException;
this.handler = handler;
}
public void run() {
performOnData(connection, taskQueue, ignoreException, handler);
}
@Override
public String toString() {
return "PerformOnDataTask#" + hashCode() + " " + connection.getId();
}
}
private static void performOnData(INonBlockingConnection connection, SerializedTaskQueue taskQueue, boolean ignoreException, IDataHandler handler) {
try {
// loop until readQueue is empty or nor processing has been done (readQueue has not been modified)
while ((connection.available() != 0) && !connection.isReceivingSuspended()) {
if (connection.getHandler() != handler) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] handler " + " replaced by " + connection.getHandler() + ". stop handling data for old handler");
}
return;
}
int version = connection.getReadBufferVersion();
// calling onData method of the handler (return value will be ignored)
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] calling onData method of handler " + printHandler(handler));
}
handler.onData(connection);
if (version == connection.getReadBufferVersion()) {
return;
}
}
} catch (MaxReadSizeExceededException mee) {
if (!ignoreException) {
LOG.warning("[" + connection.getId() + "] closing connection because max readsize is reached by handling onData by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(mee));
closeSilence(connection);
}
} catch (BufferUnderflowException bue) {
// ignore
} catch (IOException ioe) {
if (!ignoreException) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because an error has been occured by handling data by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(ioe));
}
closeSilence(connection);
}
} catch (Throwable t) {
if (!ignoreException) {
LOG.warning("[" + connection.getId() + "] closing connection. Error occured by performing onData of " + printHandler(handler) + " " + DataConverter.toString(t));
closeSilence(connection);
}
}
}
public boolean onDisconnect(INonBlockingConnection connection, SerializedTaskQueue taskQueue, Executor workerpool, boolean isUnsynchronized) {
if (handlerInfo.isDisconnectHandler()) {
if (handlerInfo.isUnsynchronized()) {
performOnDisconnect(connection, taskQueue, (IDisconnectHandler) handler);
} else {
if (getHandlerInfo().isDisconnectHandlerMultithreaded()) {
taskQueue.performMultiThreaded(new PerformOnDisconnectTask(connection, taskQueue, (IDisconnectHandler) handler), workerpool);
} else {
if (isUnsynchronized) {
performOnDisconnect(connection, taskQueue, (IDisconnectHandler) handler);
} else {
taskQueue.performNonThreaded(new PerformOnDisconnectTask(connection, taskQueue, (IDisconnectHandler) handler), workerpool);
}
}
}
}
return true;
}
private static final class PerformOnDisconnectTask implements Runnable {
private final IDisconnectHandler handler;
private final INonBlockingConnection connection;
private final SerializedTaskQueue taskQueue;
public PerformOnDisconnectTask(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IDisconnectHandler handler) {
this.connection = connection;
this.taskQueue = taskQueue;
this.handler = handler;
}
public void run() {
performOnDisconnect(connection, taskQueue, handler);
}
@Override
public String toString() {
return "PerformOnDisconnectTask#" + hashCode() + " " + connection.getId();
}
}
private static void performOnDisconnect(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IDisconnectHandler handler) {
try {
handler.onDisconnect(connection);
} catch (MaxReadSizeExceededException mee) {
// ignore
} catch (BufferUnderflowException bue) {
// ignore
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] io exception occured while performing onDisconnect multithreaded " + printHandler(handler) + " " + DataConverter.toString(ioe));
}
} catch (Throwable t) {
LOG.warning("[" + connection.getId() + "] Error occured by performing onDisconnect off " + printHandler(handler) + " " + DataConverter.toString(t));
}
}
public boolean onConnectException(final INonBlockingConnection connection, final SerializedTaskQueue taskQueue, Executor workerpool, final IOException ioe) throws IOException {
if (handlerInfo.isConnectExceptionHandler()) {
if (handlerInfo.isUnsynchronized()) {
performOnConnectException(connection, taskQueue, ioe, (IConnectExceptionHandler) handler);
} else {
if (getHandlerInfo().isConnectExceptionHandlerMultithreaded()) {
taskQueue.performMultiThreaded(new PerformOnConnectExceptionTask(connection, taskQueue, ioe, (IConnectExceptionHandler) handler), workerpool);
} else {
taskQueue.performNonThreaded(new PerformOnConnectExceptionTask(connection, taskQueue, ioe, (IConnectExceptionHandler) handler), workerpool);
}
}
}
return true;
}
private static final class PerformOnConnectExceptionTask implements Runnable {
private final IConnectExceptionHandler handler;
private final INonBlockingConnection connection;
private final SerializedTaskQueue taskQueue;
private final IOException ioe;
public PerformOnConnectExceptionTask(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IOException ioe, IConnectExceptionHandler handler) {
this.connection = connection;
this.taskQueue = taskQueue;
this.ioe = ioe;
this.handler = handler;
}
public void run() {
try {
performOnConnectException(connection, taskQueue, ioe, handler);
} catch (MaxReadSizeExceededException mee) {
LOG.warning("[" + connection.getId() + "] closing connection because max readsize is reached by handling onConnectException by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(mee));
closeSilence(connection);
} catch (BufferUnderflowException bue) {
// ignore
} catch (IOException e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection. An io exception occured while performing onConnectException multithreaded " + printHandler(handler) + " " + DataConverter.toString(e));
}
closeSilence(connection);
} catch (Throwable t) {
LOG.warning("[" + connection.getId() + "] closing connection. Error occured by performing onConnectionException of " + printHandler(handler) + " " + t.toString());
closeSilence(connection);
}
}
}
private static boolean performOnConnectException(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IOException ioe, IConnectExceptionHandler handler) throws IOException {
try {
return handler.onConnectException(connection, ioe);
} catch (RuntimeException re) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because an error has been occured by handling onDisconnect by appHandler. " + printHandler(handler) + " Reason: " + re.toString());
}
closeSilence(connection);
throw re;
} catch (IOException e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because an error has been occured by handling onDisconnect by appHandler. " + printHandler(handler) + " Reason: " + ioe.toString());
}
closeSilence(connection);
throw ioe;
}
}
public boolean onIdleTimeout(final INonBlockingConnection connection, final SerializedTaskQueue taskQueue, Executor workerpool) throws IOException {
if (handlerInfo.isIdleTimeoutHandler()) {
if (handlerInfo.isUnsynchronized()) {
performOnIdleTimeout(connection, taskQueue, (IIdleTimeoutHandler) handler);
} else {
if (getHandlerInfo().isIdleTimeoutHandlerMultithreaded()) {
taskQueue.performMultiThreaded(new PerformOnIdleTimeoutTask(connection, taskQueue, (IIdleTimeoutHandler) handler), workerpool);
} else {
taskQueue.performNonThreaded(new PerformOnIdleTimeoutTask(connection, taskQueue, (IIdleTimeoutHandler) handler), workerpool);
}
}
} else {
closeSilence(connection);
}
return true;
}
private static final class PerformOnIdleTimeoutTask implements Runnable {
private final IIdleTimeoutHandler handler;
private final INonBlockingConnection connection;
private final SerializedTaskQueue taskQueue;
public PerformOnIdleTimeoutTask(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IIdleTimeoutHandler handler) {
this.connection = connection;
this.taskQueue = taskQueue;
this.handler = handler;
}
public void run() {
performOnIdleTimeout(connection, taskQueue, handler);
}
}
private static void performOnIdleTimeout(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IIdleTimeoutHandler handler) {
try {
boolean isHandled = handler.onIdleTimeout(connection);
if (!isHandled) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because idle timeout has been occured and timeout handler returns true)");
}
closeSilence(connection);
}
} catch (MaxReadSizeExceededException mee) {
LOG.warning("[" + connection.getId() + "] closing connection because max readsize is reached by handling onIdleTimeout by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(mee));
closeSilence(connection);
} catch (BufferUnderflowException bue) {
// ignore
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection. An IO exception occured while performing onIdleTimeout multithreaded " + printHandler(handler) + " " + ioe.toString());
}
closeSilence(connection);
} catch (Throwable t) {
LOG.warning("[" + connection.getId() + "] closing connection. Error occured by performing onIdleTimeout of " + printHandler(handler) + " " + DataConverter.toString(t));
closeSilence(connection);
}
}
public boolean onConnectionTimeout(INonBlockingConnection connection, SerializedTaskQueue taskQueue, Executor workerpool) throws IOException {
if (handlerInfo.isConnectionTimeoutHandler()) {
if (handlerInfo.isUnsynchronized()) {
performOnConnectionTimeout(connection, taskQueue, (IConnectionTimeoutHandler) handler);
} else {
if (getHandlerInfo().isConnectionTimeoutHandlerMultithreaded()) {
taskQueue.performMultiThreaded(new PerformOnConnectionTimeoutTask(connection, taskQueue, (IConnectionTimeoutHandler) handler), workerpool);
} else {
taskQueue.performNonThreaded(new PerformOnConnectionTimeoutTask(connection, taskQueue, (IConnectionTimeoutHandler) handler), workerpool);
}
}
} else {
closeSilence(connection);
}
return true;
}
private static final class PerformOnConnectionTimeoutTask implements Runnable {
private final IConnectionTimeoutHandler handler;
private final INonBlockingConnection connection;
private final SerializedTaskQueue taskQueue;
public PerformOnConnectionTimeoutTask(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IConnectionTimeoutHandler handler) {
this.connection = connection;
this.taskQueue = taskQueue;
this.handler = handler;
}
public void run() {
performOnConnectionTimeout(connection, taskQueue, handler);
}
}
private static void performOnConnectionTimeout(INonBlockingConnection connection, SerializedTaskQueue taskQueue, IConnectionTimeoutHandler handler) {
try {
boolean isHandled = handler.onConnectionTimeout(connection);
if (!isHandled) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] closing connection because connection timeout has been occured and timeout handler returns true)");
}
closeSilence(connection);
}
} catch (MaxReadSizeExceededException mee) {
LOG.warning("[" + connection.getId() + "] closing connection because max readsize hasbeen reached by handling onConnectionTimeout by appHandler. " + printHandler(handler) + " Reason: " + DataConverter.toString(mee));
closeSilence(connection);
} catch (BufferUnderflowException bue) {
// ignore
} catch (IOException ioe) {
LOG.warning("[" + connection.getId() + "] closing connection because an error has been occured by handling onConnectionTimeout by appHandler. " + handler + " Reason: " + DataConverter.toString(ioe));
closeSilence(connection);
} catch (Throwable t) {
LOG.warning("[" + connection.getId() + "] closing connection. Error occured by performing onConnectionTimeout of " + printHandler(handler) + " " + DataConverter.toString(t));
closeSilence(connection);
}
}
public final void onInit() {
if (handlerInfo.isLifeCycle()) {
((ILifeCycle) handler).onInit();
}
}
public final void onDestroy() {
if (handlerInfo.isLifeCycle()) {
try {
((ILifeCycle) handler).onDestroy();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("exception occured by destroying " + printHandler(handler) + " " + ioe.toString());
}
}
}
}
HandlerAdapter getConnectionInstance() {
if (handlerInfo.isConnectionScoped()) {
try {
IHandler hdlCopy = (IHandler) ((IConnectionScoped) handler).clone();
return new HandlerAdapter(hdlCopy, handlerInfo);
} catch (CloneNotSupportedException cnse) {
throw new RuntimeException(cnse.toString());
}
} else {
return this;
}
}
private static void closeSilence(INonBlockingConnection connection) {
try {
connection.close();
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing connection " + connection + " " + e.toString());
}
}
}
@Execution(Execution.NONTHREADED)
private static final class NullHandler implements IHandler {
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/HandlerAdapter.java | Java | art | 25,434 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
/**
* activateable SSL io handler
*
* @author grro@xsocket.org
*/
final class IoActivateableSSLHandler extends IoChainableHandler implements IoSSLProcessor.EventHandler {
private static final Logger LOG = Logger.getLogger(IoActivateableSSLHandler.class.getName());
private enum Mode { PLAIN, SSL, BUFFERING };
private AtomicReference<Mode> outboundModeRef = new AtomicReference<Mode>(Mode.PLAIN);
private AtomicReference<Mode> inboundModeRef = new AtomicReference<Mode>(Mode.PLAIN);
// receive & send queue
private IoQueue inNetDataQueue = new IoQueue();
private IoQueue outNetDataQueue = new IoQueue();
private IoQueue outAppDataQueue = new IoQueue();
// sync write support
private final PendingWriteMap pendingWriteMap = new PendingWriteMap();
// event handling
private final IOEventHandler ioEventHandler = new IOEventHandler();
// ssl stuff
private final SSLContext sslContext;
private final boolean isClientMode;
private final AbstractMemoryManager memoryManager;
private final AtomicReference<IoSSLProcessor> sslProcessorRef = new AtomicReference<IoSSLProcessor>();
/**
* constructor
*
* @param successor the successor
* @param sslContext the ssl context to use
* @param isClientMode true, if is in client mode
* @param memoryManager the memory manager to use
* @throws IOException If some other I/O error occurs
*/
IoActivateableSSLHandler(IoChainableHandler successor, SSLContext sslContext, boolean isClientMode, AbstractMemoryManager memoryManager) throws IOException {
super(successor);
this.sslContext = sslContext;
this.isClientMode = isClientMode;
this.memoryManager = memoryManager;
}
public void init(IIoHandlerCallback callbackHandler) throws IOException {
setPreviousCallback(callbackHandler);
getSuccessor().init(ioEventHandler);
}
@Override
public boolean isSecure() {
return (outboundModeRef.get() == Mode.SSL) && (inboundModeRef.get() == Mode.SSL);
}
/**
* {@inheritDoc}
*/
public boolean reset() {
inNetDataQueue.drain();
outNetDataQueue.drain();
outAppDataQueue.drain();
pendingWriteMap.clear();
return super.reset();
}
/**
* {@inheritDoc}
*/
public void setPreviousCallback(IIoHandlerCallback callbackHandler) {
super.setPreviousCallback(callbackHandler);
getSuccessor().setPreviousCallback(ioEventHandler);
}
/**
* {@inheritDoc}
*/
public void close(boolean immediate) throws IOException {
if (!immediate) {
hardFlush();
}
getSuccessor().close(immediate);
}
/**
* {@inheritDoc}
*/
@Override
public int getPendingWriteDataSize() {
return outAppDataQueue.getSize() + super.getPendingWriteDataSize();
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasDataToSend() {
return (!outAppDataQueue.isEmpty() || super.hasDataToSend());
}
@Override
public void write(ByteBuffer[] buffers) throws ClosedChannelException, IOException {
outAppDataQueue.append(buffers);
}
@Override
public void hardFlush() throws IOException {
flush();
}
/**
* {@inheritDoc}
*/
public void flush() throws IOException {
Mode outboundMode = outboundModeRef.get();
if (outboundMode == Mode.SSL) {
IoSSLProcessor sslProcessor = sslProcessorRef.get();
synchronized (outAppDataQueue) {
if (!outAppDataQueue.isEmpty()) {
sslProcessor.addOutAppData(outAppDataQueue.drain());
}
}
sslProcessor.encrypt();
} else if (outboundMode == Mode.PLAIN) {
synchronized (outAppDataQueue) {
if (!outAppDataQueue.isEmpty()) {
ByteBuffer[] data = outAppDataQueue.drain();
getSuccessor().write(data);
}
}
getSuccessor().flush();
} else {
assert (outboundMode == Mode.BUFFERING);
}
}
/**
* set mode to plain write and encrypted read
*
* @return true, if mode has been set
*/
public boolean preActivateSecuredMode() {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] switch to prestart secured mode (interpret incomming as SSL, writing plain outgoing plain)");
}
IoSSLProcessor sslProcessor = sslProcessorRef.get();
if (sslProcessor == null) {
sslProcessor = new IoSSLProcessor(sslContext, isClientMode, memoryManager, this);
sslProcessorRef.set(sslProcessor);
inboundModeRef.set(Mode.SSL);
return true;
} else {
LOG.warning("connection is already in ssl mode (" + printSSLState() + "). Ignore (pre)startSecured Mode");
return false;
}
}
private String printSSLState() {
return "inbound: " + inboundModeRef.get() + " outbound: " + outboundModeRef.get();
}
/**
* Return already received data to ssl handler (this data
* will be interpreted as encrypted data). <br>
*
* @param readQueue the queue with already received data
* @throws IOException if an io exception occurs
*/
public void activateSecuredMode(ByteBuffer[] data) throws IOException {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] switch to secured mode (handle incomming and outgoing as SSL)");
}
outboundModeRef.set(Mode.BUFFERING);
if ((data != null) && (data.length > 0)) {
inNetDataQueue.addFirst(data);
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] start ssl processor");
}
IoSSLProcessor sslProcessor = sslProcessorRef.get();
sslProcessor.start();
hardFlush();
readIncomingEncryptedData(inNetDataQueue.drain());
}
public void deactivateSecuredMode() throws IOException {
IoSSLProcessor sslProcessor = sslProcessorRef.get();
if (sslProcessor == null) {
LOG.warning("connection is already in plain mode (" + printSSLState() + "). Ignore deactivate");
} else {
hardFlush();
outboundModeRef.set(Mode.PLAIN);
sslProcessorRef.get().stop();
}
}
public void onInboundClosed() throws IOException {
inboundModeRef.set(Mode.PLAIN);
}
public void onHandshakeFinished() throws IOException {
outboundModeRef.set(Mode.SSL);
hardFlush();
}
private void readIncomingEncryptedData(ByteBuffer[] inNetDataList) throws ClosedChannelException, IOException {
if (inNetDataList != null) {
if (LOG.isLoggable(Level.FINE)) {
int size = 0;
for (ByteBuffer buffer : inNetDataList) {
size += buffer.remaining();
}
LOG.fine("received " + size + " bytes encrypted data");
}
sslProcessorRef.get().decrypt(inNetDataList);
}
}
public void onDestroy() throws IOException {
close(true);
}
/**
* has to be called within a synchronized context
*/
public void onDataDecrypted(ByteBuffer decryptedBuffer) {
if ((decryptedBuffer == null) || !decryptedBuffer.hasRemaining()) {
return;
}
getPreviousCallback().onData(new ByteBuffer[] { decryptedBuffer }, decryptedBuffer.remaining());
}
public void onPostDataDecrypted() {
getPreviousCallback().onPostData();
}
public void onDataEncrypted(ByteBuffer plainData, ByteBuffer encryptedData) throws IOException {
if (encryptedData.hasRemaining()) {
pendingWriteMap.add(plainData, encryptedData);
}
synchronized (outNetDataQueue) {
outNetDataQueue.append(encryptedData);
}
}
public void onPostDataEncrypted() throws IOException {
synchronized (outNetDataQueue) {
ByteBuffer[] data = outNetDataQueue.drain();
if (LOG.isLoggable(Level.FINE)) {
if (data != null) {
int size = 0;
for (ByteBuffer buffer : data) {
size += buffer.remaining();
}
LOG.fine("sending out app data (" + size + ")");
}
}
getSuccessor().write(data);
}
getSuccessor().flush();
}
private final class IOEventHandler implements IIoHandlerCallback {
public void onData(ByteBuffer[] data, int size) {
try {
Mode inboundMode = inboundModeRef.get();
if (inboundMode == Mode.PLAIN) {
getPreviousCallback().onData(data, size);
getPreviousCallback().onPostData();
} else if (inboundMode == Mode.SSL) {
readIncomingEncryptedData(data);
} else {
assert (inboundMode == Mode.BUFFERING);
inNetDataQueue.append(data);
return;
}
} catch (IOException e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured while receiving data. Reason: " + e.toString());
}
}
}
public void onPostData() {
}
public void onConnect() {
getPreviousCallback().onConnect();
}
public void onConnectException(IOException ioe) {
getPreviousCallback().onConnectException(ioe);
}
public void onWriteException(IOException ioException, ByteBuffer data) {
getPreviousCallback().onWriteException(ioException, data);
}
public void onWritten(ByteBuffer data) {
ByteBuffer plainData = pendingWriteMap.getPlainIfWritten(data);
if (plainData != null) {
getPreviousCallback().onWritten(plainData);
} else{
getPreviousCallback().onWritten(data);
}
}
public void onDisconnect() {
//getSSLProcessor().destroy();
getPreviousCallback().onDisconnect();
}
public void onConnectionAbnormalTerminated() {
getPreviousCallback().onConnectionAbnormalTerminated();
}
}
private static final class PendingWriteMap {
private Map<ByteBuffer, List<ByteBuffer>> plainEncryptedMapping = new IdentityHashMap<ByteBuffer, List<ByteBuffer>>();
private Map<ByteBuffer, ByteBuffer> encryptedPlainMapping = new IdentityHashMap<ByteBuffer, ByteBuffer>();
public synchronized void add(ByteBuffer plain, ByteBuffer encrypted) {
// ignore system data (plain is empty)
if (plain.limit() > 0) {
List<ByteBuffer> encryptedList = plainEncryptedMapping.get(plain);
if (encryptedList == null) {
encryptedList = new ArrayList<ByteBuffer>();
plainEncryptedMapping.put(plain, encryptedList);
}
encryptedList.add(encrypted);
encryptedPlainMapping.put(encrypted, plain);
}
}
public synchronized ByteBuffer getPlainIfWritten(ByteBuffer encrypted) {
ByteBuffer plain = encryptedPlainMapping.remove(encrypted);
if (plain != null) {
List<ByteBuffer> encryptedList = plainEncryptedMapping.get(plain);
encryptedList.remove(encrypted);
if (encryptedList.isEmpty()) {
plainEncryptedMapping.remove(plain);
return plain;
}
}
return null;
}
public synchronized void clear() {
plainEncryptedMapping.clear();
encryptedPlainMapping.clear();
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IoActivateableSSLHandler.java | Java | art | 12,294 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import org.xsocket.MaxReadSizeExceededException;
/**
* Handles new incoming connections. <br><br>
*
* E.g.
* <pre>
* public final class BlackIpHandler implements IConnectHandler {
* ...
*
* public boolean onConnect(INonBlockingConnection connection) throws IOException {
* connection.write("220 my smtp server" + LINE_DELIMITER);
* return true;
* }
* }
* <pre>
*
* @author grro@xsocket.org
*/
public interface IConnectHandler extends IHandler {
/**
* handles a new incoming connection
*
* @return true for positive result of handling, false for negative result of handling
* @throws IOException if some other I/O error occurs. Throwing this exception causes that the underlying connection will be closed.
* @throws BufferUnderflowException if more incoming data is required to process (e.g. delimiter hasn't yet received -> readByDelimiter methods or size of the available, received data is smaller than the required size -> readByLength). The BufferUnderflowException will be swallowed by the framework
* @throws MaxReadSizeExceededException if the max read size has been reached (e.g. by calling method {@link INonBlockingConnection#readStringByDelimiter(String, int)}).
* Throwing this exception causes that the underlying connection will be closed.
* @throws RuntimeException if an runtime exception occurs. Throwing this exception causes that the underlying connection will be closed.
*/
boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IConnectHandler.java | Java | art | 2,824 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* Connection manager
*
* @author grro@xsocket.org
*/
final class ConnectionManager {
private static final Logger LOG = Logger.getLogger(ConnectionManager.class.getName());
// connections
private final ArrayList<WeakReference<TimeoutMgmHandle>> handles = new ArrayList<WeakReference<TimeoutMgmHandle>>();
// watch dog
private static final long DEFAULT_WATCHDOG_PERIOD_CONNECTION_CHECK_MILLISTION_CHECK_MILLIS = 1L * 60L * 1000L;
private long watchDogPeriodConCheckMillis = DEFAULT_WATCHDOG_PERIOD_CONNECTION_CHECK_MILLISTION_CHECK_MILLIS;
private WachdogTask conCheckWatchDogTask = null;
private int watchDogRuns;
private int countIdleTimeouts;
private int countConnectionTimeouts;
private AtomicInteger currentSize = new AtomicInteger(0);
public ConnectionManager() {
updateTimeoutCheckPeriod(watchDogPeriodConCheckMillis);
}
public TimeoutMgmHandle register(NonBlockingConnection connection) {
TimeoutMgmHandle mgnCon = new TimeoutMgmHandle(connection);
WeakReference<TimeoutMgmHandle> ref = mgnCon.getWeakRef();
if (ref != null) {
synchronized (handles) {
handles.add(ref);
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("did not get the weak ref");
}
}
currentSize.incrementAndGet();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("connection registered");
}
return mgnCon;
}
long getWatchDogPeriodMillis() {
return watchDogPeriodConCheckMillis;
}
int getWatchDogRuns() {
return watchDogRuns;
}
private void remove(WeakReference<TimeoutMgmHandle> handleRef) {
synchronized (handles) {
handles.remove(handleRef);
}
currentSize.decrementAndGet();
if (LOG.isLoggable(Level.FINE)) {
TimeoutMgmHandle hdl = handleRef.get();
if (hdl != null) {
INonBlockingConnection con = hdl.getConnection();
if (con != null) {
LOG.fine("[" + con.getId() + "] handle deregistered (connections size=" + computeSize() + ")");
}
}
}
}
int getSize() {
return currentSize.get();
}
private int computeSize() {
synchronized (handles) {
int size = handles.size();
currentSize.set(size);
return size;
}
}
@SuppressWarnings("unchecked")
Set<NonBlockingConnection> getConnections() {
final Set<NonBlockingConnection> cons = new HashSet<NonBlockingConnection>();
ArrayList<WeakReference<TimeoutMgmHandle>> connectionsCopy = null;
synchronized (handles) {
connectionsCopy = (ArrayList<WeakReference<TimeoutMgmHandle>>) handles.clone();
}
for (WeakReference<TimeoutMgmHandle> handleRef : connectionsCopy) {
TimeoutMgmHandle handle = handleRef.get();
if (handle != null) {
NonBlockingConnection con = handle.getConnection();
if (con != null) {
cons.add(con);
}
}
}
return cons;
}
void close() {
// closing watch dog
if (conCheckWatchDogTask != null) {
conCheckWatchDogTask.cancel();
conCheckWatchDogTask = null;
}
// close open connections
try {
for (NonBlockingConnection connection : getConnections()) {
try {
connection.close();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing connection " + connection.getId() + " " + DataConverter.toString(ioe));
}
}
}
} catch (Throwable e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing open connections " + DataConverter.toString(e));
}
}
// clear handle list
handles.clear();
}
int getNumberOfIdleTimeouts() {
return countIdleTimeouts;
}
int getNumberOfConnectionTimeouts() {
return countConnectionTimeouts;
}
void updateTimeoutCheckPeriod(long requiredMinPeriod) {
// if non watchdog task already exists and the required period is smaller than current one -> return
if ((conCheckWatchDogTask != null) && (watchDogPeriodConCheckMillis <= requiredMinPeriod)) {
return;
}
// set watch dog period
watchDogPeriodConCheckMillis = requiredMinPeriod;
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("update watchdog period " + DataConverter.toFormatedDuration(watchDogPeriodConCheckMillis));
}
synchronized (this) {
// if watchdog task task already exits -> terminate it
if (conCheckWatchDogTask != null) {
TimerTask tt = conCheckWatchDogTask;
conCheckWatchDogTask = null;
tt.cancel();
}
// create and run new watchdog task
conCheckWatchDogTask = new WachdogTask();
IoProvider.getTimer().schedule(conCheckWatchDogTask, watchDogPeriodConCheckMillis, watchDogPeriodConCheckMillis);
}
}
private final class WachdogTask extends TimerTask {
@Override
public void run() {
try {
check();
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by running check: " + e.toString());
}
}
}
}
@SuppressWarnings("unchecked")
void check() {
watchDogRuns++;
long current = System.currentTimeMillis();
ArrayList<WeakReference<TimeoutMgmHandle>> connectionsCopy = null;
synchronized (handles) {
connectionsCopy = (ArrayList<WeakReference<TimeoutMgmHandle>>) handles.clone();
}
for (WeakReference<TimeoutMgmHandle> handleRef : connectionsCopy) {
TimeoutMgmHandle handle = handleRef.get();
if (handle == null) {
remove(handleRef);
} else {
NonBlockingConnection con = handle.getConnection();
if (con.isOpen()) {
checkTimeout(con, current);
} else {
remove(handleRef);
}
}
}
computeSize();
}
private void checkTimeout(NonBlockingConnection connection, long current) {
boolean timeoutOccured = connection.checkIdleTimeout(current);
if (timeoutOccured) {
countIdleTimeouts++;
}
timeoutOccured = connection.checkConnectionTimeout(current);
if (timeoutOccured) {
countConnectionTimeouts++;
}
}
final class TimeoutMgmHandle {
private final NonBlockingConnection con;
private WeakReference<TimeoutMgmHandle> handleRef;
public TimeoutMgmHandle(NonBlockingConnection connection) {
con = connection;
handleRef = new WeakReference<TimeoutMgmHandle>(this);
}
WeakReference<TimeoutMgmHandle> getWeakRef() {
return handleRef;
}
void updateCheckPeriod(long period) {
updateTimeoutCheckPeriod(period);
}
void destroy() {
if (handleRef != null) {
remove(handleRef);
handleRef = null;
}
}
NonBlockingConnection getConnection() {
return con;
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/ConnectionManager.java | Java | art | 8,950 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.xsocket.DataConverter;
import org.xsocket.WorkerPool;
import org.xsocket.connection.IConnection.FlushMode;
/**
* Implementation of a server. For more information see
* {@link IServer}
*
* @author grro@xsocket.org
*/
public class Server implements IServer {
private static final Logger LOG = Logger.getLogger(Server.class.getName());
private static String implementationVersion = ConnectionUtils.getImplementationVersion();
private static String implementationDate;
protected static final int SIZE_WORKER_POOL = Integer.parseInt(System.getProperty("org.xsocket.connection.server.workerpoolSize", "100"));
protected static final int MIN_SIZE_WORKER_POOL = Integer.parseInt(System.getProperty("org.xsocket.connection.server.workerpoolMinSize", "2"));
protected static final int TASK_QUEUE_SIZE = Integer.parseInt(System.getProperty("org.xsocket.connection.server.taskqueuesize", Integer.toString(SIZE_WORKER_POOL)));
private static final int WAITTIME_MAXCONNECTION_EXCEEDED = Integer.parseInt(System.getProperty("org.xsocket.connection.server.waittimeMaxConnectionExceeded", Integer.toString(500)));
private FlushMode flushMode = IConnection.DEFAULT_FLUSH_MODE;
private boolean autoflush = IConnection.DEFAULT_AUTOFLUSH;
private Integer writeRate;
// is open flag
private final AtomicBoolean isOpen = new AtomicBoolean(false);
// name
private String name = "server";
// acceptor
private IoAcceptor acceptor;
// workerpool
private ExecutorService defaultWorkerPool;
private Executor workerpool;
//connection manager
private ConnectionManager connectionManager = new ConnectionManager();
private int maxConcurrentConnections = Integer.MAX_VALUE;
private boolean isMaxConnectionCheckAvtive = false;
// handler replace Listener
private final AtomicReference<IHandlerChangeListener> handlerReplaceListenerRef = new AtomicReference<IHandlerChangeListener>();
// app handler
private HandlerAdapter handlerAdapter = HandlerAdapter.newInstance(null);
// thresholds
private Integer maxReadBufferThreshold = null;
// timeouts
private long idleTimeoutMillis = IConnection.MAX_TIMEOUT_MILLIS;
private long connectionTimeoutMillis = IConnection.MAX_TIMEOUT_MILLIS;
// server listeners
private final ArrayList<IServerListener> listeners = new ArrayList<IServerListener>();
// local address
private String localHostname = "";
private int localPort = -1;
// start up message
private String startUpLogMessage = "xSocket " + implementationVersion;
// startup date
private long startUpTime = 0;
/**
* constructor <br><br>
*
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws IOException If some other I/O error occurs
* @throws UnknownHostException if the local host cannot determined
*/
public Server(IHandler handler) throws UnknownHostException, IOException {
this(new InetSocketAddress(0), new HashMap<String, Object>(), handler, null, false, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws IOException If some other I/O error occurs
* @throws UnknownHostException if the local host cannot determined
*/
public Server(Map<String, Object> options, IHandler handler) throws UnknownHostException, IOException {
this(new InetSocketAddress(0), options, handler, null, false, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
*
* @param port the local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port, IHandler handler) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), new HashMap<String, Object>(), handler, null, false, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
*
* @param port the local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param minPoolsize the min workerpool size
* @param maxPoolsize the max workerpool size
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port, IHandler handler, int minPoolsize, int maxPoolsize) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), new HashMap<String, Object>(), handler, null, false, 0, minPoolsize, maxPoolsize, maxPoolsize);
}
/**
* constructor <br><br>
*
*
* @param port the local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param backlog The maximum number number of pending connections. If has the value 0, or a negative value, then an implementation specific default is used.
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port, IHandler handler, int backlog) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), new HashMap<String, Object>(), handler, null, false, backlog, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param port the local port
* @param options the acceptor socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port, Map<String , Object> options, IHandler handler) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), options, handler, null, false, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param address the local address
* @param port the local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(InetAddress address, int port, IHandler handler) throws UnknownHostException, IOException {
this(address, port, new HashMap<String, Object>(), handler, null, false,0);
}
/**
* constructor <br><br>
*
* @param ipAddress the local ip address
* @param port the local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(String ipAddress, int port, IHandler handler) throws UnknownHostException, IOException {
this(new InetSocketAddress(ipAddress, port), new HashMap<String, Object>(), handler, null, false, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
*
* @param ipAddress the local ip address
* @param port the local port
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(String ipAddress, int port, Map<String, Object> options, IHandler handler) throws UnknownHostException, IOException {
this(new InetSocketAddress(ipAddress, port), options, handler, null, false, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param port local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port, IHandler handler, SSLContext sslContext, boolean sslOn) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), new HashMap<String, Object>(), handler, sslContext, sslOn, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param port local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @param minPoolsize the min workerpool size
* @param maxPoolsize the max workerpool size
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port, IHandler handler, SSLContext sslContext, boolean sslOn, int minPoolsize, int maxPoolsize) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), new HashMap<String, Object>(), handler, sslContext, sslOn, 0, minPoolsize, maxPoolsize, maxPoolsize);
}
/**
* constructor <br><br>
*
* @param port local port
* @param options the acceptor socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(int port,Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn) throws UnknownHostException, IOException {
this(new InetSocketAddress(port), options, handler, sslContext, sslOn, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param ipAddress local ip address
* @param port local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(String ipAddress, int port, IHandler handler, SSLContext sslContext, boolean sslOn) throws UnknownHostException, IOException {
this(new InetSocketAddress(ipAddress, port), new HashMap<String, Object>(), handler, sslContext, sslOn, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param ipAddress local ip address
* @param port local port
* @param options the acceptor socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(String ipAddress, int port, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn) throws UnknownHostException, IOException {
this(new InetSocketAddress(ipAddress, port), options, handler, sslContext, sslOn, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param address local address
* @param port local port
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(InetAddress address, int port, IHandler handler, SSLContext sslContext, boolean sslOn) throws UnknownHostException, IOException {
this(new InetSocketAddress(address, port), new HashMap<String, Object>(), handler, sslContext, sslOn, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param address local address
* @param port local port
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(InetAddress address, int port, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn) throws UnknownHostException, IOException {
this(new InetSocketAddress(address, port), options, handler, sslContext, sslOn, 0, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param address local address
* @param port local port
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @param backlog The maximum number number of pending connections. If has the value 0, or a negative value, then an implementation specific default is used.
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(InetAddress address, int port, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn, int backlog) throws UnknownHostException, IOException {
this(new InetSocketAddress(address, port), options, handler, sslContext, sslOn, backlog, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor <br><br>
*
* @param address local address
* @param port local port
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @param backlog The maximum number number of pending connections. If has the value 0, or a negative value, then an implementation specific default is used.
* @param minPoolsize The min workerpool size
* @param maxPoolsize The max workerpool size
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
public Server(InetAddress address, int port, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn, int backlog, int minPoolsize, int maxPoolsize) throws UnknownHostException, IOException {
this(new InetSocketAddress(address, port), options, handler, sslContext, sslOn, backlog, minPoolsize, maxPoolsize, maxPoolsize);
}
/**
* constructor
*
* @param address local address
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @param backlog The maximum number number of pending connections. If has the value 0, or a negative value, then an implementation specific default is used.
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
protected Server(InetSocketAddress address, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn, int backlog) throws UnknownHostException, IOException {
this(address, options, handler, sslContext, sslOn, backlog, MIN_SIZE_WORKER_POOL, SIZE_WORKER_POOL, TASK_QUEUE_SIZE);
}
/**
* constructor
*
* @param address local address
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @param backlog The maximum number number of pending connections. If has the value 0, or a negative value, then an implementation specific default is used.
* @param minPoolsize The min workerpool size
* @param maxPoolsize The max workerpool size
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
protected Server(InetSocketAddress address, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn, int backlog, int minPoolsize, int maxPoolsize) throws UnknownHostException, IOException {
this(address, options, handler, sslContext, sslOn, backlog, minPoolsize, maxPoolsize, maxPoolsize);
}
/**
* constructor
*
* @param address local address
* @param options the socket options
* @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler, IConnectionTimeoutHandler, IConnectionScoped, ILifeCycle)
* @param sslOn true, is SSL should be activated
* @param sslContext the ssl context to use
* @param backlog The maximum number number of pending connections. If has the value 0, or a negative value, then an implementation specific default is used.
* @param minPoolsize The min workerpool size
* @param maxPoolsize The max workerpool size
* @param taskqueueSize The taskqueue size
* @throws UnknownHostException if the local host cannot determined
* @throws IOException If some other I/O error occurs
*/
protected Server(InetSocketAddress address, Map<String, Object> options, IHandler handler, SSLContext sslContext, boolean sslOn, int backlog, int minPoolsize, int maxPoolsize, int taskqueueSize) throws UnknownHostException, IOException {
defaultWorkerPool = new WorkerPool(minPoolsize, maxPoolsize, taskqueueSize);
workerpool = defaultWorkerPool;
if (sslContext != null) {
acceptor = ConnectionUtils.getIoProvider().createAcceptor(new LifeCycleHandler(), address, backlog, options, sslContext, sslOn);
} else {
acceptor = ConnectionUtils.getIoProvider().createAcceptor(new LifeCycleHandler(), address, backlog, options);
}
localHostname = acceptor.getLocalAddress().getHostName();
localPort = acceptor.getLocalPort();
setHandler(handler);
}
/**
* set the handler
* @param handler the handler
*/
public void setHandler(IHandler handler) {
if (isOpen.get()) {
callCurrentHandlerOnDestroy();
}
IHandlerChangeListener changeListener = handlerReplaceListenerRef.get();
if (changeListener != null) {
IHandler oldHandler = handlerAdapter.getHandler();
changeListener.onHanderReplaced(oldHandler, handler);
}
handlerAdapter = HandlerAdapter.newInstance(handler);
// init app handler
initCurrentHandler();
}
private void initCurrentHandler() {
ConnectionUtils.injectServerField(this, handlerAdapter.getHandler());
handlerAdapter.onInit();
}
private void callCurrentHandlerOnDestroy() {
handlerAdapter.onDestroy();
}
/**
* the the server name. The server name will be used to print out the start log message.<br>
*
* E.g.
* <pre>
* IServer cacheServer = new Server(port, new CacheHandler());
* ConnectionUtils.start(server);
* server.setServerName("CacheServer");
*
*
* // prints out
* // 01::52::42,756 10 INFO [Server$AcceptorCallback#onConnected] CacheServer listening on 172.25.34.33/172.25.34.33:9921 (xSocket 2.0)
* </pre>
*
* @param name the server name
*/
public final void setServerName(String name) {
this.name = name;
}
/**
* return the server name
*
* @return the server name
*/
public final String getServerName() {
return name;
}
/**
* {@inheritDoc}
*/
public String getStartUpLogMessage() {
return startUpLogMessage;
}
/**
* {@inheritDoc}
*/
public void setStartUpLogMessage(String message) {
this.startUpLogMessage = message;
}
/**
* {@inheritDoc}
*/
public void run() {
try {
if (getHandler() == null) {
LOG.warning("no handler has been set. Call setHandler-method to assign a handler");
}
startUpTime = System.currentTimeMillis();
ShutdownHookHandler shutdownHookHandler = new ShutdownHookHandler(this);
try {
// register shutdown hook handler
shutdownHookHandler.register();
// listening in a blocking way
acceptor.listen();
} finally {
// deregister shutdown hook handler
shutdownHookHandler.deregister();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static final class ShutdownHookHandler extends Thread {
private Runtime runtime;
private Server server;
public ShutdownHookHandler(Server server) {
this.server = server;
}
void register() {
runtime = Runtime.getRuntime();
runtime.addShutdownHook(this);
}
public void run() {
if (server != null) {
server.close();
}
}
void deregister() {
if (runtime != null) {
try {
runtime.removeShutdownHook(this);
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by derigistering shutdwon hook " + e.toString());
}
}
runtime = null;
server = null;
}
}
}
/**
* starts the given server within a dedicated thread. This method blocks
* until the server is open. This method is equals to {@link ConnectionUtils#start(IServer)}
*
* @throws SocketTimeoutException is the timeout has been reached
*/
public void start() throws IOException {
ConnectionUtils.start(this);
}
/**
* {@inheritDoc}
*/
public final Object getOption(String name) throws IOException {
return acceptor.getOption(name);
}
public IHandler getHandler() {
return handlerAdapter.getHandler();
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public final Map<String, Class> getOptions() {
return acceptor.getOptions();
}
/**
* {@inheritDoc}
*/
public final void close() {
// is open?
if (isOpen.getAndSet(false)) {
// close connection manager
try {
connectionManager.close();
} catch (Throwable e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing acceptor " + DataConverter.toString(e));
}
}
connectionManager = null;
// closing acceptor
try {
acceptor.close(); // closing of dispatcher will be initiated by acceptor
} catch (Throwable e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing acceptor " + DataConverter.toString(e));
}
}
acceptor = null;
// notify listeners
try {
onClosed();
} catch (Throwable e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by performing onClosed method " + DataConverter.toString(e));
}
}
// unset references
handlerAdapter = null;
}
}
protected void onClosed() throws IOException {
}
protected void onPreRejectConnection(NonBlockingConnection connection) throws IOException {
}
final IoAcceptor getAcceptor() {
return acceptor;
}
final long getConnectionManagerWatchDogPeriodMillis() {
return connectionManager.getWatchDogPeriodMillis();
}
final int getConnectionManagerWatchDogRuns() {
return connectionManager.getWatchDogRuns();
}
/**
* {@inheritDoc}
*/
public final void addListener(IServerListener listener) {
listeners.add(listener);
}
/**
* {@inheritDoc}
*/
public final boolean removeListener(IServerListener listener) {
boolean result = listeners.remove(listener);
return result;
}
/**
* {@inheritDoc}
*/
public final Executor getWorkerpool() {
return workerpool;
}
/**
* {@inheritDoc}
*/
public final void setWorkerpool(Executor executor) {
if (executor == null) {
throw new NullPointerException("executor has to be set");
}
if (isOpen.get()) {
LOG.warning("server is already running");
}
workerpool = executor;
if (defaultWorkerPool != null) {
defaultWorkerPool.shutdown();
defaultWorkerPool = null;
}
}
/**
* {@inheritDoc}
*/
public final boolean isOpen() {
return isOpen.get();
}
/**
* sets the max number of concurrent connections
*
* @param maxConcurrentConnections the max number of concurrent connections
*/
public final void setMaxConcurrentConnections(int maxConcurrentConnections) {
this.maxConcurrentConnections = maxConcurrentConnections;
if (maxConcurrentConnections == Integer.MAX_VALUE) {
isMaxConnectionCheckAvtive = false;
} else {
isMaxConnectionCheckAvtive = true;
}
}
/**
* set the max app read buffer threshold
*
* @param maxSize the max read buffer threshold
*/
public void setMaxReadBufferThreshold(int maxSize) {
this.maxReadBufferThreshold = maxSize;
}
/**
* returns the number of max concurrent connections
* @return the number of max concurrent connections
*/
int getMaxConcurrentConnections() {
return maxConcurrentConnections;
}
/**
* {@inheritDoc}
*/
public final int getLocalPort() {
return acceptor.getLocalPort();
}
/**
* {@inheritDoc}
*/
public final InetAddress getLocalAddress() {
return acceptor.getLocalAddress();
}
final int getNumberOfOpenConnections() {
return connectionManager.getSize();
}
final int getDispatcherPoolSize() {
return acceptor.getDispatcherSize();
}
final void setDispatcherPoolSize(int size) {
acceptor.setDispatcherSize(size);
}
final boolean getReceiveBufferIsDirect() {
return acceptor.getReceiveBufferIsDirect();
}
final void setReceiveBufferIsDirect(boolean isDirect) {
acceptor.setReceiveBufferIsDirect(isDirect);
}
final Integer getReceiveBufferPreallocatedMinSize() {
if (acceptor.isReceiveBufferPreallocationMode()) {
return acceptor.getReceiveBufferPreallocatedMinSize();
} else {
return null;
}
}
public Set<INonBlockingConnection> getOpenConnections() {
HashSet<INonBlockingConnection> cons = new HashSet<INonBlockingConnection>();
if (connectionManager != null) {
for (INonBlockingConnection con: connectionManager.getConnections()) {
if (con.isOpen()) {
cons.add(con);
}
}
}
return cons;
}
final List<String> getOpenConnectionInfos() {
List<String> infos = new ArrayList<String>();
for (NonBlockingConnection con : connectionManager.getConnections()) {
infos.add(con.toDetailedString());
}
return infos;
}
final int getNumberOfIdleTimeouts() {
return connectionManager.getNumberOfIdleTimeouts();
}
final int getNumberOfConnectionTimeouts() {
return connectionManager.getNumberOfConnectionTimeouts();
}
final Date getStartUPDate() {
return new Date(startUpTime);
}
/**
* {@inheritDoc}
*/
public final FlushMode getFlushmode() {
return flushMode;
}
/**
* {@inheritDoc}
*/
public final void setFlushmode(FlushMode flusmode) {
this.flushMode = flusmode;
}
/**
* {@inheritDoc}
*/
public final void setAutoflush(boolean autoflush) {
this.autoflush = autoflush;
}
/**
* {@inheritDoc}
*/
public final boolean getAutoflush() {
return autoflush;
}
/**
* {@inheritDoc}
*/
public final void setConnectionTimeoutMillis(long timeoutMillis) {
this.connectionTimeoutMillis = timeoutMillis;
}
/**
* {@inheritDoc}
*/
public void setWriteTransferRate(int bytesPerSecond) throws IOException {
if ((bytesPerSecond != INonBlockingConnection.UNLIMITED) && (flushMode != FlushMode.ASYNC)) {
LOG.warning("setWriteTransferRate is only supported for FlushMode ASYNC. Ignore update of the transfer rate");
return;
}
this.writeRate = bytesPerSecond;
}
// public void setReadTransferRate(int bytesPerSecond) throws IOException {
// this.readRate = bytesPerSecond;
// }
/**
* {@inheritDoc}
*/
public void setIdleTimeoutMillis(long timeoutMillis) {
this.idleTimeoutMillis = timeoutMillis;
}
/**
* {@inheritDoc}
*/
public final long getConnectionTimeoutMillis() {
return connectionTimeoutMillis;
}
/**
* {@inheritDoc}
*/
public final long getIdleTimeoutMillis() {
return idleTimeoutMillis;
}
/**
* returns the implementation version
*
* @return the implementation version
*/
public String getImplementationVersion() {
return implementationVersion;
}
/**
* returns the implementation date
*
* @return the implementation date
*/
public String getImplementationDate() {
if (implementationDate == null) {
implementationDate = ConnectionUtils.getImplementationDate();
}
return implementationDate;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getServerName() + " on " + getLocalAddress().toString() + " Port " + getLocalPort());
sb.append("\r\nopen connections:");
for (NonBlockingConnection con : connectionManager.getConnections()) {
sb.append("\r\n " + con.toString());
}
return sb.toString();
}
private final class LifeCycleHandler implements IIoAcceptorCallback {
@SuppressWarnings("unchecked")
public void onConnected() {
isOpen.set(true);
// notify listeners
for (IServerListener listener : (ArrayList<IServerListener>) listeners.clone()) {
listener.onInit();
}
// print out the startUp log message
if (acceptor.isSSLSupported()) {
if (acceptor.isSSLOn()) {
LOG.info(name + " listening on " + localHostname + ":" + localPort + " - SSL (" + startUpLogMessage + ")");
} else {
LOG.info(name + " listening on " + localHostname + ":" + localPort + " - activatable SSL (" + startUpLogMessage + ")");
}
} else {
LOG.info(name + " listening on " + localHostname + ":" + localPort + " (" + startUpLogMessage + ")");
}
}
@SuppressWarnings("unchecked")
public void onDisconnected() {
// perform handler callback
callCurrentHandlerOnDestroy();
// calling server listener
for (IServerListener listener : (ArrayList<IServerListener>)listeners.clone()) {
try {
listener.onDestroy();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("exception occured by destroying " + listener + " " + ioe.toString());
}
}
}
listeners.clear();
// close default worker pool if exists
if (defaultWorkerPool != null) {
WorkerpoolCloser workerpoolCloser = new WorkerpoolCloser(Server.this);
workerpoolCloser.start();
}
// unset workerpool reference
workerpool = null;
// print log message
LOG.info("server (" + localHostname + ":" + localPort + ") has been shutdown");
}
public void onConnectionAccepted(IoChainableHandler ioHandler) throws IOException {
// if max connection size reached -> reject connection & sleep
if (isMacConnectionSizeExceeded()) {
// create connection
NonBlockingConnection connection = new NonBlockingConnection(connectionManager, HandlerAdapter.newInstance(null));
init(connection, ioHandler);
// first call pre reject
try {
onPreRejectConnection(connection);
} catch (IOException e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] error occured by calling onPreRejectConnection " + e.toString());
}
}
// ... and than reject it
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] rejecting connection. Max concurrent connection size (" + maxConcurrentConnections + ") exceeded");
}
connection.closeQuietly();
// wait while max connection size is exceeded
do {
try {
Thread.sleep(WAITTIME_MAXCONNECTION_EXCEEDED);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
} while (isMacConnectionSizeExceeded());
// .. not exceeded
} else {
// create a new connection
NonBlockingConnection connection = new NonBlockingConnection(connectionManager, handlerAdapter.getConnectionInstance());
init(connection, ioHandler);
}
}
private boolean isMacConnectionSizeExceeded() {
return (isMaxConnectionCheckAvtive &&
isOpen.get() &&
(acceptor.getDispatcherPool().getRoughNumRegisteredHandles() >= maxConcurrentConnections) &&
(acceptor.getDispatcherPool().getNumRegisteredHandles() >= maxConcurrentConnections));
}
private void init(NonBlockingConnection connection, IoChainableHandler ioHandler) throws SocketTimeoutException, IOException {
// set default flush properties
connection.setAutoflush(autoflush);
connection.setFlushmode(flushMode);
connection.setWorkerpool(workerpool);
// initialize the connection
connection.init(ioHandler);
// set timeouts (requires that connection is already initialized)
connection.setIdleTimeoutMillis(idleTimeoutMillis);
connection.setConnectionTimeoutMillis(connectionTimeoutMillis);
// set transfer rates
if (writeRate != null) {
connection.setWriteTransferRate(writeRate);
}
// and threshold
if (maxReadBufferThreshold != null) {
connection.setMaxReadBufferThreshold(maxReadBufferThreshold);
}
}
}
private static final class WorkerpoolCloser extends Thread {
private Server server;
public WorkerpoolCloser(Server server) {
super("workerpoolCloser");
setDaemon(true);
this.server = server;
}
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
try {
server.defaultWorkerPool.shutdownNow();
} finally {
server.defaultWorkerPool = null;
server = null;
}
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/Server.java | Java | art | 41,011 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import org.xsocket.Execution;
/**
* A marker interface for a handler <br><br>
*
* Specific handlers defines <code>on<event></code> callback methods. <br>
*
* @author grro@xsocket.org
*/
public interface IHandler {
static final int DEFAULT_EXECUTION_MODE = Execution.MULTITHREADED;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IHandler.java | Java | art | 1,354 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.AbstractNonBlockingStream.ISource;
/**
*
*
* @author grro
*/
final class ReadQueue {
private static final Logger LOG = Logger.getLogger(ReadQueue.class.getName());
// queue
private final Queue queue = new Queue();
// mark support
private ByteBuffer[] readMarkBuffer;
private boolean isReadMarked = false;
private int readMarkVersion = -1;
public void reset() {
readMarkBuffer = null;
isReadMarked = false;
queue.reset();
}
/**
* returns true, if empty
*
* @return true, if empty
*/
public boolean isEmpty() {
return (queue.getSize() == 0);
}
/**
* return a int, which represent the modification version.
* this value will increase with each modification
*
* @return the modify version
*/
public int geVersion() {
return queue.getVersion(false);
}
/**
* append a byte buffer array to this queue. By adding a list,
* the list becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the ByteBuffers
* @param size the size
*/
public void append(ByteBuffer[] bufs, int size) {
assert (size == computeSize(bufs));
//is data available?
if (size > 0) {
queue.append(bufs, size);
}
}
private static int computeSize(ByteBuffer[] bufs) {
int size = 0;
for (ByteBuffer buf : bufs) {
size += buf.remaining();
}
return size;
}
/**
* return the index of the delimiter or -1 if the delimiter has not been found
*
* @param delimiter the delimiter
* @param maxReadSize the max read size
* @return the position of the first delimiter byte
* @throws IOException in an exception occurs
* @throws MaxReadSizeExceededException if the max read size has been reached
*/
public int retrieveIndexOf(byte[] delimiter, int maxReadSize) throws IOException, MaxReadSizeExceededException {
return queue.retrieveIndexOf(delimiter, maxReadSize);
}
/**
* return the current size
*
* @return the current size
*/
public int getSize() {
return queue.getSize();
}
public ByteBuffer[] readAvailable() {
ByteBuffer[] buffers = queue.drain();
onExtracted(buffers);
return buffers;
}
public ByteBuffer[] copyAvailable() {
ByteBuffer[] buffers = queue.copy();
onExtracted(buffers);
return buffers;
}
public ByteBuffer[] readByteBufferByDelimiter(byte[] delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
ByteBuffer[] buffers = queue.readByteBufferByDelimiter(delimiter, maxLength);
onExtracted(buffers, delimiter);
return buffers;
}
public void unread(ByteBuffer[] buffers) throws IOException {
if (isReadMarked) {
throw new IOException("unread() is not supported in marked read mode");
}
queue.addFirst(buffers);
}
public ByteBuffer[] readByteBufferByLength(int length) throws BufferUnderflowException {
ByteBuffer[] buffers = queue.readByteBufferByLength(length);
onExtracted(buffers);
return buffers;
}
public ByteBuffer readSingleByteBuffer(int length) throws BufferUnderflowException {
if (getSize() < length) {
throw new BufferUnderflowException();
}
ByteBuffer buffer = queue.readSingleByteBuffer(length);
onExtracted(buffer);
return buffer;
}
public void markReadPosition() {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("mark read position");
}
removeReadMark();
isReadMarked = true;
readMarkVersion = queue.getVersion(true);
}
public boolean resetToReadMark() {
if (isReadMarked) {
if (readMarkBuffer != null) {
queue.addFirst(readMarkBuffer);
removeReadMark();
queue.setVersion(readMarkVersion);
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("reset read mark. nothing to return to read queue");
}
}
return true;
} else {
return false;
}
}
public void removeReadMark() {
isReadMarked = false;
readMarkBuffer = null;
}
private void onExtracted(ByteBuffer[] buffers) {
if (isReadMarked) {
for (ByteBuffer buffer : buffers) {
onExtracted(buffer);
}
}
}
private void onExtracted(ByteBuffer[] buffers, byte[] delimiter) {
if (isReadMarked) {
if (buffers != null) {
for (ByteBuffer buffer : buffers) {
onExtracted(buffer);
}
}
onExtracted(ByteBuffer.wrap(delimiter));
}
}
private void onExtracted(ByteBuffer buffer) {
if (isReadMarked) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("add data (" + DataConverter.toFormatedBytesSize(buffer.remaining()) + ") to read mark buffer ");
}
if (readMarkBuffer == null) {
readMarkBuffer = new ByteBuffer[1];
readMarkBuffer[0] = buffer.duplicate();
} else {
ByteBuffer[] newReadMarkBuffer = new ByteBuffer[readMarkBuffer.length + 1];
System.arraycopy(readMarkBuffer, 0, newReadMarkBuffer, 0, readMarkBuffer.length);
newReadMarkBuffer[readMarkBuffer.length] = buffer.duplicate();
readMarkBuffer = newReadMarkBuffer;
}
}
}
@Override
public String toString() {
return queue.toString();
}
public String toString(String encoding) {
return queue.toString(encoding);
}
private static final class Queue implements ISource {
private static final int THRESHOLD_COMPACT_BUFFER_COUNT_TOTAL = 20;
private static final int THRESHOLD_COMPACT_BUFFER_COUNT_EMPTY = 10;
// queue
private ByteBuffer[] buffers = null;
private Integer currentSize = null;
private int version = 0;
private boolean isAppended = false;
// cache support
private Index cachedIndex = null;
/**
* clean the queue
*/
public synchronized void reset() {
buffers = null;
currentSize = null;
cachedIndex = null;
isAppended = false;
}
/**
* return a int, which represent the version.
* this value will increase with modification
*
* @return the modify version
*/
public synchronized int getVersion(boolean mark) {
if (mark) {
isAppended = false;
}
return version;
}
public synchronized void setVersion(int version) {
if (!isAppended) {
this.version = version;
}
}
/**
* return the current size
*
* @return the current size
*/
public synchronized int getSize() {
return size();
}
private int size() {
// performance optimization if size has been already calculated
if (currentSize != null) {
return currentSize;
}
if (buffers == null) {
return 0;
} else {
int size = 0;
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] != null) {
size += buffers[i].remaining();
}
}
currentSize = size;
return size;
}
}
/**
* append a byte buffer array to this queue. By adding a array,
* the array becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the ByteBuffers
* @param size the size
*/
public synchronized void append(ByteBuffer[] bufs, int size) {
isAppended = true;
version++;
assert (!containsEmptyBuffer(bufs));
if (buffers == null) {
buffers = bufs;
currentSize = size;
} else {
currentSize = null;
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + bufs.length];
System.arraycopy(buffers, 0, newBuffers, 0, buffers.length);
System.arraycopy(bufs, 0, newBuffers, buffers.length, bufs.length);
buffers = newBuffers;
}
}
public synchronized void addFirst(ByteBuffer[] bufs) {
version++;
currentSize = null;
cachedIndex = null;
assert (!containsEmptyBuffer(bufs));
addFirstSilence(bufs);
}
private void addFirstSilence(ByteBuffer[] bufs) {
currentSize = null;
if (buffers == null) {
buffers = bufs;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + bufs.length];
System.arraycopy(bufs, 0, newBuffers, 0, bufs.length);
System.arraycopy(buffers, 0, newBuffers, bufs.length, buffers.length);
buffers = newBuffers;
}
}
private static boolean containsEmptyBuffer(ByteBuffer[] bufs) {
boolean containsEmtpyBuffer = false;
for (ByteBuffer buf : bufs) {
if (buf == null) {
containsEmtpyBuffer = true;
}
}
return containsEmtpyBuffer;
}
/**
* drain the queue
*
* @return the content
*/
public synchronized ByteBuffer[] drain() {
currentSize = null;
cachedIndex = null;
ByteBuffer[] result = buffers;
buffers = null;
if (result != null) {
version++;
}
return removeEmptyBuffers(result);
}
public synchronized ByteBuffer[] copy() {
if (buffers == null) {
return new ByteBuffer[0];
}
ByteBuffer[] result = new ByteBuffer[buffers.length];
for (int i = 0; i < buffers.length; i++) {
result[i] = buffers[i].duplicate();
}
return removeEmptyBuffers(result);
}
/**
* read bytes
*
* @param length the length
* @return the read bytes
* @throws BufferUnderflowException if the buffer`s limit has been reached
*/
public synchronized ByteBuffer readSingleByteBuffer(int length) throws BufferUnderflowException {
// data available?
if (buffers == null) {
throw new BufferUnderflowException();
}
// enough bytes available ?
if (!isSizeEqualsOrLargerThan(length)) {
throw new BufferUnderflowException();
}
// length 0 requested?
if (length == 0) {
return ByteBuffer.allocate(0);
}
ByteBuffer result = null;
int countEmptyBuffer = 0;
bufLoop : for (int i = 0; i < buffers.length; i++) {
if (buffers[i] == null) {
countEmptyBuffer++;
continue;
}
// length first buffer == required length
if (buffers[i].remaining() == length) {
result = buffers[i];
buffers[i] = null;
break bufLoop;
// length first buffer > required length
} else if(buffers[i].remaining() > length) {
int savedLimit = buffers[i].limit();
int savedPos = buffers[i].position();
buffers[i].limit(buffers[i].position() + length);
result = buffers[i].slice();
buffers[i].position(savedPos + length);
buffers[i].limit(savedLimit);
buffers[i] = buffers[i].slice();
break bufLoop;
// length first buffer < required length
} else {
result = ByteBuffer.allocate(length);
int written = 0;
for (int j = i; j < buffers.length; j++) {
if (buffers[j] == null) {
countEmptyBuffer++;
continue;
} else {
while(buffers[j].hasRemaining()) {
result.put(buffers[j].get());
written++;
// all data written
if (written == length) {
if (buffers[j].position() < buffers[j].limit()) {
buffers[j] = buffers[j].slice();
} else {
buffers[j] = null;
}
result.clear();
break bufLoop;
}
}
}
buffers[j] = null;
}
}
}
if (result == null) {
throw new BufferUnderflowException();
} else {
if (countEmptyBuffer >= THRESHOLD_COMPACT_BUFFER_COUNT_EMPTY) {
compact();
}
currentSize = null;
cachedIndex = null;
version++;
return result;
}
}
public ByteBuffer[] readByteBufferByLength(int length) throws BufferUnderflowException {
if (length == 0) {
return new ByteBuffer[0];
}
return extract(length, 0);
}
public ByteBuffer[] readByteBufferByDelimiter(byte[] delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
synchronized (this) {
if (buffers == null) {
throw new BufferUnderflowException();
}
}
int index = retrieveIndexOf(delimiter, maxLength);
// delimiter found?
if (index >= 0) {
return extract(index, delimiter.length);
} else {
throw new BufferUnderflowException();
}
}
synchronized ByteBuffer[] extract(int length, int countTailingBytesToRemove) throws BufferUnderflowException {
ByteBuffer[] extracted = null;
int size = size();
if (length == size) {
return drain();
}
if (size < length) {
throw new BufferUnderflowException();
}
extracted = extractBuffers(length);
if (countTailingBytesToRemove > 0) {
extractBuffers(countTailingBytesToRemove); // remove tailing bytes
}
compact();
currentSize = null;
cachedIndex = null;
version++;
return extracted;
}
/**
* return the index of the delimiter or -1 if the delimiter has not been found
*
* @param delimiter the delimiter
* @param maxReadSize the max read size
* @return the position of the first delimiter byte
* @throws IOException in an exception occurs
* @throws MaxReadSizeExceededException if the max read size has been reached
*/
public int retrieveIndexOf(byte[] delimiter, int maxReadSize) throws IOException, MaxReadSizeExceededException {
ByteBuffer[] bufs = null;
// get the current buffers
synchronized (this) {
if (buffers == null) {
return -1;
}
bufs = buffers;
buffers = null;
}
// .. scan it
int index = retrieveIndexOf(delimiter, bufs, maxReadSize);
// .. and return the buffers
synchronized (this) {
addFirstSilence(bufs);
}
if (index == -2) {
throw new MaxReadSizeExceededException();
} else {
return index;
}
}
private int retrieveIndexOf(byte[] delimiter, ByteBuffer[] buffers, int maxReadSize) {
Integer length = null;
// is data available?
if (buffers == null) {
return -1;
}
Index index = scanByDelimiter(buffers, delimiter);
// index found?
if (index.hasDelimiterFound()) {
// ... within the max range?
if (index.getReadBytes() <= maxReadSize) {
length = index.getReadBytes() - delimiter.length;
// .. no
} else {
length = null;
}
// .. no
} else {
length = null;
}
cachedIndex = index;
// delimiter not found (length is not set)
if (length == null) {
// check if max read size has been reached
if (index.getReadBytes() >= maxReadSize) {
return -2;
}
return -1;
// delimiter found -> return length
} else {
return length;
}
}
private Index scanByDelimiter(ByteBuffer[] buffers, byte[] delimiter) {
// does index already exists (-> former scan) & same delimiter?
if ((cachedIndex != null) && (cachedIndex.isDelimiterEquals(delimiter))) {
// delimiter already found?
if (cachedIndex.hasDelimiterFound()) {
return cachedIndex;
// .. no
} else {
// cached index available -> use index to find
return find(buffers, cachedIndex);
}
// ... no cached index -> find by delimiter
} else {
return find(buffers, delimiter);
}
}
private boolean isSizeEqualsOrLargerThan(int requiredSize) {
if (buffers == null) {
return false;
}
int bufferSize = 0;
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] != null) {
bufferSize += buffers[i].remaining();
if (bufferSize >= requiredSize) {
return true;
}
}
}
return false;
}
private ByteBuffer[] extractBuffers(int length) {
ByteBuffer[] extracted = null;
int remainingToExtract = length;
ByteBuffer buffer = null;
for (int i = 0; i < buffers.length; i++) {
// get the first buffer
buffer = buffers[i];
if (buffer == null) {
continue;
}
// can complete buffer be taken?
int bufLength = buffer.limit() - buffer.position();
if (remainingToExtract >= bufLength) {
// write taken into out channel
extracted = appendBuffer(extracted, buffer);
remainingToExtract -= bufLength;
buffers[i] = null;
// .. no
} else {
int savedLimit = buffer.limit();
// extract the takenable
buffer.limit(buffer.position() + remainingToExtract);
ByteBuffer leftPart = buffer.slice();
extracted = appendBuffer(extracted, leftPart);
buffer.position(buffer.limit());
buffer.limit(savedLimit);
ByteBuffer rightPart = buffer.slice();
buffers[i] = rightPart;
remainingToExtract = 0;
}
if (remainingToExtract == 0) {
return extracted;
}
}
return new ByteBuffer[0];
}
private static ByteBuffer[] appendBuffer(ByteBuffer[] buffers, ByteBuffer buffer) {
if (buffers == null) {
ByteBuffer[] result = new ByteBuffer[1];
result[0] = buffer;
return result;
} else {
ByteBuffer[] result = new ByteBuffer[buffers.length + 1];
System.arraycopy(buffers, 0, result, 0, buffers.length);
result[buffers.length] = buffer;
return result;
}
}
private void compact() {
if ((buffers != null) && (buffers.length > THRESHOLD_COMPACT_BUFFER_COUNT_TOTAL)) {
// count empty buffers
int emptyBuffers = 0;
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] == null) {
emptyBuffers++;
}
}
// enough empty buffers found? create new compact array
if (emptyBuffers > THRESHOLD_COMPACT_BUFFER_COUNT_EMPTY) {
if (emptyBuffers == buffers.length) {
buffers = null;
} else {
ByteBuffer[] newByteBuffer = new ByteBuffer[buffers.length - emptyBuffers];
int num = 0;
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] != null) {
newByteBuffer[num] = buffers[i];
num++;
}
}
buffers = newByteBuffer;
}
}
}
}
private static ByteBuffer[] removeEmptyBuffers(ByteBuffer[] buffers) {
if (buffers == null) {
return buffers;
}
int countEmptyBuffers = 0;
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] == null) {
countEmptyBuffers++;
}
}
if (countEmptyBuffers > 0) {
if (countEmptyBuffers == buffers.length) {
return new ByteBuffer[0];
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length - countEmptyBuffers];
int num = 0;
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] != null) {
newBuffers[num] = buffers[i];
num++;
}
}
return newBuffers;
}
} else {
return buffers;
}
}
@Override
public String toString() {
try {
ByteBuffer[] copy = buffers.clone();
for (int i = 0; i < copy.length; i++) {
if (copy[i] != null) {
copy[i] = copy[i].duplicate();
}
}
return DataConverter.toTextAndHexString(copy, "UTF-8", 300);
} catch (NullPointerException npe) {
return "";
} catch (Exception e) {
return e.toString();
}
}
public synchronized String toString(String encoding) {
try {
ByteBuffer[] copy = buffers.clone();
for (int i = 0; i < copy.length; i++) {
if (copy[i] != null) {
copy[i] = copy[i].duplicate();
}
}
return DataConverter.toString(copy, encoding);
} catch (NullPointerException npe) {
return "";
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Index find(ByteBuffer[] bufferQueue, byte[] delimiter) {
return find(bufferQueue, new Index(delimiter));
}
private Index find(ByteBuffer[] buffers, Index index) {
int i = findFirstBufferToScan(buffers, index);
for (; (i < buffers.length) && !index.hasDelimiterFound; i++) {
ByteBuffer buffer = buffers[i];
if (buffer == null) {
continue;
}
// save current buffer positions
int savedPos = buffer.position();
int savedLimit = buffer.limit();
findInBuffer(buffer, index);
// restore buffer positions
buffer.position(savedPos);
buffer.limit(savedLimit);
}
return index;
}
private int findFirstBufferToScan(ByteBuffer[] buffers, Index index) {
int i = 0;
// jump to next buffer which follows the cached one
if (index.lastScannedBuffer != null) {
// find the last scanned buffer
for (int j = 0; j < buffers.length; j++) {
if (buffers[j] == index.lastScannedBuffer) {
i = j;
break;
}
}
// position to next buffer
i++;
// are there more buffers?
if (i >= buffers.length) {
// ...no, do nothing
return i;
}
// filter the empty buffers
for (int k = i; k < buffers.length; k++) {
if (buffers[k] != null) {
i = k;
break;
}
}
// are there more buffers?
if (i >= buffers.length) {
// ...no, do nothing
return i;
}
}
return i;
}
private void findInBuffer(ByteBuffer buffer, Index index) {
index.lastScannedBuffer = buffer;
int dataSize = buffer.remaining();
byte[] delimiter = index.delimiterBytes;
int delimiterLength = index.delimiterLength;
int delimiterPosition = index.delimiterPos;
byte nextDelimiterByte = delimiter[delimiterPosition];
boolean delimiterPartsFound = delimiterPosition > 0;
for (int i = 0; i < dataSize; i++) {
byte b = buffer.get();
// is current byte a delimiter byte?
if (b == nextDelimiterByte) {
delimiterPosition++;
// is single byte delimiter?
if (delimiterLength == 1) {
index.hasDelimiterFound = true;
index.delimiterPos = delimiterPosition;
index.readBytes += (i + 1);
return;
// .. no, it is a multi byte delimiter
} else {
index.delimiterPos = delimiterPosition;
// last delimiter byte found?
if (delimiterPosition == delimiterLength) {
index.hasDelimiterFound = true;
index.readBytes += (i + 1);
return;
}
nextDelimiterByte = delimiter[delimiterPosition];
}
delimiterPartsFound = true;
// byte doesn't match
} else {
if (delimiterPartsFound) {
delimiterPosition = 0;
index.delimiterPos = 0;
nextDelimiterByte = delimiter[delimiterPosition];
delimiterPartsFound = false;
// check if byte is equals to first delimiter byte
if ((delimiterLength > 1) && (b == nextDelimiterByte)) {
delimiterPosition++;
nextDelimiterByte = delimiter[delimiterPosition];
index.delimiterPos = delimiterPosition;
}
}
}
}
index.readBytes += dataSize;
}
}
private static final class Index implements Cloneable {
private boolean hasDelimiterFound = false;
private byte[] delimiterBytes = null;
private int delimiterLength = 0;
private int delimiterPos = 0;
// consumed bytes
private int readBytes = 0;
// cache support
ByteBuffer lastScannedBuffer = null;
Index(byte[] delimiterBytes) {
this.delimiterBytes = delimiterBytes;
this.delimiterLength = delimiterBytes.length;
}
public boolean hasDelimiterFound() {
return hasDelimiterFound;
}
public int getReadBytes() {
return readBytes;
}
public boolean isDelimiterEquals(byte[] other) {
if (other.length != delimiterLength) {
return false;
}
for (int i = 0; i < delimiterLength; i++) {
if (other[i] != delimiterBytes[i]) {
return false;
}
}
return true;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Index copy = (Index) super.clone();
return copy;
}
@Override
public String toString() {
return "found=" + hasDelimiterFound + " delimiterPos=" + delimiterPos
+ " delimiterLength="+ delimiterLength + " readBytes=" + readBytes;
}
}
} | zzh-simple-hr | Zxsocket/src/org/xsocket/connection/ReadQueue.java | Java | art | 26,884 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.xsocket.ILifeCycle;
/**
* A blocking connection pool implementation. <br> <br>
*
* This class is thread safe <br>
*
* <pre>
* // create a unbound connection pool
* BlockingConnectionPool pool = new BlockingConnectionPool();
*
*
* IBlockingConnection con = null;
*
* try {
* // retrieve a connection (if no connection is in pool, a new one will be created)
* con = pool.getBlockingConnection(host, port);
* con.write("Hello");
* ...
*
* // always close the connection! (the connection will be returned into the connection pool)
* con.close();
*
* } catch (IOException e) {
* if (con != null) {
* try {
* // if the connection is invalid -> destroy it (it will not return into the pool)
* pool.destroy(con);
* } catch (Exception ignore) { }
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public final class BlockingConnectionPool implements IConnectionPool {
private final NonBlockingConnectionPool pool;
/**
* constructor
*/
public BlockingConnectionPool() {
pool = new NonBlockingConnectionPool();
}
/**
* constructor
*
* @param sslContext the ssl context or <code>null</code> if ssl should not be used
*/
public BlockingConnectionPool(SSLContext sslContext) {
pool = new NonBlockingConnectionPool(sslContext);
}
/**
* {@inheritDoc}
*/
public boolean isOpen() {
return pool.isOpen();
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(String host, int port) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(host, port, false));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occur
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(String host, int port, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(host, port, isSSL));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(String host, int port, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(host, port, connectTimeoutMillis, false));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(String host, int port, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(host, port, connectTimeoutMillis, isSSL));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(InetAddress address, int port) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(address, port, false));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(InetAddress address, int port, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(address, port, isSSL));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(InetAddress address, int port, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(address, port, connectTimeoutMillis, false));
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public IBlockingConnection getBlockingConnection(InetAddress address, int port, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return new BlockingConnection(pool.getNonBlockingConnection(address, port, connectTimeoutMillis, isSSL));
}
/**
* {@inheritDoc}
*/
public void addListener(ILifeCycle listener) {
pool.addListener(listener);
}
/**
* {@inheritDoc}
*/
public boolean removeListener(ILifeCycle listener) {
return pool.removeListener(listener);
}
/**
* {@inheritDoc}
*/
public int getPooledMaxIdleTimeMillis() {
return pool.getPooledMaxIdleTimeMillis();
}
/**
* {@inheritDoc}
*/
public void setPooledMaxIdleTimeMillis(int idleTimeoutMillis) {
pool.setPooledMaxIdleTimeMillis(idleTimeoutMillis);
}
/**
* {@inheritDoc}
*/
public int getPooledMaxLifeTimeMillis() {
return pool.getPooledMaxLifeTimeMillis();
}
/**
* {@inheritDoc}
*/
public void setPooledMaxLifeTimeMillis(int lifeTimeoutMillis) {
pool.setPooledMaxLifeTimeMillis(lifeTimeoutMillis);
}
/**
* {@inheritDoc}
*/
public int getMaxActive() {
return pool.getMaxActive();
}
/**
* {@inheritDoc}
*/
public void setMaxActive(int maxActive) {
pool.setMaxActive(maxActive);
}
/**
* {@inheritDoc}
*/
public void setMaxActivePerServer(int maxActivePerServer) {
pool.setMaxActivePerServer(maxActivePerServer);
}
/**
* {@inheritDoc}
*/
public int getMaxActivePerServer() {
return pool.getMaxActivePerServer();
}
/**
* {@inheritDoc}
*/
public int getMaxIdle() {
return pool.getMaxIdle();
}
/**
* {@inheritDoc}
*/
public void setMaxIdle(int maxIdle) {
pool.setMaxIdle(maxIdle);
}
/**
* {@inheritDoc}
*/
public int getNumActive() {
return pool.getNumActive();
}
/**
* {@inheritDoc}
*/
public int getNumIdle() {
return pool.getNumIdle();
}
/**
* {@inheritDoc}
*/
public List<String> getActiveConnectionInfos() {
return pool.getActiveConnectionInfos();
}
/**
* {@inheritDoc}
*/
public List<String> getIdleConnectionInfos() {
return pool.getIdleConnectionInfos();
}
/**
* {@inheritDoc}
*/
public int getNumCreated() {
return pool.getNumCreated();
}
/**
* get the number of the creation errors
*
* @return the number of creation errors
*/
public int getNumCreationError() {
return pool.getNumCreationError();
}
/**
* {@inheritDoc}
*/
public int getNumDestroyed() {
return pool.getNumDestroyed();
}
/**
* {@inheritDoc}
*/
public int getNumTimeoutPooledMaxIdleTime() {
return pool.getNumTimeoutPooledMaxIdleTime();
}
/**
* {@inheritDoc}
*/
public int getNumTimeoutPooledMaxLifeTime() {
return pool.getNumTimeoutPooledMaxLifeTime();
}
/**
* get the current number of pending get operations to retrieve a resource
*
* @return the current number of pending get operations
*/
public int getNumPendingGet() {
return pool.getNumPendingGet();
}
public void close() {
pool.close();
}
public void destroy(IBlockingConnection resource) throws IOException {
if (resource instanceof BlockingConnection) {
NonBlockingConnectionPool.destroy(((BlockingConnection) resource).getDelegate());
}
resource.close();
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/BlockingConnectionPool.java | Java | art | 13,072 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* Delayed write IO handler
*
* @author grro@xsocket.org
*/
final class IoThrottledWriteHandler extends IoChainableHandler {
private static final Logger LOG = Logger.getLogger(IoThrottledWriteHandler.class.getName());
private static final int PERIOD_MILLIS = 500;
// write queue
private final IoQueue writeQueue = new IoQueue();
private final ArrayList<ByteBuffer> throttledSendQueue = new ArrayList<ByteBuffer>(1);
// timer handling
private int writeSize = Integer.MAX_VALUE;
private TimerTask delayedDelivererTask;
/**
* constructor
* @param successor the successor
*/
IoThrottledWriteHandler(IoChainableHandler successor) {
super(successor);
}
/**
* {@inheritDoc}
*/
public void init(IIoHandlerCallback callbackHandler) throws IOException {
setPreviousCallback(callbackHandler);
getSuccessor().init(callbackHandler);
}
/**
* {@inheritDoc}
*/
public boolean reset() {
throttledSendQueue.clear();
writeSize = Integer.MAX_VALUE;
if (delayedDelivererTask != null) {
delayedDelivererTask.cancel();
delayedDelivererTask = null;
}
return super.reset();
}
/**
* set the write rate in sec
*
* @param writeRateSec the write rate
*/
void setWriteRateSec(int writeRateSec) {
writeSize = (PERIOD_MILLIS * writeRateSec) / 1000;
if (writeSize <= 0) {
writeSize = 1;
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("write transfer rate set to " + writeRateSec);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getPendingWriteDataSize() {
return getSendQueueSize() + super.getPendingWriteDataSize();
}
@Override
public boolean hasDataToSend() {
return ((getSendQueueSize() > 0) || super.hasDataToSend());
}
@SuppressWarnings("unchecked")
private int getSendQueueSize() {
int size = 0;
ArrayList<ByteBuffer> copy = null;
synchronized (throttledSendQueue) {
copy = (ArrayList<ByteBuffer>) throttledSendQueue.clone();
}
for (ByteBuffer buffer : copy) {
size += buffer.remaining();
}
return size;
}
/**
* {@inheritDoc}
*/
public void close(boolean immediate) throws IOException {
if (!immediate) {
hardFlush();
}
getSuccessor().close(immediate);
}
@Override
public void write(ByteBuffer[] buffers) throws ClosedChannelException, IOException {
writeQueue.append(buffers);
}
@Override
public void flush() throws IOException {
synchronized (writeQueue) {
for (ByteBuffer buffer : writeQueue.drain()) {
writeOutgoing(buffer);
}
}
}
private void writeOutgoing(ByteBuffer buffer) {
// append to delay queue
int size = buffer.remaining();
if (size > 0) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] add buffer (" + buffer.remaining() + " bytes) to delay queue");
}
synchronized (throttledSendQueue) {
throttledSendQueue.add(buffer);
}
}
// create delivery task if not exists
if (delayedDelivererTask == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] delay delivery task is null. Starting task (period=" + DataConverter.toFormatedDuration(PERIOD_MILLIS) + ")");
}
delayedDelivererTask = new DeliveryTask(this);
IoProvider.getTimer().schedule(delayedDelivererTask, 0, PERIOD_MILLIS);
}
}
/**
* {@inheritDoc}
*/
public void hardFlush() throws IOException {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("flush all remaning data (" + getSendQueueSize() + ")");
}
write();
synchronized (throttledSendQueue) {
if (!throttledSendQueue.isEmpty()) {
ByteBuffer[] entries = throttledSendQueue.toArray(new ByteBuffer[throttledSendQueue.size()]);
throttledSendQueue.clear();
ByteBuffer[] buffers = new ByteBuffer[entries.length];
for (int i = 0; i < buffers.length; i++) {
buffers[i] = entries[i];
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] flushing " + buffers.length + " buffers of delay queue");
}
try {
IoThrottledWriteHandler.this.getSuccessor().write(buffers);
IoThrottledWriteHandler.this.getSuccessor().flush();
} catch (Exception e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured while writing. Reason: " + e.toString());
}
getSuccessor().close(true);
}
}
}
getSuccessor().hardFlush();
}
private static final class DeliveryTask extends TimerTask {
private WeakReference<IoThrottledWriteHandler> ioThrottledWriteHandlerRef = null;
public DeliveryTask(IoThrottledWriteHandler ioThrottledWriteHandler) {
ioThrottledWriteHandlerRef = new WeakReference<IoThrottledWriteHandler>(ioThrottledWriteHandler);
}
@Override
public void run() {
IoThrottledWriteHandler ioThrottledWriteHandler = ioThrottledWriteHandlerRef.get();
if (ioThrottledWriteHandler == null) {
cancel();
} else {
ioThrottledWriteHandler.writeChunk();
}
}
}
void writeChunk() {
int sizeToWrite = writeSize;
try {
synchronized (throttledSendQueue) {
while ((sizeToWrite > 0) && (!throttledSendQueue.isEmpty())) {
ByteBuffer buffer = throttledSendQueue.remove(0);
if (buffer.remaining() > sizeToWrite) {
int saveLimit = buffer.limit();
buffer.limit(sizeToWrite);
ByteBuffer newBuffer = buffer.slice();
buffer.position(buffer.limit());
buffer.limit(saveLimit);
throttledSendQueue.add(0, buffer.slice());
buffer = newBuffer;
}
sizeToWrite -= buffer.remaining();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] release " + buffer.remaining() + " bytes from delay queue (remaining size = " + getSendQueueSize() + ")");
}
getSuccessor().write(new ByteBuffer[] { buffer });
getSuccessor().flush();
}
}
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured by writing queue data " + DataConverter.toString(ioe));
}
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return this.getClass().getSimpleName() + "(pending delayQueueSize=" + DataConverter.toFormatedBytesSize(getPendingWriteDataSize()) + ") ->" + "\r\n" + getSuccessor().toString();
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IoThrottledWriteHandler.java | Java | art | 8,008 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
/**
* Defines that the {@link IHandler} is connection scoped.
* A connection scoped handler will be used by the server
* as a prototype. That means, for each new incoming connection
* this handler will be cloned and the cloned handler will be assigned
* to the new connection to perform the handling. <br>
* The prototype handler will never be used to handle
* connections. It will only be used as a clone base. <br><br>
*
* By having such a dedicate handler instance for each connection,
* all variables of the cloned handler become session specific
* variables. <br><br>
*
* Take care by implementing the clone interface. Just calling the
* super.clone() method within the handler clone method lead to
* a shallow copy. That means all fields that refer to other
* objects will point to the same objects in both the original and
* the clone. To avoid side effects a deep copy has to be implemented.
* All attributes beside primitives, immutable or global manager/service
* references has also to be cloned
* <br>
* E.g.
* <pre>
*
* class MyHandler implements IDataHandler, IConnectionScoped {
* private int state = 0;
* private ConnectionRecordQueue recordQueue = new ConnectionRecordQueue();
* ...
*
*
* public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException {
* ...
* return true;
* }
*
*
* @Override
* public Object clone() throws CloneNotSupportedException {
* MyHandler copy = (MyHandler) super.clone();
* copy.recordQueue = new ConnectionRecordQueue(); // deep "clone"
* return copy;
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public interface IConnectionScoped extends Cloneable {
/**
* {@inheritDoc}
*/
Object clone() throws CloneNotSupportedException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IConnectionScoped.java | Java | art | 2,999 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
/**
* Handles idle timeout. The timeouts will be defined by the server. To modify the timeouts
* the proper server methods has to be called. E.g.<br>
* <pre>
* ...
* IServer server = new Server(new MyHandler());
* server.setIdleTimeoutMillis(60 * 1000);
* ConnectionUtils.start(server);
* ...
*
*
* class MyHandler implements IIdleTimeoutHandler {
*
* public boolean onIdleTimeout(INonBlockingConnection connection) throws IOException {
* ...
* connection.close();
* return true; // true -> event has been handled (by returning false xSocket will close the connection)
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public interface IIdleTimeoutHandler extends IHandler {
/**
* handles the idle timeout.
*
* @param connection the underlying connection
* @return true if the timeout event has been handled (in case of false the connection will be closed by the server)
* @throws IOException if an error occurs. Throwing this exception causes that the underlying connection will be closed.
*/
boolean onIdleTimeout(INonBlockingConnection connection) throws IOException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IIdleTimeoutHandler.java | Java | art | 2,300 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
/**
* A connection (session) between two endpoints. It encapsulates the underlying socket channel. <br><br>
*
*
* @author grro@xsocket.org
*/
public interface IConnection extends Closeable {
public static final String INITIAL_DEFAULT_ENCODING = "UTF-8";
public static final String SO_SNDBUF = "SOL_SOCKET.SO_SNDBUF";
public static final String SO_RCVBUF = "SOL_SOCKET.SO_RCVBUF";
public static final String SO_REUSEADDR = "SOL_SOCKET.SO_REUSEADDR";
public static final String SO_KEEPALIVE = "SOL_SOCKET.SO_KEEPALIVE";
public static final String SO_LINGER = "SOL_SOCKET.SO_LINGER";
public static final String TCP_NODELAY = "IPPROTO_TCP.TCP_NODELAY";
static final String SO_TIMEOUT = "SOL_SOCKET.SO_TIMEOUT";
public static final long MAX_TIMEOUT_MILLIS = Long.MAX_VALUE;
public static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = MAX_TIMEOUT_MILLIS;
public static final long DEFAULT_IDLE_TIMEOUT_MILLIS = MAX_TIMEOUT_MILLIS;
public enum FlushMode { SYNC, ASYNC };
public static final FlushMode DEFAULT_FLUSH_MODE = FlushMode.SYNC;
public static final boolean DEFAULT_AUTOFLUSH = true;
/**
* returns the id
*
* @return id
*/
String getId();
/**
* returns true id connection is server side
*
* @return true, if is server side
*/
boolean isServerSide();
/**
* returns, if the connection is open. <br><br>
*
* Please note, that a connection could be closed, but reading of already
* received (and internally buffered) data would not fail. See also
* {@link IDataHandler#onData(INonBlockingConnection)}
*
*
* @return true if the connection is open
*/
boolean isOpen();
/**
* returns the local port
*
* @return the local port
*/
int getLocalPort();
/**
* returns the local address
*
* @return the local IP address or InetAddress.anyLocalAddress() if the socket is not bound yet.
*/
InetAddress getLocalAddress();
/**
* returns the remote address
*
* @return the remote address
*/
InetAddress getRemoteAddress();
/**
* returns the port of the remote end point
*
* @return the remote port
*/
int getRemotePort();
/**
* returns the idle timeout in millis.
*
* @return idle timeout in millis
*/
long getIdleTimeoutMillis();
/**
* sets the idle timeout in millis
*
* @param timeoutInSec idle timeout in millis
*/
void setIdleTimeoutMillis(long timeoutInMillis);
/**
* gets the connection timeout
*
* @return connection timeout
*/
long getConnectionTimeoutMillis();
/**
* sets the max time for a connections. By
* exceeding this time the connection will be
* terminated
*
* @param timeoutSec the connection timeout in millis
*/
void setConnectionTimeoutMillis(long timeoutMillis);
/**
* returns the remaining time before a idle timeout occurs
*
* @return the remaining time
*/
long getRemainingMillisToIdleTimeout();
/**
* returns the remaining time before a connection timeout occurs
*
* @return the remaining time
*/
long getRemainingMillisToConnectionTimeout();
/**
* sets the value of a option. <br><br>
*
* A good article for tuning can be found here {@link http://www.onlamp.com/lpt/a/6324}
*
* @param name the name of the option
* @param value the value of the option
* @throws IOException In an I/O error occurs
*/
void setOption(String name, Object value) throws IOException;
/**
* returns the value of a option
*
* @param name the name of the option
* @return the value of the option
* @throws IOException In an I/O error occurs
*/
Object getOption(String name) throws IOException;
/**
* Returns an unmodifiable map of the options supported by this end point.
*
* The key in the returned map is the name of a option, and its value
* is the type of the option value. The returned map will never contain null keys or values.
*
* @return An unmodifiable map of the options supported by this channel
*/
@SuppressWarnings("unchecked")
java.util.Map<String, Class> getOptions();
/**
* Attaches the given object to this connection
*
* @param obj The object to be attached; may be null
* @return The previously-attached object, if any, otherwise null
*/
void setAttachment(Object obj);
/**
* Retrieves the current attachment.
*
* @return The object currently attached to this key, or null if there is no attachment
*/
Object getAttachment();
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IConnection.java | Java | art | 5,792 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.Flushable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.concurrent.Executor;
import org.xsocket.IDataSink;
import org.xsocket.IDataSource;
import org.xsocket.MaxReadSizeExceededException;
/**
* A connection which accesses the underlying channel in a non-blocking manner. <br><br>
*
* @author grro@xsocket.org
*/
public interface INonBlockingConnection extends IConnection, IDataSource, IDataSink, GatheringByteChannel, ReadableByteChannel, WritableByteChannel, Flushable {
public static final int UNLIMITED = Integer.MAX_VALUE;
/**
* set the connection handler. <br><br>
*
* @param handler the handler
* @throws IOException If some other I/O error occurs
*/
void setHandler(IHandler handler) throws IOException;
/**
* gets the connection handler
*
* @return the handler
*
*/
IHandler getHandler();
/**
* gets the encoding (used by string related methods like write(String) ...)
*
* @return the encoding
*/
String getEncoding();
/**
* sets the encoding (used by string related methods like write(String) ...)
*
* @param encoding the encoding
*/
void setEncoding(String encoding);
/**
* set autoflush. If autoflush is activated, each write call
* will cause a flush. <br><br>
*
* @param autoflush true if autoflush should be activated
*/
void setAutoflush(boolean autoflush);
/**
* get autoflush
*
* @return true, if autoflush is activated
*/
boolean isAutoflush();
/**
* flush the send buffer. The method call will block until
* the outgoing data has been flushed into the underlying
* os-specific send buffer.
*
*
* @throws IOException If some other I/O error occurs
* @throws SocketTimeoutException If the timeout has been reached
* @throws ClosedChannelException if the underlying channel is closed
*/
void flush() throws ClosedChannelException, IOException, SocketTimeoutException;
/**
* returns if secured mode is activateable
* @return true, if secured mode is activateable
*/
boolean isSecuredModeActivateable();
/**
* ad hoc activation of a secured mode (SSL). By performing of this
* method all remaining data to send will be flushed.
* After this all data will be sent and received in the secured mode
*
* @throws IOException If some other I/O error occurs
*/
void activateSecuredMode() throws IOException;
/**
* ad hoc deactivation of a secured mode (SSL). By performing of this
* method all remaining data to send will be flushed.
* After this all data will be sent and received in the plain mode
*
* @throws IOException If some other I/O error occurs
*/
void deactivateSecuredMode() throws IOException;
/**
* returns if the connection is in secured mode
* @return true, if the connection is in secured mode
*/
boolean isSecure();
/**
* returns the size of the data which have already been written, but not
* yet transferred to the underlying socket.
*
* @return the size of the pending data to write
*/
int getPendingWriteDataSize();
/**
* suspend receiving data from the underlying subsystem
*
* @throws IOException If some other I/O error occurs
*/
void suspendReceiving() throws IOException;
/**
* resume receiving data from the underlying subsystem
*
* @throws IOException If some other I/O error occurs
*/
void resumeReceiving() throws IOException;
/**
* returns true if receiving is suspended
*
* @return true, if receiving is suspended
*/
boolean isReceivingSuspended();
/**
* write a message
*
* @param message the message to write
* @param encoding the encoding which should be used th encode the chars into byte (e.g. `US-ASCII` or `UTF-8`)
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(String message, String encoding) throws IOException, BufferOverflowException;
/**
* writes a byte buffer array. Typically this write mthod will be used in async flush mode
*
* @param buffers the buffers to write
* @param writeCompletionHandler the completionHandler
* @throws IOException If some I/O error occurs
*/
void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a byte buffer. Typically this write mthod will be used in async flush mode
*
* @param buffer the buffer to write
* @param writeCompletionHandler the completionHandler
* @throws IOException If some I/O error occurs
*/
void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a byte buffer array. Typically this write mthod will be used in async flush mode
*
* @param srcs the buffers
* @param offset the offset
* @param length the length
* @param writeCompletionHandler the completionHandler
* @throws IOException If some I/O error occurs
*/
void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a list of bytes to the data sink. Typically this write mthod will be used in async flush mode
*
* @param buffers the bytes to write
* @param writeCompletionHandler the completionHandler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes bytes to the data sink. Typically this write mthod will be used in async flush mode
*
* @param bytes the bytes to write
* @param writeCompletionHandler the completion handler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes bytes to the data sink. Typically this write mthod will be used in async flush mode
*
* @param bytes the bytes to write
* @param offset the offset of the sub array to be used; must be non-negative and no larger than array.length. The new buffer`s position will be set to this value.
* @param length the length of the sub array to be used; must be non-negative and no larger than array.length - offset. The new buffer`s limit will be set to offset + length.
* @param writeCompletionHandler the completion handler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* writes a message. Typically this write mthod will be used in async flush mode
*
* @param message the message to write
* @param encoding the encoding which should be used th encode the chars into byte (e.g. `US-ASCII` or `UTF-8`)
* @param writeCompletionHandler the completion handler
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException;
/**
* returns the ByteBuffers to the <i>top</i> of the read queue.
*
* @param buffers the buffers to return
* @throws IOException if an exception occurs
*/
void unread(ByteBuffer[] buffers) throws IOException;
/**
* returns the ByteBuffer to the <i>top</i> of the read queue.
*
* @param buffer the buffer to return
* @throws IOException if an exception occurs
*/
void unread(ByteBuffer buffer) throws IOException;
/**
* returns the bytes to the <i>top</i> of the read queue.
*
* @param bytes the bytes to return
* @throws IOException if an exception occurs
*/
void unread(byte[] bytes) throws IOException;
/**
* returns the text to the <i>top</i> of the read queue.
*
* @param text the text to return
* @throws IOException if an exception occurs
*/
void unread(String text) throws IOException;
/**
* read a ByteBuffer by using a delimiter. The default encoding will be used to decode the delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @return the ByteBuffer
* @throws BufferUnderflowException If not enough data is available
* @throws IOException If some other I/O error occurs
*/
ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException;
/**
* read a ByteBuffer by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding of the delimiter
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the ByteBuffer
* @throws BufferUnderflowException If not enough data is available
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
*/
ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException;
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @return the read bytes
* @throws BufferUnderflowException If not enough data is available
* @throws IOException If some other I/O error occurs
*/
byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException;
/**
* read a byte array by using a delimiter
*
* For performance reasons, the ByteBuffer readByteBuffer method is
* generally preferable to get bytes
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the read bytes
* @throws BufferUnderflowException If not enough data is available
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
*/
byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException;
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @return the string
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException If not enough data is available
* @throws UnsupportedEncodingException if the given encoding is not supported
*/
String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException;
/**
* read a string by using a delimiter
*
* @param delimiter the delimiter
* @param encoding the encoding to use
* @param maxLength the max length of bytes that should be read. If the limit is exceeded a MaxReadSizeExceededException will been thrown
* @return the string
* @throws BufferUnderflowException If not enough data is available
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
* @throws IOException If some other I/O error occurs
* @throws UnsupportedEncodingException If the given encoding is not supported
*/
String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException;
/**
* read a string by using a length definition
*
* @param length the amount of bytes to read.
* @param encoding the encoding to use
* @return the string
* @throws IOException If some other I/O error occurs
* @throws BufferUnderflowException If not enough data is available
* @throws UnsupportedEncodingException if the given encoding is not supported
* @throws IllegalArgumentException, if the length parameter is negative
*/
String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException;
/**
* transfer the data of the file channel to this data sink
*
* @param source the source channel
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
long transferFrom(FileChannel source) throws IOException, BufferOverflowException;
/**
* Returns the index of the first occurrence of the given string.
*
* @param str any string
* @return if the string argument occurs as a substring within this object, then
* the index of the first character of the first such substring is returned;
* if it does not occur as a substring, -1 is returned.
* @throws IOException If some other I/O error occurs
*/
int indexOf(String str) throws IOException;
/**
* Returns the index of the first occurrence of the given string.
*
* @param str any string
* @param encoding the encoding to use
* @return if the string argument occurs as a substring within this object, then
* the index of the first character of the first such substring is returned;
* if it does not occur as a substring, -1 is returned.
* @throws IOException If some other I/O error occurs
* @throws MaxReadSizeExceededException If the max read length has been exceeded and the delimiter hasn�t been found
*/
int indexOf(String str, String encoding) throws IOException;
/**
* set the send delay time. Data to write will be buffered
* internally and be written to the underlying subsystem
* based on the given write rate.
* The write methods will <b>not</b> block for this time. <br>
*
* By default the write transfer rate is set with UNLIMITED <br><br>
*
* Reduced write transfer is only supported for FlushMode.ASYNC. see
* {@link INonBlockingConnection#setFlushmode(org.xsocket.connection.IConnection.FlushMode))}
*
* @param bytesPerSecond the transfer rate of the outgoing data
* @throws ClosedChannelException If the underlying socket is already closed
* @throws IOException If some other I/O error occurs
*/
void setWriteTransferRate(int bytesPerSecond) throws ClosedChannelException, IOException;
/**
* gets the send delay time.
*
* @return the transfer rate of the outgoing data
* @throws ClosedChannelException If the underlying socket is already closed
* @throws IOException If some other I/O error occurs
*/
int getWriteTransferRate() throws ClosedChannelException, IOException;
/**
* set the read rate. By default the read transfer rate is set with UNLIMITED <br><br>
*
* @param bytesPerSecond the transfer rate of the outgoing data
* @throws ClosedChannelException If the underlying socket is already closed
* @throws IOException If some other I/O error occurs
*/
// public void setReadTransferRate(int bytesPerSecond) throws ClosedChannelException, IOException;
/**
* get the number of available bytes to read
*
* @return the number of available bytes, possibly zero, or -1 if the channel has reached end-of-stream
*/
int available() throws IOException;
/**
* get the version of read buffer. The version number increases, if
* the read buffer queue has been modified
*
* @return the version of the read buffer
* @throws IOException If some other I/O error occurs
*/
int getReadBufferVersion() throws IOException;
/**
* return if the data source is open. Default is true
* @return true, if the data source is open
*/
boolean isOpen();
/**
* return the worker pool which is used to process the call back methods
*
* @return the worker pool
*/
Executor getWorkerpool();
/**
* sets the worker pool which is used to process the call back methods
*
* @param workerpool the workerpool
*/
void setWorkerpool(Executor workerpool);
/**
* Resets to the marked write position. If the connection has been marked,
* then attempt to reposition it at the mark.
*
* @return true, if reset was successful
*/
boolean resetToWriteMark();
/**
* Resets to the marked read position. If the connection has been marked,
* then attempt to reposition it at the mark.
*
* @return true, if reset was successful
*/
boolean resetToReadMark();
/**
* Marks the write position in the connection.
*/
void markWritePosition();
/**
* Marks the read position in the connection. Subsequent calls to resetToReadMark() will attempt
* to reposition the connection to this point.
*
*/
void markReadPosition();
/**
* remove the read mark
*/
void removeReadMark();
/**
* remove the write mark
*/
void removeWriteMark();
/**
* get the max app read buffer size. If the read buffer size exceeds this limit the
* connection will stop receiving data. The read buffer size can be higher the limit
* (max size = maxReadBufferThreshold + socket read buffer size * 2)
*
* @return the max read buffer threshold
*/
int getMaxReadBufferThreshold();
/**
* set the max app read buffer threshold
*
* @param maxSize the max read buffer threshold
*/
void setMaxReadBufferThreshold(int size);
/**
* sets the flush mode. If the flush mode is set toASYNC (default is SYNC),
* the data will be transferred to the underlying connection in a asynchronous way. <br> <br>
* By using the {@link WritableByteChannel} interface methods write(ByteBuffer) and
* write(ByteBuffer[]) some restriction exits. Calling such a write method in mode
* ASYNC causes that the byte buffer will be read asynchronously by the internal I/O thread.
* If the byte buffer will be accessed (reused) after calling the write method, race
* conditions will occur. The write(ByteBuffer) and write(ByteBuffer[]) should only
* called in ASNC mode, if the byte buffer will not be accessed (reused)
* after the write operation. E.g.
*
* <pre>
*
* File file = new File(filename);
* RandomAccessFile raf = new RandomAccessFile(file, "r");
* ReadableByteChannel fc = raf.getChannel();
*
* INonBlockingConnection connection = new NonBlockingConnection(host, port);
*
* // using a copy buffer (which will be reused for the read operations)
* // requires FlushMode SYNC which is default (for writing)!
* ByteBuffer copyBuffer = ByteBuffer.allocate(4096);
*
* int read = 0;
* while (read >= 0) {
* // read channel
* read = fc.read(copyBuffer);
* copyBuffer.flip();
*
* if (read > 0) {
* // write channel
* connection.write(copyBuffer);
* if (copyBuffer.hasRemaining()) {
* copyBuffer.compact();
* } else {
* copyBuffer.clear();
* }
* }
* }
* </pre>
*
* @param flushMode {@link FlushMode#ASYNC} if flush should be performed asynchronous,
* {@link FlushMode#SYNC} if flush should be perform synchronous
*/
void setFlushmode(FlushMode flushMode);
/**
* return the flush mode
* @return the flush mode
*/
FlushMode getFlushmode();
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/INonBlockingConnection.java | Java | art | 23,085 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.nio.ByteBuffer;
import java.util.ArrayList;
/**
*
* @author grro@xsocket.org
*/
final class IoQueue {
/*
* the implementation is driven by the assumption, that
* in most cases just one buffer or one buffer array
* will be enqueued
*/
private ByteBuffer[] buffers = null;
private ByteBuffer[] leased = null;
/**
* returns true, if empty
*
* @return true, if empty
*/
public synchronized boolean isEmpty() {
if ((buffers == null) && (leased == null)) {
return true;
} else {
return (getSize() == 0);
}
}
/**
* return the current size
*
* @return the current size
*/
public synchronized int getSize() {
int size = 0;
if (buffers != null) {
for (int i = 0; i < buffers.length; i++) {
if (buffers[i] != null) {
size += buffers[i].remaining();
}
}
}
if (leased != null) {
for (int i = 0; i < leased.length; i++) {
if (leased[i] != null) {
size += leased[i].remaining();
}
}
}
return size;
}
/**
* append a byte buffer to this queue.
*
* @param data the ByteBuffer to append
*/
public synchronized void append(ByteBuffer data) {
if ((data == null) || (data.remaining() == 0)) {
return;
}
if (buffers == null) {
buffers = new ByteBuffer[1];
buffers[0] = data;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + 1];
System.arraycopy(buffers, 0, newBuffers, 0, buffers.length);
newBuffers[buffers.length] = data;
buffers = newBuffers;
}
}
/**
* append a list of byte buffer to this queue. By adding a list,
* the list becomes part of to the buffer, and should not be modified outside the buffer
* to avoid side effects
*
* @param bufs the list of ByteBuffer
*/
public synchronized void append(ByteBuffer[] data) {
if (data == null) {
return;
}
if (buffers == null) {
buffers = data;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + data.length];
System.arraycopy(buffers, 0, newBuffers, 0, buffers.length);
System.arraycopy(data, 0, newBuffers, buffers.length, data.length);
buffers = newBuffers;
}
}
/**
* add the given ByteBuffer array into the head of the queue
*
* @param bufs the list of ByteBuffer
*/
public synchronized void addFirst(ByteBuffer[] data) {
if (data == null) {
return;
}
if (buffers == null) {
buffers = data;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + data.length];
System.arraycopy(data, 0, newBuffers, 0, data.length);
System.arraycopy(buffers, 0, newBuffers, data.length, buffers.length);
buffers = newBuffers;
}
}
private void addFirst(ByteBuffer data) {
if (data == null) {
return;
}
if (buffers == null) {
buffers = new ByteBuffer[] { data };
} else {
ByteBuffer[] newBuffers = new ByteBuffer[buffers.length + 1];
newBuffers[0] = data;
System.arraycopy(buffers, 0, newBuffers, 1, buffers.length);
buffers = newBuffers;
}
}
/**
* drain this queue
*
* @return the contained ByteBuffer array or <code>null</code>
*/
public synchronized ByteBuffer[] drain() {
ByteBuffer[] result = buffers;
buffers = null;
return result;
}
/**
* lease
*
* @param maxSize max size to drain if buffer array will be returned
*
* @return the contained ByteBuffer array or <code>null</code>
*/
public synchronized ByteBuffer[] lease(int maxSize) {
if ((buffers != null) && (buffers.length == 1)) {
ByteBuffer[] data = drain();
leased = data;
return data;
}
if (getSize() <= maxSize) {
ByteBuffer[] data = drain();
leased = data;
return data;
} else {
ArrayList<ByteBuffer> result = new ArrayList<ByteBuffer>();
int remaining = maxSize;
for (int i = 0; i < buffers.length; i++) {
int size = buffers[i].remaining();
if (size > 0) {
if (size <= remaining) {
result.add(buffers[i]);
remaining -= size;
if (remaining == 0) {
removeBuffersFromHead(i + 1);
break;
}
} else {
int savedPos = buffers[i].position();
int savedLimit = buffers[i].limit();
buffers[i].limit(savedPos + remaining);
ByteBuffer buffer = buffers[i].slice();
result.add(buffer);
buffers[i].limit(savedLimit);
buffers[i].position(savedPos + remaining);
addFirst(buffers[i]);
removeBuffersFromHead(i + 1);
break;
}
}
}
ByteBuffer[] data = result.toArray(new ByteBuffer[result.size()]);
leased = data;
return data;
}
}
public synchronized void removeLeased() {
leased = null;
}
private void removeBuffersFromHead(int count) {
int newSize = buffers.length - count;
if (newSize == 0) {
buffers = null;
} else {
ByteBuffer[] newBuffers = new ByteBuffer[newSize];
System.arraycopy(buffers, count, newBuffers, 0, newBuffers.length);
buffers = newBuffers;
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IoQueue.java | Java | art | 6,435 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* a Memory Manager implementation
*
* @author grro@xsocket.org
*/
final class IoSynchronizedMemoryManager extends AbstractMemoryManager {
private static final Logger LOG = Logger.getLogger(IoSynchronizedMemoryManager.class.getName());
private final List<SoftReference<ByteBuffer>> memoryBuffer = new ArrayList<SoftReference<ByteBuffer>>();
/**
* constructor
*
* @param allocationSize the buffer to allocate
* @param preallocate true, if buffer should be preallocated
* @param minPreallocatedBufferSize the minimal buffer size
* @param useDirectMemory true, if direct memory should be used
*/
private IoSynchronizedMemoryManager(int preallocationSize, boolean preallocate, int minPreallocatedBufferSize, boolean useDirectMemory) {
super(preallocationSize, preallocate, minPreallocatedBufferSize, useDirectMemory);
}
public static IoSynchronizedMemoryManager createPreallocatedMemoryManager(int preallocationSize, int minBufferSze, boolean useDirectMemory) {
return new IoSynchronizedMemoryManager(preallocationSize, true, minBufferSze, useDirectMemory);
}
public static IoSynchronizedMemoryManager createNonPreallocatedMemoryManager(boolean useDirectMemory) {
return new IoSynchronizedMemoryManager(0, false, 1, useDirectMemory);
}
/**
* return the free memory size
*
* @return the free memory size
*/
public int getCurrentSizePreallocatedBuffer() {
int size = 0;
synchronized (memoryBuffer) {
for (SoftReference<ByteBuffer> bufferRef: memoryBuffer) {
ByteBuffer buffer = bufferRef.get();
if (buffer != null) {
size += buffer.remaining();
}
}
}
return size;
}
/**
* recycle free memory
*
* @param buffer the buffer to recycle
*/
public void recycleMemory(ByteBuffer buffer) {
if (isPreallocationMode()) {
int remaining = buffer.remaining();
if (remaining >= getPreallocatedMinBufferSize()) {
synchronized (memoryBuffer) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("recycling " + DataConverter.toFormatedBytesSize(buffer.remaining()));
}
memoryBuffer.add(new SoftReference<ByteBuffer>(buffer));
}
}
}
}
public void preallocate() {
}
/**
* acquire free memory
*/
public ByteBuffer acquireMemoryStandardSizeOrPreallocated(int standardSize) throws IOException {
ByteBuffer buffer = null;
if (isPreallocationMode()) {
synchronized (memoryBuffer) {
if (!memoryBuffer.isEmpty()) {
SoftReference<ByteBuffer> freeBuffer = memoryBuffer.remove(0);
buffer = freeBuffer.get();
// size sufficient?
if ((buffer != null) && (buffer.limit() < getPreallocatedMinBufferSize())) {
buffer = null;
}
}
}
if (buffer == null) {
buffer = newBuffer(standardSize);
}
return buffer;
} else {
return newBuffer(standardSize);
}
}
} | zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IoSynchronizedMemoryManager.java | Java | art | 4,364 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.xsocket.DataConverter;
/**
* SSL io handler
*
* @author grro@xsocket.org
*/
final class IoSSLHandler extends IoChainableHandler implements IoSSLProcessor.EventHandler {
private static final Logger LOG = Logger.getLogger(IoSSLHandler.class.getName());
// receive & send queue
private final IoQueue outAppDataQueue = new IoQueue();
private final IoQueue outNetDataQueue = new IoQueue();
// sync write support
private final PendingWriteMap pendingWriteMap = new PendingWriteMap();
private final IOEventHandler ioEventHandler = new IOEventHandler();
// ssl stuff
private final IoSSLProcessor sslProcessor;
private final AtomicBoolean isSSLConnected = new AtomicBoolean(false);
private final Object initGuard = new Object();
private final boolean isClientMode;
private IOException readException;
/**
* constructor
*
* @param successor the successor
* @param sslContext the ssl context to use
* @param isClientMode true, if is in client mode
* @param memoryManager the memory manager to use
* @throws IOException If some other I/O error occurs
*/
IoSSLHandler(IoChainableHandler successor, SSLContext sslContext,boolean isClientMode, AbstractMemoryManager memoryManager) throws IOException {
super(successor);
this.isClientMode = isClientMode;
sslProcessor = new IoSSLProcessor(sslContext, isClientMode, memoryManager, this);
}
public void init(IIoHandlerCallback callbackHandler) throws IOException {
setPreviousCallback(callbackHandler);
getSuccessor().init(ioEventHandler);
startSSL();
}
/**
* {@inheritDoc}
*/
public boolean reset() {
outAppDataQueue.drain();
outNetDataQueue.drain();
pendingWriteMap.clear();
return super.reset();
}
/**
* {@inheritDoc}
*/
public boolean isSecure() {
return isSSLConnected.get();
}
/**
* {@inheritDoc}
*/
public void setPreviousCallback(IIoHandlerCallback callbackHandler) {
super.setPreviousCallback(callbackHandler);
getSuccessor().setPreviousCallback(ioEventHandler);
}
/**
* {@inheritDoc}
*/
@Override
public int getPendingWriteDataSize() {
return outAppDataQueue.getSize() + super.getPendingWriteDataSize();
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasDataToSend() {
return (!outAppDataQueue.isEmpty() || super.hasDataToSend());
}
/**
* start the ssl mode
*
* @throws IOException If some other I/O error occurs
*/
void startSSL() throws IOException {
if (!isSSLConnected.get()) {
sslProcessor.start();
}
if (isClientMode) {
synchronized (initGuard) {
while (!isSSLConnected.get()) {
if (readException != null) {
IOException ex = readException;
readException = null;
throw ex;
}
try {
if (ConnectionUtils.isDispatcherThread()) {
LOG.warning("try to initialize ssl client within xSocket I/O thread (" + Thread.currentThread().getName() + "). This will cause a deadlock");
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] waiting until ssl handeshake has been finished");
}
initGuard.wait();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] ssl handeshake has been finished continue processing");
}
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
}
}
}
public void onHandshakeFinished() throws IOException {
if (!isSSLConnected.get()) {
if (LOG.isLoggable(Level.FINE) && (isClientMode)) {
LOG.fine("[" + getId() + "] wakeup waiting processes for handeshake");
}
isSSLConnected.set(true);
synchronized (initGuard) {
initGuard.notifyAll();
}
getPreviousCallback().onConnect();
}
boolean isEncryptRequired = false;
synchronized (outAppDataQueue) {
if (!outAppDataQueue.isEmpty()) {
sslProcessor.addOutAppData(outAppDataQueue.drain());
isEncryptRequired = true;
}
}
if (isEncryptRequired) {
sslProcessor.encrypt();
}
}
/**
* {@inheritDoc}
*/
public void close(boolean immediate) throws IOException {
if (!immediate) {
hardFlush();
}
getSuccessor().close(immediate);
}
@Override
public void write(ByteBuffer[] buffers) throws ClosedChannelException, IOException {
outAppDataQueue.append(buffers);
flush();
}
@Override
public void flush() throws IOException {
synchronized (outAppDataQueue) {
if (!outAppDataQueue.isEmpty()) {
ByteBuffer[] dataToEncrypt = outAppDataQueue.drain();
if (LOG.isLoggable(Level.FINE)) {
int size = 0;
List<ByteBuffer> dataToEncryptCopy = new ArrayList<ByteBuffer>();
for (ByteBuffer buffer : dataToEncrypt) {
dataToEncryptCopy.add(buffer.duplicate());
size += buffer.remaining();
}
LOG.fine("encrypting out app data (" + size + "): " + DataConverter.toTextOrHexString(dataToEncryptCopy.toArray(new ByteBuffer[dataToEncryptCopy.size()]), "US-ASCII", 500));
}
sslProcessor.addOutAppData(dataToEncrypt);
}
}
sslProcessor.encrypt();
}
/**
* {@inheritDoc}
*/
public void hardFlush() throws IOException {
flush();
}
private void readIncomingEncryptedData(ByteBuffer[] inNetDataList) throws ClosedChannelException, IOException {
if (LOG.isLoggable(Level.FINE)) {
int size = 0;
for (ByteBuffer buffer : inNetDataList) {
size += buffer.remaining();
}
LOG.fine("[" + getId() + "] " + size + " encrypted data received");
}
if (inNetDataList != null) {
sslProcessor.decrypt(inNetDataList);
}
}
public void onDestroy() throws IOException {
close(true);
}
public void onInboundClosed() throws IOException {
close(true);
}
/**
* has to be called within a synchronized context
*/
public void onDataDecrypted(ByteBuffer decryptedBuffer) {
if ((decryptedBuffer == null) || !decryptedBuffer.hasRemaining()) {
return;
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("in app data decrypted: " + DataConverter.toTextOrHexString(decryptedBuffer.duplicate(), "US-ASCII", 500));
}
getPreviousCallback().onData(new ByteBuffer[] { decryptedBuffer }, decryptedBuffer.remaining());
}
public void onPostDataDecrypted() {
getPreviousCallback().onPostData();
}
public void onDataEncrypted(ByteBuffer plainData, ByteBuffer encryptedData) throws IOException {
if (encryptedData.hasRemaining()) {
pendingWriteMap.add(plainData, encryptedData);
}
synchronized (outNetDataQueue) {
outNetDataQueue.append(encryptedData);
}
}
public void onPostDataEncrypted() throws IOException {
synchronized (outNetDataQueue) {
ByteBuffer[] data = outNetDataQueue.drain();
if (LOG.isLoggable(Level.FINE)) {
if (data != null) {
int size = 0;
for (ByteBuffer buffer : data) {
size += buffer.remaining();
}
LOG.fine("sending out app data (" + size + ")");
}
}
getSuccessor().write(data);
}
getSuccessor().flush();
}
private final class IOEventHandler implements IIoHandlerCallback {
public void onData(ByteBuffer[] data, int size) {
try {
readIncomingEncryptedData(data);
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured while receiving data. Reason: " + ioe.toString());
}
synchronized (initGuard) {
readException = ioe;
initGuard.notifyAll();
}
}
}
public void onPostData() {
}
public void onConnect() {
}
public void onConnectException(IOException ioe) {
getPreviousCallback().onConnectException(ioe);
}
public void onWriteException(IOException ioException, ByteBuffer data) {
getPreviousCallback().onWriteException(ioException, data);
}
public void onWritten(ByteBuffer data) {
ByteBuffer plainData = pendingWriteMap.getPlainIfWritten(data);
if (plainData != null) {
getPreviousCallback().onWritten(plainData);
} else {
// else case shouldn't occur, handle it nevertheless
getPreviousCallback().onWritten(data);
}
}
public void onDisconnect() {
sslProcessor.destroy();
getPreviousCallback().onDisconnect();
}
public void onConnectionAbnormalTerminated() {
getPreviousCallback().onConnectionAbnormalTerminated();
}
}
static final class PendingWriteMap {
private Map<ByteBuffer, List<ByteBuffer>> plainEncryptedMapping = new IdentityHashMap<ByteBuffer, List<ByteBuffer>>();
private Map<ByteBuffer, ByteBuffer> encryptedPlainMapping = new IdentityHashMap<ByteBuffer, ByteBuffer>();
public synchronized void add(ByteBuffer plain, ByteBuffer encrypted) {
// ignore system data (plain is empty)
if (plain.limit() > 0) {
List<ByteBuffer> encryptedList = plainEncryptedMapping.get(plain);
if (encryptedList == null) {
encryptedList = new ArrayList<ByteBuffer>();
plainEncryptedMapping.put(plain, encryptedList);
}
encryptedList.add(encrypted);
encryptedPlainMapping.put(encrypted, plain);
}
}
public synchronized ByteBuffer getPlainIfWritten(ByteBuffer encrypted) {
ByteBuffer plain = encryptedPlainMapping.remove(encrypted);
if (plain != null) {
List<ByteBuffer> encryptedList = plainEncryptedMapping.get(plain);
encryptedList.remove(encrypted);
if (encryptedList.isEmpty()) {
plainEncryptedMapping.remove(plain);
return plain;
}
}
return null;
}
public synchronized void clear() {
plainEncryptedMapping.clear();
encryptedPlainMapping.clear();
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/IoSSLHandler.java | Java | art | 11,533 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.concurrent.Executor;
import org.xsocket.MaxReadSizeExceededException;
/**
* Thread-safe wrapper of a NonBlockingConnection
*
* @author grro@xsocket.org
*/
final class SynchronizedNonBlockingConnection extends AbstractSynchronizedConnection implements INonBlockingConnection {
private final INonBlockingConnection delegate;
public SynchronizedNonBlockingConnection(INonBlockingConnection delegate) {
super(delegate);
this.delegate = delegate;
}
public void activateSecuredMode() throws IOException {
synchronized(delegate) {
delegate.activateSecuredMode();
}
}
public void deactivateSecuredMode() throws IOException {
synchronized(delegate) {
delegate.deactivateSecuredMode();
}
}
public int available() throws IOException {
synchronized(delegate) {
return delegate.available();
}
}
public void flush() throws ClosedChannelException, IOException, SocketTimeoutException {
synchronized(delegate) {
delegate.flush();
}
}
public String getEncoding() {
synchronized(delegate) {
return delegate.getEncoding();
}
}
public FlushMode getFlushmode() {
synchronized(delegate) {
return delegate.getFlushmode();
}
}
public IHandler getHandler() {
synchronized(delegate) {
return delegate.getHandler();
}
}
public int getMaxReadBufferThreshold() {
synchronized(delegate) {
return delegate.getMaxReadBufferThreshold();
}
}
public int getPendingWriteDataSize() {
synchronized(delegate) {
return delegate.getPendingWriteDataSize();
}
}
public int getReadBufferVersion() throws IOException {
synchronized(delegate) {
return delegate.getReadBufferVersion();
}
}
public Executor getWorkerpool() {
synchronized(delegate) {
return delegate.getWorkerpool();
}
}
public int getWriteTransferRate() throws ClosedChannelException, IOException {
synchronized(delegate) {
return delegate.getWriteTransferRate();
}
}
public int indexOf(String str) throws IOException {
synchronized(delegate) {
return delegate.indexOf(str);
}
}
public int indexOf(String str, String encoding) throws IOException {
synchronized(delegate) {
return delegate.indexOf(str, encoding);
}
}
public boolean isAutoflush() {
synchronized(delegate) {
return delegate.isAutoflush();
}
}
public boolean isReceivingSuspended() {
synchronized(delegate) {
return delegate.isReceivingSuspended();
}
}
public boolean isSecure() {
synchronized(delegate) {
return delegate.isSecure();
}
}
public boolean isSecuredModeActivateable() {
synchronized(delegate) {
return delegate.isSecuredModeActivateable();
}
}
public void markReadPosition() {
synchronized(delegate) {
delegate.markReadPosition();
}
}
public void markWritePosition() {
synchronized(delegate) {
delegate.markWritePosition();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter, encoding);
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter, encoding, maxLength);
}
}
public byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter, encoding);
}
}
public byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter, encoding, maxLength);
}
}
public String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter, encoding);
}
}
public String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter, encoding, maxLength);
}
}
public String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
synchronized(delegate) {
return delegate.readStringByLength(length, encoding);
}
}
public void removeReadMark() {
synchronized(delegate) {
delegate.removeReadMark();
}
}
public void removeWriteMark() {
synchronized(delegate) {
delegate.removeWriteMark();
}
}
public boolean resetToReadMark() {
synchronized(delegate) {
return delegate.resetToReadMark();
}
}
public boolean resetToWriteMark() {
synchronized(delegate) {
return delegate.resetToWriteMark();
}
}
public void resumeReceiving() throws IOException {
synchronized(delegate) {
delegate.resumeReceiving();
}
}
public void setAutoflush(boolean autoflush) {
synchronized(delegate) {
delegate.setAutoflush(autoflush);
}
}
public void setEncoding(String encoding) {
synchronized(delegate) {
delegate.setEncoding(encoding);
}
}
public void setFlushmode(FlushMode flushMode) {
synchronized(delegate) {
delegate.setFlushmode(flushMode);
}
}
public void setHandler(IHandler handler) throws IOException {
synchronized(delegate) {
delegate.setHandler(handler);
}
}
public void setMaxReadBufferThreshold(int size) {
synchronized(delegate) {
delegate.setMaxReadBufferThreshold(size);
}
}
public void setWorkerpool(Executor workerpool) {
synchronized(delegate) {
delegate.setWorkerpool(workerpool);
}
}
public void setWriteTransferRate(int bytesPerSecond) throws ClosedChannelException, IOException {
synchronized(delegate) {
delegate.setWriteTransferRate(bytesPerSecond);
}
}
public void suspendReceiving() throws IOException {
synchronized(delegate) {
delegate.suspendReceiving();
}
}
public long transferFrom(FileChannel source) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.transferFrom(source);
}
}
public void unread(ByteBuffer[] buffers) throws IOException {
synchronized(delegate) {
delegate.unread(buffers);
}
}
public void unread(ByteBuffer buffer) throws IOException {
synchronized(delegate) {
delegate.unread(buffer);
}
}
public void unread(byte[] bytes) throws IOException {
synchronized(delegate) {
delegate.unread(bytes);
}
}
public void unread(String text) throws IOException {
synchronized(delegate) {
delegate.unread(text);
}
}
public int write(String message, String encoding) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(message, encoding);
}
}
public void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(buffers, writeCompletionHandler);
}
}
public void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(buffer, writeCompletionHandler);
}
}
public void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(srcs, offset, length, writeCompletionHandler);
}
}
public void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(buffers, writeCompletionHandler);
}
}
public void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(bytes, writeCompletionHandler);
}
}
public void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(bytes, offset, length, writeCompletionHandler);
}
}
public void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException {
synchronized(delegate) {
delegate.write(message, encoding, writeCompletionHandler);
}
}
public int read(ByteBuffer buffer) throws IOException {
synchronized(delegate) {
return delegate.read(buffer);
}
}
public byte readByte() throws IOException {
synchronized(delegate) {
return delegate.readByte();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter) throws IOException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter);
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, int maxLength) throws IOException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readByteBufferByDelimiter(delimiter, maxLength);
}
}
public ByteBuffer[] readByteBufferByLength(int length) throws IOException {
synchronized(delegate) {
return delegate.readByteBufferByLength(length);
}
}
public byte[] readBytesByDelimiter(String delimiter) throws IOException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter);
}
}
public byte[] readBytesByDelimiter(String delimiter, int maxLength) throws IOException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readBytesByDelimiter(delimiter, maxLength);
}
}
public byte[] readBytesByLength(int length) throws IOException {
synchronized(delegate) {
return delegate.readBytesByLength(length);
}
}
public double readDouble() throws IOException {
synchronized(delegate) {
return delegate.readDouble();
}
}
public int readInt() throws IOException {
synchronized(delegate) {
return delegate.readInt();
}
}
public long readLong() throws IOException {
synchronized(delegate) {
return delegate.readLong();
}
}
public short readShort() throws IOException {
synchronized(delegate) {
return delegate.readShort();
}
}
public String readStringByDelimiter(String delimiter) throws IOException, UnsupportedEncodingException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter);
}
}
public String readStringByDelimiter(String delimiter, int maxLength) throws IOException, UnsupportedEncodingException, MaxReadSizeExceededException {
synchronized(delegate) {
return delegate.readStringByDelimiter(delimiter, maxLength);
}
}
public String readStringByLength(int length) throws IOException, BufferUnderflowException {
synchronized(delegate) {
return delegate.readStringByLength(length);
}
}
public long transferTo(WritableByteChannel target, int length) throws IOException, ClosedChannelException {
synchronized(delegate) {
return delegate.transferTo(target, length);
}
}
public long transferFrom(ReadableByteChannel source) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.transferFrom(source);
}
}
public long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.transferFrom(source, chunkSize);
}
}
public int write(byte b) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(b);
}
}
public int write(byte... bytes) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(bytes);
}
}
public int write(byte[] bytes, int offset, int length) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(bytes, offset, length);
}
}
public int write(ByteBuffer buffer) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(buffer);
}
}
public long write(ByteBuffer[] buffers) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(buffers);
}
}
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
synchronized(delegate) {
return delegate.write(srcs, offset, length);
}
}
public long write(List<ByteBuffer> buffers) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(buffers);
}
}
public int write(int i) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(i);
}
}
public int write(short s) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(s);
}
}
public int write(long l) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(l);
}
}
public int write(double d) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(d);
}
}
public int write(String message) throws IOException, BufferOverflowException {
synchronized(delegate) {
return delegate.write(message);
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/SynchronizedNonBlockingConnection.java | Java | art | 18,006 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.channels.FileChannel.MapMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.xsocket.DataConverter;
import org.xsocket.Execution;
import org.xsocket.ILifeCycle;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.SerializedTaskQueue;
/**
* A connection pool implementation.<br> <br>
*
* This class is thread safe <br>
*
* <pre>
* // create a unbound connection pool
* NonBlockingConnectionPool pool = new NonBlockingConnectionPool();
*
* INonBlockingCinnection con = null;
*
* try {
* // retrieve a connection (if no connection is in pool, a new one will be created)
* con = pool.getNonBlockingConnection(host, port);
* con.write("Hello");
* ...
*
* // always close the connection! (the connection will be returned into the connection pool)
* con.close();
*
* } catch (IOException e) {
* if (con != null) {
* try {
* // if the connection is invalid -> destroy it (it will not return into the pool)
* pool.destroy(con);
* } catch (Exception ignore) { }
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public final class NonBlockingConnectionPool implements IConnectionPool {
private static final Logger LOG = Logger.getLogger(NonBlockingConnectionPool.class.getName());
private static final long MIN_REMAINING_MILLIS_TO_IDLE_TIMEOUT = 3 * 1000;
private static final long MIN_REMAINING_MILLIS_TO_CONNECTION_TIMEOUT = 3 * 1000;
private static final int CONNECT_MAX_TRIALS = Integer.parseInt(System.getProperty("org.xsocket.connection.connectionpool.maxtrials", "3"));
private static final int CONNECT_RETRY_WAIT_TIME_MILLIS = Integer.parseInt(System.getProperty("org.xsocket.connection.connectionpool.retrywaittimemillis", "50"));
// is open flag
private final AtomicBoolean isOpen = new AtomicBoolean(true);
// ssl support
private final SSLContext sslContext;
// settings
private final AtomicInteger maxActive = new AtomicInteger(IConnectionPool.DEFAULT_MAX_ACTIVE);
private final AtomicInteger maxActivePerServer = new AtomicInteger(IConnectionPool.DEFAULT_MAX_ACTIVE_PER_SERVER);
private final AtomicInteger maxIdle = new AtomicInteger(IConnectionPool.DEFAULT_MAX_IDLE);
private final AtomicInteger poolIdleTimeoutMillis = new AtomicInteger(IConnectionPool.DEFAULT_IDLE_TIMEOUT_MILLIS);
private final AtomicInteger lifeTimeoutMillis = new AtomicInteger(IConnectionPool.DEFAULT_LIFE_TIMEOUT_MILLIS);
private final Object limitGuard = new Object();
private int numInitializingConnections = 0;
private final Map<InetAddress, Integer> initializingConnectionMap = new HashMap<InetAddress, Integer>();
// pool management
private final Pool pool = new Pool();
private final Object retrieveGuard = new Object();
private Integer acquireTimeoutMillis = null;
private Executor workerpool = NonBlockingConnection.getDefaultWorkerpool();
// timeout checker
private static final int DEFAULT_WATCHDOG_CHECK_PERIOD = 30 * 1000;
private final Watchog watchdog;
// listeners
private final List<ILifeCycle> listeners = new ArrayList<ILifeCycle>();
// statistics
private final AtomicInteger countRejectedConnections = new AtomicInteger(0);
private final AtomicInteger countUndetectedDisconnect = new AtomicInteger(0);
private final AtomicInteger countPendingGet = new AtomicInteger(0);
private final AtomicInteger countCreated = new AtomicInteger(0);
private final AtomicInteger countDestroyed = new AtomicInteger(0);
private final AtomicInteger countRemainingMillisToIdleTimeoutToSmall = new AtomicInteger(0);
private final AtomicInteger countRemainingConnectionToIdleTimeoutToSmall = new AtomicInteger(0);
private final AtomicInteger countCreationError = new AtomicInteger(0);
private final AtomicInteger countIdleTimeout = new AtomicInteger(0);
private final AtomicInteger countConnectionTimeout = new AtomicInteger(0);
private final AtomicInteger countTimeoutPooledIdle = new AtomicInteger(0);
private final AtomicInteger countTimeoutPooledLifetime = new AtomicInteger(0);
/**
* constructor
*
*/
public NonBlockingConnectionPool() {
this(null);
}
/**
* constructor
*
* @param sslContext the ssl context or <code>null</code> if ssl should not be used
*/
public NonBlockingConnectionPool(SSLContext sslContext) {
this(sslContext, DEFAULT_WATCHDOG_CHECK_PERIOD);
}
/**
* constructor
*
* @param sslContext the ssl context or <code>null</code> if ssl should not be used
*/
NonBlockingConnectionPool(SSLContext sslCtx, int watchdogCheckPeriod) {
// autoload SSL context if not set (works only with Java 1.6 or higher)
if (sslCtx == null) {
try {
Method m = SSLContext.class.getMethod("getDefault");
sslCtx = (SSLContext) m.invoke(SSLContext.class);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("default SSLContext -> SSLContext.getDefault() is loaded automatically");
}
} catch (Exception ignore) { }
}
sslContext = sslCtx;
watchdog = new Watchog();
IoProvider.getTimer().schedule(watchdog, watchdogCheckPeriod, watchdogCheckPeriod);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(String host, int port) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(host, port), null, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(String host, int port, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(host, port), null, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(String host, int port, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(host, port), null, workerpool, true, connectTimeoutMillis, false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(String host, int port, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(host, port), null, workerpool, true, connectTimeoutMillis, isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetSocketAddress address) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(address, null, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the sever port
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), null, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the sever port
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), null, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), null, workerpool, true, connectTimeoutMillis, false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param connectTimeoutMillis the connection timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), null, workerpool, true, connectTimeoutMillis, isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param waitForConnect true, if the call should block until the connection is established
* @param connectTimeoutMillis the connection timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, boolean waitForConnect, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), null, workerpool, waitForConnect, connectTimeoutMillis, isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(String host, int port, IHandler appHandler) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(host, port), appHandler, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param host the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(String host, int port, IHandler appHandler, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(host, port), appHandler, workerpool, true, toInt(IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS), isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param connectTimeoutMillis the connection creation timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerpool, true, connectTimeoutMillis, false);
}
/**
* get a pool connection for the given address in an asynchronous wa. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param waitForConnect true, if the method should block until the connection is established
* @param connectTimeoutMillis the connection creation timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerpool, waitForConnect, connectTimeoutMillis, false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param connectTimeoutMillis the connection creation timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerpool, true, connectTimeoutMillis, isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created
*
* @param address the server address
* @param port the server port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and IConnectionTimeoutHandler)
* @param waitForConnect true, if the method should block until the connection is established
* @param connectTimeoutMillis the connection creation timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, boolean waitForConnect, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerpool, waitForConnect, connectTimeoutMillis, isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created <br> <br>
*
* This method is thread safe
*
* @param address the server address
* @param port the sever port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and ConnectionTimeoutHandler)
* @param workerPool the worker pool to use
* @param connectTimeoutMillis the connection creation timeout
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, Executor workerPool, int connectTimeoutMillis) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerPool, true, connectTimeoutMillis, false);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created <br> <br>
*
* This method is thread safe
*
* @param address the server address
* @param port the sever port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and ConnectionTimeoutHandler)
* @param workerPool the worker pool to use
* @param connectTimeoutMillis the connection creation timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, Executor workerPool, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerPool, true, connectTimeoutMillis, isSSL);
}
/**
* get a pool connection for the given address. If no free connection is in the pool,
* a new one will be created <br> <br>
*
* This method is thread safe
*
* @param address the server address
* @param port the sever port
* @param appHandler the application handler (supported: IConnectHandler, IDisconnectHandler, IDataHandler, IIdleTimeoutHandler and ConnectionTimeoutHandler)
* @param workerPool the worker pool to use
* @param waitForConnect true, if the method should block until the connection is established
* @param connectTimeoutMillis the connection creation timeout
* @param isSSL true, if ssl connection
* @return the connection
* @throws SocketTimeoutException if the wait timeout has been reached (this will only been thrown if wait time has been set)
* @throws IOException if an exception occurs
* @throws MaxConnectionsExceededException if the max number of active connections (per server) is reached
*/
public INonBlockingConnection getNonBlockingConnection(InetAddress address, int port, IHandler appHandler, Executor workerPool, boolean waitForConnect, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException {
return getConnection(new InetSocketAddress(address, port), appHandler, workerPool, waitForConnect, connectTimeoutMillis, isSSL);
}
private int toInt(long l) {
if (l > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else {
return (int) l;
}
}
private INonBlockingConnection getConnection(InetSocketAddress address, IHandler appHandler, Executor workerPool, boolean waitForConnect, int connectTimeoutMillis, boolean isSSL) throws IOException, SocketTimeoutException, MaxConnectionsExceededException, MaxConnectionsExceededException {
NonBlockingConnectionProxy proxy = new NonBlockingConnectionProxy(address);
Connector connector;
if (waitForConnect) {
connector = new SyncConnector(proxy, appHandler, isSSL, CONNECT_MAX_TRIALS, connectTimeoutMillis, CONNECT_RETRY_WAIT_TIME_MILLIS);
} else {
connector = new Connector(proxy, appHandler, isSSL, CONNECT_MAX_TRIALS, connectTimeoutMillis, CONNECT_RETRY_WAIT_TIME_MILLIS);
}
try {
if (isSSL && (sslContext == null)) {
throw new IOException("could not create a SSL connection to " + address.toString() + ". SSLContext is not set");
}
if (isOpen.get()) {
connector.connect();
return proxy;
} else {
throw new IOException("pool is already closed");
}
} catch (IOException ioe) {
connector.onConnectFailed(ioe);
throw ioe;
}
}
private void checkLimit(InetAddress addr) throws MaxConnectionsExceededException {
synchronized (limitGuard) {
if ((pool.getNumActive() + numInitializingConnections) > maxActive.get()) {
if(LOG.isLoggable(Level.FINE)) {
LOG.fine("max active connections " + maxActive.get() + " exceeded");
}
countRejectedConnections.incrementAndGet();
throw new MaxConnectionsExceededException("max active connections " + maxActive.get() + " exceeded");
}
// limit per host activated?
if (maxActivePerServer.get() != Integer.MAX_VALUE) {
Integer connectionAddr = initializingConnectionMap.get(addr);
if (connectionAddr == null) {
connectionAddr = 0;
}
if (pool.isActiveExceeded(addr, (maxActivePerServer.get() - connectionAddr))) {
if(LOG.isLoggable(Level.FINE)) {
LOG.fine("max active connections " + maxActivePerServer.get() + " (initializing: " + connectionAddr + ") to " + addr + " exceeded");
}
countRejectedConnections.incrementAndGet();
throw new MaxConnectionsExceededException("max active connections " + maxActivePerServer.get() + " (initializing: " + connectionAddr + ") to " + addr + " exceeded");
}
}
}
}
private void incCountInitializingConnections(InetAddress addr) {
synchronized (limitGuard) {
numInitializingConnections++;
Integer connectionAddr = initializingConnectionMap.get(addr);
if (connectionAddr == null) {
connectionAddr = 0;
}
connectionAddr++;
initializingConnectionMap.put(addr, connectionAddr);
}
}
private void decCountInitializingConnections(InetAddress addr) {
synchronized (limitGuard) {
numInitializingConnections--;
if (numInitializingConnections < 0) {
numInitializingConnections = 0;
}
Integer connectionAddr = initializingConnectionMap.get(addr);
if (connectionAddr != null) {
connectionAddr--;
if (connectionAddr <= 0) {
initializingConnectionMap.remove(addr);
} else {
initializingConnectionMap.put(addr, connectionAddr);
}
}
}
}
private void newConnection(Connector connector) {
try {
// try to get a connection from the pool
NativeConnectionHolder nativeConnectionHolder;
do {
// try to get a pooled native connection
nativeConnectionHolder = pool.getAndRemoveIdleConnection(connector.getAddress(), connector.isSSL());
// got it?
if (nativeConnectionHolder != null) {
// reset resource (connection will be closed if invalid)
boolean isValid = nativeConnectionHolder.isVaild(System.currentTimeMillis(), true);
if (isValid && nativeConnectionHolder.getConnection().reset()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("got connection from pool (" + pool.toString() + ", idleTimeoutMillis=" + getPooledMaxIdleTimeMillis() + ", lifeTimeout=" + getPooledMaxLifeTimeMillis() + "): " + nativeConnectionHolder.getConnection());
}
connector.onConnected(nativeConnectionHolder);
return;
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("get a invalid connection try another one");
}
}
}
} while (nativeConnectionHolder != null);
// no resource available in pool -> create a new one
nativeConnectionHolder = newNativeConnection(connector, connector.getConnectTimeoutMillis(), CONNECT_MAX_TRIALS, CONNECT_RETRY_WAIT_TIME_MILLIS, connector.isSSL());
} catch (IOException ioe) {
connector.onConnectError(ioe);
}
}
private class Connector {
private final NonBlockingConnectionProxy proxy;
private final IHandler appHandler;
private final boolean isSSL;
private boolean isConnectionLimited;
private final long startMillis;
private final int connectTimeoutMillis;
private final long retryWaittimeMillis;
private final int maxTrials;
private int trials = 0;
public Connector(NonBlockingConnectionProxy proxy, IHandler appHandler, boolean isSSL, int maxTrials, int connectTimeoutMillis, long retryWaittimeMillis) {
this.proxy = proxy;
this.appHandler = appHandler;
this.isSSL = isSSL;
this.maxTrials = maxTrials;
this.connectTimeoutMillis = connectTimeoutMillis;
this.retryWaittimeMillis = retryWaittimeMillis;
startMillis = System.currentTimeMillis();
isConnectionLimited = ((maxActive.get() != Integer.MAX_VALUE) || (maxActivePerServer.get() != Integer.MAX_VALUE));
}
boolean isSSL() {
return isSSL;
}
Executor getWorkerpool() {
return workerpool;
}
int getConnectTimeoutMillis() {
return connectTimeoutMillis;
}
InetSocketAddress getAddress() {
return proxy.getAddress();
}
void connect() throws IOException {
if (isConnectionLimited) {
incCountInitializingConnections(proxy.getAddress().getAddress());
}
performConnect();
}
final void performConnect() {
trials++;
if (isConnectionLimited) {
try {
checkLimit(proxy.getAddress().getAddress());
} catch (MaxConnectionsExceededException mcr) {
onConnectError(mcr);
return;
}
}
newConnection(this);
}
final void onConnected(NativeConnectionHolder holder) throws IOException {
proxy.onConnected(holder, appHandler);
onConnectionEstablished();
}
final void onConnectError(IOException ioe) {
countCreationError.incrementAndGet();
// is timeout reached?
long remainingTimeMillis = connectTimeoutMillis - ((int) (System.currentTimeMillis() - startMillis));
if (remainingTimeMillis <= 0) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by creating connection to " + proxy.getAddress()
+ ". connect timeout " + DataConverter.toFormatedDuration(connectTimeoutMillis) + " reached (trials: " + trials + " maxTrials: " + maxTrials + ")");
}
onConnectFailed(new SocketTimeoutException("connect timeout " + connectTimeoutMillis + " millis reached (trials: " + trials + " maxTrials: " + maxTrials + "). Could not connect to " + proxy.getAddress() + " " + ioe.toString()));
}
if (ioe instanceof MaxConnectionsExceededException) {
if ((acquireTimeoutMillis == null) || (acquireTimeoutMillis <= 0)) {
onConnectFailed((MaxConnectionsExceededException) ioe);
} else {
long remaining = (startMillis + acquireTimeoutMillis) - System.currentTimeMillis();
if (remaining > 0) {
synchronized (retrieveGuard) {
try {
retrieveGuard.wait(remaining);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
performConnect();
} else {
onConnectFailed((MaxConnectionsExceededException) ioe);
}
}
} else {
// max trials reached?
if (trials >= maxTrials) {
onConnectFailed(new SocketTimeoutException("creation failed. Max trials " + maxTrials + " reached. Elapsed time " + DataConverter.toFormatedDuration(System.currentTimeMillis() - startMillis) +
" (connection timeout " + DataConverter.toFormatedDuration(connectTimeoutMillis) + "). Could not connect to " + proxy.getAddress() + " " + ioe.toString()));
// .. no, retry connect
} else {
if (remainingTimeMillis > retryWaittimeMillis) {
// after
TimerTask tt = new TimerTask() {
@Override
public void run() {
performConnect();
}
};
IoProvider.getTimer().schedule(tt, retryWaittimeMillis);
} else {
onConnectFailed(new SocketTimeoutException("connect timeout " + connectTimeoutMillis + " millis reached (trials: " + trials + " maxTrials: " + maxTrials + "). Could not connect to " + proxy.getAddress() + " " + ioe.toString()));
}
}
}
}
void onConnectionEstablished() {
if (isConnectionLimited) {
decCountInitializingConnections(proxy.getAddress().getAddress());
}
}
void onConnectFailed(IOException ioe) {
if (isConnectionLimited) {
decCountInitializingConnections(proxy.getAddress().getAddress());
}
proxy.onConnectFailed(workerpool, ioe, appHandler);
}
}
private final class SyncConnector extends Connector {
private boolean isConnected = false;
private IOException ioe = null;
public SyncConnector(NonBlockingConnectionProxy proxy, IHandler appHandler, boolean isSSL, int maxTrials, int connectTimeoutMillis, long retryWaittimeMillis) {
super(proxy, appHandler, isSSL, maxTrials, connectTimeoutMillis, retryWaittimeMillis);
}
void connect() throws IOException {
synchronized (this) {
super.connect();
while (isConnected == false) {
try {
this.wait();
} catch (InterruptedException ignore) { }
}
if (ioe != null) {
throw ioe;
}
}
}
@Override
void onConnectionEstablished() {
super.onConnectionEstablished();
synchronized (this) {
this.ioe = null;
isConnected = true;
this.notifyAll();
}
}
@Override
void onConnectFailed(IOException ioe) {
super.onConnectFailed(ioe);
synchronized (this) {
this.ioe = ioe;
isConnected = true;
this.notifyAll();
}
}
}
private void returnToIdlePool(NativeConnectionHolder nativeConnectionHolder) {
pool.returnIdleConnection(nativeConnectionHolder);
if (maxActive.get() < Integer.MAX_VALUE) {
wakeupPendingRetrieve();
}
}
private void wakeupPendingRetrieve() {
synchronized (retrieveGuard) {
retrieveGuard.notifyAll();
}
}
private NativeConnectionHolder newNativeConnection(Connector connector, final int creationTimeoutMillis, int maxTrials, int retryWaittimeMillis, boolean isSSL) throws IOException {
long start = System.currentTimeMillis();
int remainingTimeMillis = creationTimeoutMillis;
int trials = 0;
while (true) {
trials++;
try {
// create a new tcp connection and the assigned holder
NativeConnectionHolder nativeConnectionHolder = new NativeConnectionHolder(connector);
new NonBlockingConnection(connector.getAddress(), false, remainingTimeMillis, new HashMap<String, Object>(), sslContext, isSSL, nativeConnectionHolder, connector.getWorkerpool(), null);
return nativeConnectionHolder;
} catch (IOException ioe) {
countCreationError.incrementAndGet();
// is timeout reached?
remainingTimeMillis = creationTimeoutMillis - ((int) (System.currentTimeMillis() - start));
if (remainingTimeMillis <= 0) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by creating connection to " + connector.getAddress()
+ ". creation timeout " + DataConverter.toFormatedDuration(creationTimeoutMillis) + " reached (trials: " + trials + " maxTrials: " + maxTrials + ")");
}
throw new SocketTimeoutException("creation timeout " + creationTimeoutMillis + " millis reached (trials: " + trials + " maxTrials: " + maxTrials + "). Could not connect to " + connector.getAddress() + " " + ioe.toString());
}
// max trials reached?
if (trials >= maxTrials) {
throw new SocketTimeoutException("creation failed. Max trials " + maxTrials + " reached. Elapsed time " + DataConverter.toFormatedDuration(System.currentTimeMillis() - start) +
" (creation timeout " + DataConverter.toFormatedDuration(creationTimeoutMillis) + "). Could not connect to " + connector.getAddress() + " " + ioe.toString());
} else {
if (remainingTimeMillis > retryWaittimeMillis) {
try {
Thread.sleep(retryWaittimeMillis);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
retryWaittimeMillis += retryWaittimeMillis;
} else {
throw new SocketTimeoutException("creation timeout " + creationTimeoutMillis + " millis reached (trials: " + trials + " maxTrials: " + maxTrials + "). Could not connect to " + connector.getAddress() + " " + ioe.toString());
}
}
}
}
}
/**
* {@inheritDoc}
*/
public boolean isOpen() {
return isOpen.get();
}
/**
* {@inheritDoc}
*/
public void close() {
if (isOpen.getAndSet(false)) {
pool.close();
watchdog.cancel();
for (ILifeCycle lifeCycle : listeners) {
try {
lifeCycle.onDestroy();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("exception occured by destroying " + lifeCycle + " " + ioe.toString());
}
}
}
listeners.clear();
// unset references
workerpool = null;
}
}
/**
* destroy the pool by killing idle and active connections
*/
public void destroy() {
if (isOpen.getAndSet(false)) {
pool.destroy();
watchdog.cancel();
for (ILifeCycle lifeCycle : listeners) {
try {
lifeCycle.onDestroy();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("exception occured by destroying " + lifeCycle + " " + ioe.toString());
}
}
}
listeners.clear();
// unset references
workerpool = null;
}
}
/**
* {@inheritDoc}
*/
public void addListener(ILifeCycle listener) {
listeners.add(listener);
}
/**
* {@inheritDoc}
*/
public boolean removeListener(ILifeCycle listener) {
boolean result = listeners.remove(listener);
return result;
}
/**
* set the worker pool which will be assigned to the connections for call back handling
* @param workerpool the worker pool
*/
public void setWorkerpool(Executor workerpool) {
this.workerpool = workerpool;
}
/**
* get the worker pool which will be assigned to the connections for call back handling
* @return the worker pool
*/
public Executor getWorkerpool() {
return workerpool;
}
/**
* {@inheritDoc}
*/
public int getMaxActive() {
return maxActive.get();
}
/**
* {@inheritDoc}
*/
public int getNumRejectedConnections() {
return countRejectedConnections.get();
}
/**
* {@inheritDoc}
*/
public void setMaxActive(int maxActive) {
if (maxActive < 0) {
maxActive = 0;
}
this.maxActive.set(maxActive);
wakeupPendingRetrieve();
}
/**
* {@inheritDoc}
*/
public void setMaxActivePerServer(int maxActivePerServer) {
if (maxActivePerServer < 0) {
maxActivePerServer = 0;
}
this.maxActivePerServer.set(maxActivePerServer);
wakeupPendingRetrieve();
}
/**
* {@inheritDoc}
*/
public int getMaxActivePerServer() {
return maxActivePerServer.get();
}
/**
* {@inheritDoc}
*/
public int getMaxIdle() {
return maxIdle.get();
}
/**
* {@inheritDoc}
*/
public void setMaxIdle(int maxIdle) {
this.maxIdle.set(maxIdle);
}
/**
* {@inheritDoc}
*/
public int getNumActive() {
return pool.getNumActive();
}
/**
* returns the acquire timeout. Default is null
*
* @return the acquire timeout
*/
public Integer getAcquireTimeoutMillis() {
return acquireTimeoutMillis;
}
/**
* sets the acquire time out. Null deactivates the acquire timeout.
*
* @param aquireTimeoutMillis the acquire timeout or <code>null</code>
*/
public void setAcquireTimeoutMillis(Integer aquireTimeoutMillis) {
this.acquireTimeoutMillis = aquireTimeoutMillis;
}
public List<String> getActiveConnectionInfos() {
List<String> result = new ArrayList<String>();
List<NativeConnectionHolder> connectionHolders = pool.newManagedPoolCopy();
connectionHolders.removeAll(pool.newIdleCopySet());
for (NativeConnectionHolder connectionHolder : connectionHolders) {
result.add(connectionHolder.toString());
}
return result;
}
public List<String> getIdleConnectionInfos() {
List<String> result = new ArrayList<String>();
for (NativeConnectionHolder nativeConnectionHolder : pool.newIdleCopySet()) {
result.add(nativeConnectionHolder.toString());
}
return result;
}
/**
* {@inheritDoc}
*/
public int getNumIdle() {
return pool.getNumIdle();
}
/**
* {@inheritDoc}
*/
public int getNumCreated() {
return countCreated.get();
}
/**
* get the number of the creation errors
*
* @return the number of creation errors
*/
public int getNumCreationError() {
return countCreationError.get();
}
/**
* {@inheritDoc}
*/
public int getNumDestroyed() {
return countDestroyed.get();
}
int getNumIdleTimeout() {
return countIdleTimeout.get();
}
int getNumConnectionTimeout() {
return countConnectionTimeout.get();
}
int getNumPoolIdleTimeout() {
return countTimeoutPooledIdle.get();
}
int getNumPoolLifetimeTimeout() {
return countTimeoutPooledLifetime.get();
}
/**
* {@inheritDoc}
*/
public int getNumTimeoutPooledMaxIdleTime() {
return countTimeoutPooledIdle.get();
}
/**
* {@inheritDoc}
*/
public int getNumTimeoutPooledMaxLifeTime() {
return countTimeoutPooledLifetime.get();
}
int getNumUndetectedDisconnect() {
return countUndetectedDisconnect.get();
}
/**
* {@inheritDoc}
*/
public int getPooledMaxIdleTimeMillis() {
return poolIdleTimeoutMillis.get();
}
/**
* {@inheritDoc}
*/
public void setPooledMaxIdleTimeMillis(int idleTimeoutMillis) {
this.poolIdleTimeoutMillis.set(idleTimeoutMillis);
}
/**
* {@inheritDoc}
*/
public int getPooledMaxLifeTimeMillis() {
return lifeTimeoutMillis.get();
}
/**
* {@inheritDoc}
*/
public void setPooledMaxLifeTimeMillis(int lifeTimeoutMillis) {
this.lifeTimeoutMillis.set(lifeTimeoutMillis);
}
/**
* get the current number of pending get operations to retrieve a resource
*
* @return the current number of pending get operations
*/
public int getNumPendingGet() {
return countPendingGet.get();
}
/**
* {@inheritDoc}
*/
public static void destroy(INonBlockingConnection connection) throws IOException {
if (connection == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("warning trying to destroy a <null> connection. destroy will be ignored");
}
return;
}
if (connection instanceof NonBlockingConnectionProxy) {
((NonBlockingConnectionProxy) connection).destroy();
} else {
connection.close();
}
}
static boolean isDestroyed(INonBlockingConnection connection) {
if (connection instanceof NonBlockingConnectionProxy) {
return ((NonBlockingConnectionProxy) connection).isDestroyed();
} else {
return connection.isOpen();
}
}
private void checkIdleConnections() {
long currentMillis = System.currentTimeMillis();
for (NativeConnectionHolder nativeConnectionHolder : pool.newIdleCopySet()) {
if (!nativeConnectionHolder.isVaild(currentMillis, false)) {
boolean isRemoved = pool.removeIdleConnection(nativeConnectionHolder);
if (isRemoved) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] closing connection because it is invalid (e.g. idle timeout, connection timeout reached)");
}
nativeConnectionHolder.isVaild(currentMillis, true); // true -> closes the connection
nativeConnectionHolder.close(); /// sanity close
}
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
try {
sb.append("active=" + getNumActive() + ", idle=" + getNumIdle() + " ");
sb.append("created=" + countCreated + ", destroyed=" + countDestroyed + " ");
sb.append("connectionTimeout=" + countConnectionTimeout + ", idleTimeout=" + countIdleTimeout + " (");
sb.append("maxActive=" + maxActive + ", maxIdle=" + maxIdle + ", ");
sb.append("poolIdleTimeout=" + poolIdleTimeoutMillis + ", poollifetimeTimeout=" + lifeTimeoutMillis + ")");
} catch (Exception ignore) {
}
return sb.toString();
}
private final class Watchog extends TimerTask {
@Override
public void run() {
try {
checkIdleConnections();
} catch (Throwable t) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by checking connections " + t.toString());
}
}
}
}
private static final class Pool {
private final ArrayList<NativeConnectionHolder> managedPool = new ArrayList<NativeConnectionHolder>();
private final HashMap<InetSocketAddress, List<NativeConnectionHolder>> idlePool = new HashMap<InetSocketAddress, List<NativeConnectionHolder>>();
private boolean isOpen = true;
public void register(NativeConnectionHolder nativeConnectionHolder) {
if (isOpen) {
synchronized (this) {
managedPool.add(nativeConnectionHolder);
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] added to managed pool (active=" + getNumActive() + ", idle=" + getNumIdle() + ")");
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("ignore registering connection " + nativeConnectionHolder.toString() + " because pool is already closed");
}
}
}
public boolean remove(NativeConnectionHolder nativeConnectionHolder) {
boolean isRemoved = false;
if (isOpen) {
removeIdleConnection(nativeConnectionHolder);
synchronized (this) {
isRemoved = managedPool.remove(nativeConnectionHolder);
}
if (LOG.isLoggable(Level.FINE)) {
if (isRemoved) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] connection removed from managed pool (active=" + getNumActive() + ", idle=" + getNumIdle() + ")");
} else {
LOG.fine("[" + nativeConnectionHolder.getId() + "] could not removed connection from managed pool. Connection already removed? (active=" + getNumActive() + ", idle=" + getNumIdle() + ")");
}
}
}
return isRemoved;
}
public boolean removeIdleConnection(NativeConnectionHolder connectionHolder) {
if (isOpen) {
synchronized (this) {
List<NativeConnectionHolder> idleList = idlePool.get(connectionHolder.getAddress());
if (idleList != null) {
for (NativeConnectionHolder nativeConnectionHolder : idleList) {
if (nativeConnectionHolder == connectionHolder) {
boolean isRemoved = idleList.remove(nativeConnectionHolder);
if (idleList.isEmpty()) {
idlePool.remove(connectionHolder.getAddress());
}
return isRemoved;
}
}
}
}
}
return false;
}
public NativeConnectionHolder getAndRemoveIdleConnection(InetSocketAddress address, boolean isSSL) {
if (isOpen) {
synchronized (this) {
List<NativeConnectionHolder> idleList = idlePool.get(address);
if (idleList != null) {
for (NativeConnectionHolder nativeConnectionHolder : idleList) {
if (nativeConnectionHolder.isSSL == isSSL) {
idleList.remove(nativeConnectionHolder);
if (idleList.isEmpty()) {
idlePool.remove(address);
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] got from idle pool (active=" + getNumActive() + ", idle=" + getNumIdle() + ")");
}
return nativeConnectionHolder;
}
}
}
}
}
return null;
}
public void returnIdleConnection(NativeConnectionHolder nativeConnectionHolder) {
if (isOpen) {
InetSocketAddress address = nativeConnectionHolder.getAddress();
synchronized (this) {
List<NativeConnectionHolder> idleList = idlePool.get(address);
if (idleList == null) {
idleList = new ArrayList<NativeConnectionHolder>();
idlePool.put(address, idleList);
}
if (!idleList.contains(nativeConnectionHolder)) {
idleList.add(nativeConnectionHolder);
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] will not be returned to pool because it already exits (active=" + getNumActive() + ", idle=" + getNumIdle() + ")");
}
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] added to idle pool (active=" + getNumActive() + ", idle=" + getNumIdle() + ")");
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + nativeConnectionHolder.getId() + "] will not be returned to pool, because pool is already closed. destroying connection");
}
nativeConnectionHolder.close();
}
}
public void close() {
synchronized (this) {
if (isOpen) {
isOpen = false;
} else {
return;
}
}
List<NativeConnectionHolder> idleSet = newIdleCopySet();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("closing " + idleSet.size() + " idle conection(s); " + managedPool.size() + " connection(s) stay open unmanaged");
}
for (NativeConnectionHolder nativeConnectionHolder : idleSet) {
nativeConnectionHolder.close();
}
idlePool.clear();
managedPool.clear();
}
public void destroy() {
synchronized (this) {
if (isOpen) {
isOpen = false;
} else {
return;
}
}
List<NativeConnectionHolder> connections = newManagedPoolCopy();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("closing " + connections.size() + " managed connections");
}
for (NativeConnectionHolder nativeConnectionHolder : connections) {
nativeConnectionHolder.close();
}
synchronized (this) {
idlePool.clear();
managedPool.clear();
}
}
private List<NativeConnectionHolder> newIdleCopySet() {
List<NativeConnectionHolder> idleList = new ArrayList<NativeConnectionHolder>();
for (List<NativeConnectionHolder> nativeConnectionHolderList : newIdlePoolCopy().values()) {
idleList.addAll(nativeConnectionHolderList);
}
return idleList;
}
@SuppressWarnings("unchecked")
List<NativeConnectionHolder> newManagedPoolCopy() {
List<NativeConnectionHolder> managedPoolCopy = null;
synchronized (this) {
managedPoolCopy = (List<NativeConnectionHolder>) managedPool.clone();
}
return managedPoolCopy;
}
@SuppressWarnings("unchecked")
boolean isActiveExceeded(InetAddress address, int maxSize) {
List<NativeConnectionHolder> managedPoolCopy;
synchronized (this) {
managedPoolCopy = (List<NativeConnectionHolder>) managedPool.clone();
}
// if connections is smaller than max size, return not exceeded
if (managedPoolCopy.size() <= maxSize) {
return false;
}
int managedMatched = 0;
for (NativeConnectionHolder holder : managedPoolCopy) {
if (holder.getAddress().getAddress().equals(address)) {
managedMatched++;
}
}
// if connections of the address is smaller than max size, return not exceeded
if (managedMatched <= maxSize) {
return false;
}
HashMap<InetSocketAddress, List<NativeConnectionHolder>> idlePoolCopy;
synchronized (this) {
idlePoolCopy = (HashMap<InetSocketAddress, List<NativeConnectionHolder>>) idlePool.clone();
}
for (Entry<InetSocketAddress, List<NativeConnectionHolder>> entry : idlePoolCopy.entrySet()) {
if (entry.getKey().getAddress().equals(address)) {
managedMatched = managedMatched - entry.getValue().size();
if (managedMatched <= maxSize) {
return false;
}
}
}
return true;
}
@SuppressWarnings("unchecked")
HashMap<InetSocketAddress, List<NativeConnectionHolder>> newIdlePoolCopy() {
HashMap<InetSocketAddress, List<NativeConnectionHolder>> idlePoolCopy = null;
synchronized (this) {
idlePoolCopy = (HashMap<InetSocketAddress, List<NativeConnectionHolder>>) idlePool.clone();
}
return idlePoolCopy;
}
public int getSize() {
synchronized (this) {
return managedPool.size();
}
}
public int getNumIdle() {
synchronized (this) {
return computeNumIdle();
}
}
public int getNumActive() {
synchronized (this) {
return (managedPool.size() - computeNumIdle());
}
}
private int computeNumIdle() {
int size = 0;
for (List<NativeConnectionHolder> nativeConnectionHolderList : idlePool.values()) {
size += nativeConnectionHolderList.size();
}
return size;
}
@Override
public String toString() {
return "size=" + getSize() + ", active=" + getNumActive();
}
}
private final class NativeConnectionHolder implements IConnectHandler, IConnectExceptionHandler, IDataHandler, IDisconnectHandler, IConnectionTimeoutHandler, IIdleTimeoutHandler, IUnsynchronized {
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final AtomicBoolean isReusable = new AtomicBoolean(true);
private final AtomicReference<NonBlockingConnectionProxy> proxyRef = new AtomicReference<NonBlockingConnectionProxy>(null);
private Connector connector;
private NonBlockingConnection connection;
private InetSocketAddress address;
private boolean isSSL;
private int usage = 0;
private long creationTimeMillis = System.currentTimeMillis();
private long lastUsageTimeMillis = System.currentTimeMillis();
public NativeConnectionHolder(Connector connector) {
this.connector = connector;
}
public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
this.address = new InetSocketAddress(connection.getRemoteAddress(), connection.getRemotePort());
this.connection = (NonBlockingConnection) connection;
isSSL = connection.isSecure();
pool.register(this);
countCreated.incrementAndGet();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] pooled connection created (" + pool.toString() + ", pooledIdleTimeoutMillis=" + getPooledMaxIdleTimeMillis() + ", pooledLifeTimeout=" + getPooledMaxLifeTimeMillis() + "): " + connection);
}
connector.onConnected(this);
return true;
}
public boolean onConnectException(INonBlockingConnection connection, IOException ioe) throws IOException {
connector.onConnectError(ioe);
return true;
}
String getId() {
return connection.getId();
}
int getPooledMaxLifeTimeMillis() {
return lifeTimeoutMillis.get();
}
int getPooledMaxIdleTimeMillis() {
return poolIdleTimeoutMillis.get();
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
NonBlockingConnectionProxy cp = proxyRef.get();
if (cp != null) {
try {
return cp.onData();
} catch (MaxReadSizeExceededException mre) {
isReusable.set(false);
throw mre;
} catch (IOException ioe) {
isReusable.set(false);
throw ioe;
}
} else {
return true;
}
}
public boolean onDisconnect(INonBlockingConnection connection) throws IOException {
isReusable.set(false);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("onDisconnect occured. Removing connection from pool (" + address.toString() + ") (" + pool.toString() + ", idleTimeoutMillis=" + getPooledMaxIdleTimeMillis() + ", lifeTimeout=" + getPooledMaxLifeTimeMillis() + "): " + connection);
}
pool.remove(this);
try {
NonBlockingConnectionProxy cp = proxyRef.get();
if (cp!= null) {
return cp.onDisconnect();
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("could not call onDisconnect on proxy (proxy already dregistered?)");
}
return true;
}
} finally {
countDestroyed.incrementAndGet();
}
}
public boolean onConnectionTimeout(INonBlockingConnection connection) throws IOException {
isReusable.set(false);
countConnectionTimeout.incrementAndGet();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] connection timeout occured");
}
NonBlockingConnectionProxy cp = proxyRef.get();
if (cp != null) {
return cp.onConnectionTimeout();
} else {
return false; // let the connection be destroyed
}
}
public boolean onIdleTimeout(INonBlockingConnection connection) throws IOException {
isReusable.set(false);
countIdleTimeout.incrementAndGet();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] idle timeout (" + DataConverter.toFormatedDuration(getConnection().getIdleTimeoutMillis()) + ") occured");
}
NonBlockingConnectionProxy cp = proxyRef.get();
if (cp != null) {
return cp.onIdleTimeout();
} else {
return false; // let the connection be destroyed
}
}
int getUsage() {
return usage;
}
long getCreationTimeMillis() {
return creationTimeMillis;
}
NonBlockingConnection getConnection() {
return connection;
}
InetSocketAddress getAddress() {
return address;
}
void registerProxy(NonBlockingConnectionProxy proxy) {
assert (proxyRef.get() == null);
usage++;
lastUsageTimeMillis = System.currentTimeMillis();
proxyRef.set(proxy);
}
void unregister() {
proxyRef.set(null);
lastUsageTimeMillis = System.currentTimeMillis();
try {
// is connected?
if (connection.isConnected()) {
if (connection.isOpen() && isOpen() && (connection.available() == 0)) {
// reset resource
boolean isValid = isVaild(System.currentTimeMillis(), true);
if (isValid) {
// .. and return it to the pool only if max idle size is not reached
if ((maxIdle.get() != Integer.MAX_VALUE) || (pool.getNumIdle() >= maxIdle.get())) {
return;
}
boolean isReset = connection.reset();
if (isReset) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] releasing connection (for reuse)");
}
returnToIdlePool(this);
return;
}
}
}
close();
}
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by releasing a pooled connection (" + address.toString() + ") " + e.toString());
}
}
}
/**
* check if the connection is valid
*
* @return true, if reuseable
*/
private boolean isVaild(long currentTimeMillis, boolean closeIfInvalid) {
// is open?
if (isClosed.get()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] is invalid (closed)");
}
return false;
}
if (!isReusable.get()) {
if (closeIfInvalid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] closing connection because it is marked as non reuseable");
}
close();
}
return false;
}
if (!connection.isConnected() || !connection.isOpen()) {
if (closeIfInvalid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] closing connection because it is disconnected or closed");
}
close();
}
return false;
}
if (connection.getRemainingMillisToIdleTimeout() < MIN_REMAINING_MILLIS_TO_IDLE_TIMEOUT) {
if (closeIfInvalid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] closing connection because remaining time to idle timeout (" + connection.getRemainingMillisToIdleTimeout() + " millis) is to small");
}
countRemainingMillisToIdleTimeoutToSmall.incrementAndGet();
close();
}
return false;
}
if (connection.getRemainingMillisToConnectionTimeout() < MIN_REMAINING_MILLIS_TO_CONNECTION_TIMEOUT) {
if (closeIfInvalid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] closing connection because remaining time to connection timeout (" + connection.getRemainingMillisToConnectionTimeout() + " millis) is to small");
}
countRemainingConnectionToIdleTimeoutToSmall.incrementAndGet();
close();
}
return false;
}
if ((poolIdleTimeoutMillis.get() != Integer.MAX_VALUE) && (currentTimeMillis > (lastUsageTimeMillis + poolIdleTimeoutMillis.get()))) {
if (closeIfInvalid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + connection.getId() + "] connection (" + address + ") pool idle timeout reached (" + poolIdleTimeoutMillis + ")");
}
countTimeoutPooledIdle.incrementAndGet();
close();
}
return false;
}
if ((lifeTimeoutMillis.get() != Integer.MAX_VALUE) && (currentTimeMillis > (creationTimeMillis + lifeTimeoutMillis.get()))) {
if (closeIfInvalid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] connection (" + address + ") pool life timeout reached (" + lifeTimeoutMillis + ")");
}
countTimeoutPooledLifetime.incrementAndGet();
close();
}
return false;
}
return true;
}
void close() {
if (!isClosed.getAndSet(true)) {
pool.remove(this);
NonBlockingConnection.closeQuietly(connection);
wakeupPendingRetrieve();
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
try {
if (connection.isReceivingSuspended()) {
sb.append("[suspended] ");
}
try {
sb.append(connection.getLocalAddress() + ":" + connection.getLocalPort() + " -> " +
connection.getRemoteAddress() + ":" + connection.getRemotePort() + " " +
"[" + connection.getId() + "]");
} catch (Exception e) {
sb.append("[" + connection.getId() + "]");
}
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sb.append(" creationTime=" + df.format(getCreationTimeMillis()) +
", ageMillis=" + (System.currentTimeMillis() - creationTimeMillis) +
", elapsedLastUsageMillis=" + (System.currentTimeMillis() - lastUsageTimeMillis) +
", countUsage=" + getUsage() +
", isReusable=" + isReusable.get());
} catch (Exception ignore) {
}
return sb.toString();
}
}
private static final class NonBlockingConnectionProxy implements INonBlockingConnection {
private volatile boolean isOpen = false;
private final AtomicReference<NativeConnectionHolder> nativeConnectionHolderRef = new AtomicReference<NativeConnectionHolder>(null);
private String id;
private final AtomicReference<HandlerAdapter> handlerAdapterRef = new AtomicReference<HandlerAdapter>(null);
private final AtomicReference<IHandlerChangeListener> handlerReplaceListenerRef = new AtomicReference<IHandlerChangeListener>();
private Object attachment = null;
private boolean isAutoflush = IConnection.DEFAULT_AUTOFLUSH;
private final InetSocketAddress address;
// statisitcs
private int countReuse;
private long initialSendBytes;
private long initialReceivedBytes;
private long creationTime;
private long elapsedLastUsage;
// timeout support
private final AtomicBoolean isIdleTimeoutOccured = new AtomicBoolean(false);
private final AtomicBoolean isConnectionTimeoutOccured = new AtomicBoolean(false);
private final Object disconnectedGuard = false;
private boolean isDisconnected = false;
public NonBlockingConnectionProxy(InetSocketAddress address) {
this.address = address;
}
InetSocketAddress getAddress() {
return address;
}
void onConnected(NativeConnectionHolder holder, IHandler handler) throws IOException {
isOpen = true;
nativeConnectionHolderRef.set(holder);
holder.getConnection().setAutoflush(false);
creationTime = System.currentTimeMillis();
elapsedLastUsage = holder.lastUsageTimeMillis;
countReuse = holder.usage;
id = holder.getConnection().getId() + "I" + Integer.toHexString(countReuse);
initialReceivedBytes = holder.getConnection().getNumberOfReceivedBytes();
initialSendBytes = holder.getConnection().getNumberOfSendBytes();
setHandler(handler);
onConnect();
holder.registerProxy(this);
onData();
}
private boolean onConnect() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
HandlerAdapter handlerAdapter = handlerAdapterRef.get();
if ((holder != null) && (handlerAdapter != null)) {
try {
return handlerAdapter.onConnect(this, holder.connection.getTaskQueue(), holder.connection.getExecutor(), false);
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] Error occured by perform onConnect callback on " + handlerAdapter + " " + ioe.toString());
}
return false;
}
} else {
return false;
}
}
void onConnectFailed(Executor workerpool, IOException ioe, IHandler appHandler) {
HandlerAdapter handlerAdapter = HandlerAdapter.newInstance(appHandler);
try {
handlerAdapter.onConnectException(this, new SerializedTaskQueue(), workerpool, ioe);
} catch (IOException e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] Error occured by perform onConnect callback on " + handlerAdapter + " " + e.toString());
}
}
}
private void ensureOpen() {
if (!isOpen) {
throw new RuntimeException("channel " + getId() + " is closed");
}
}
public void setHandler(IHandler hdl) throws IOException {
ensureOpen();
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
HandlerAdapter oldHandlerAdapter = handlerAdapterRef.get();
IHandlerChangeListener changeListener = handlerReplaceListenerRef.get();
// call old handler change listener
if ((changeListener != null) && (oldHandlerAdapter != null)) {
IHandler oldHandler = oldHandlerAdapter.getHandler();
changeListener.onHanderReplaced(oldHandler, hdl);
}
boolean isChangeListener = false;
if (hdl != null) {
isChangeListener = (hdl instanceof IHandlerChangeListener);
}
HandlerAdapter adapter = HandlerAdapter.newInstance(hdl);
if (hdl instanceof IHandlerChangeListener) {
handlerReplaceListenerRef.set((IHandlerChangeListener) hdl);
}
boolean callDisconnect = false;
synchronized (disconnectedGuard) {
handlerAdapterRef.set(adapter);
if (isChangeListener) {
handlerReplaceListenerRef.set((IHandlerChangeListener) hdl);
}
if (isDisconnected) {
callDisconnect = true;
}
}
onData();
// is disconnected
if (callDisconnect) {
adapter.onDisconnect(this, holder.connection.getTaskQueue(), holder.connection.getExecutor(), false);
}
}
}
public IHandler getHandler() {
ensureOpen();
if (nativeConnectionHolderRef.get() == null) {
return null;
}
HandlerAdapter handlerAdapter = handlerAdapterRef.get();
if (handlerAdapter == null) {
return null;
} else {
return ((HandlerAdapter) handlerAdapter).getHandler();
}
}
boolean isDestroyed() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return !holder.getConnection().isConnected();
} else {
return true;
}
}
public boolean isOpen() {
if (!isOpen) {
return false;
}
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().isOpen();
} else {
return false;
}
}
public void close() throws IOException {
initiateOnDisconnect();
NativeConnectionHolder holder = nativeConnectionHolderRef.getAndSet(null);
if (holder != null) {
holder.unregister();
}
}
void destroy() {
initiateOnDisconnect();
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
holder.close();
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] error occured while destroying pooledConnectionHolder " + nativeConnectionHolderRef.get() + " reason: " + e.toString());
}
}
}
}
private void initiateOnDisconnect() {
try {
onData();
} catch (IOException ignore) { }
onDisconnect();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
try {
sb.append(getId());
if (!isOpen()) {
sb.append(" closed");
}
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
sb.append(" (" + holder.getAddress() + ") ");
}
sb.append(" (proxy ");
if (holder == null) {
sb.append("closed " +
", countReuse=" + countReuse +
", ageProxyMillis=" + (System.currentTimeMillis() - creationTime) +
", elapsedLastUsageMillis=" + (System.currentTimeMillis() - elapsedLastUsage));
} else {
sb.append("received=" + getNumberOfReceivedBytes() +
", sent=" + getNumberOfSendBytes() +
", countReuse=" + countReuse +
", agePhysicalMillis=" + (System.currentTimeMillis() - holder.creationTimeMillis) +
", pooledLifeTimeout=" + holder.getPooledMaxLifeTimeMillis() +
", pooledIdleTimeout=" + holder.getPooledMaxIdleTimeMillis() +
", ageProxyMillis=" + (System.currentTimeMillis() - creationTime) +
", elapsedLastUsageMillis=" + (System.currentTimeMillis() - elapsedLastUsage) +
", elapsedTimeLastSent=" + (System.currentTimeMillis() - holder.getConnection().getLastTimeSendMillis()) +
", elapsedTimeLastReceived=" + (System.currentTimeMillis() - holder.getConnection().getLastTimeReceivedMillis()));
}
} catch (Exception ignore) {
}
return sb.toString();
}
public String getId() {
return id;
}
private boolean onDisconnect() {
HandlerAdapter adapter = null;
synchronized (disconnectedGuard) {
if (isDisconnected) {
return true;
} else {
isDisconnected = true;
adapter = handlerAdapterRef.get();
}
}
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if ((holder != null) && (adapter != null)) {
adapter.onDisconnect(this, holder.connection.getTaskQueue(), holder.connection.getExecutor(), false);
}
return true;
}
private boolean onData() throws IOException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
HandlerAdapter handlerAdapter = handlerAdapterRef.get();
if ((holder != null) && (handlerAdapter != null)) {
return handlerAdapter.onData(this, holder.connection.getTaskQueue(), holder.connection.getExecutor(), false, false);
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] onData called even though proxy is closed");
}
return true;
}
}
private boolean onConnectionTimeout() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
HandlerAdapter handlerAdapter = handlerAdapterRef.get();
if ((holder != null) && (handlerAdapter != null)) {
if (!isConnectionTimeoutOccured.getAndSet(true)) {
return handlerAdapter.onConnectionTimeout(this, holder.connection.getTaskQueue(), holder.connection.getExecutor());
} else {
return true;
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] onConnectionTimeout called even though proxy is closed");
}
return true;
}
}
private boolean onIdleTimeout() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
HandlerAdapter handlerAdapter = handlerAdapterRef.get();
if ((holder != null) && (handlerAdapter != null)) {
if (!isIdleTimeoutOccured.getAndSet(true)) {
return handlerAdapter.onIdleTimeout(this, holder.connection.getTaskQueue(), holder.connection.getExecutor());
} else {
return true;
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] onIdletimeout called even though proxy is closed");
}
return true;
}
}
public boolean isServerSide() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().isServerSide();
} else {
throw newClosedChannelRuntimeException();
}
}
public Executor getWorkerpool() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().getWorkerpool();
} else {
return NonBlockingConnection.getDefaultWorkerpool();
}
}
public void setWorkerpool(Executor workerpool) {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setWorkerpool(workerpool);
}
}
public void setAttachment(Object obj) {
this.attachment = obj;
}
public Object getAttachment() {
return attachment;
}
public void setAutoflush(boolean autoflush) {
isAutoflush = autoflush;
}
public boolean isAutoflush() {
return isAutoflush;
}
public void setEncoding(String defaultEncoding) {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setEncoding(defaultEncoding);
}
}
public String getEncoding() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getEncoding();
} else {
return IConnection.INITIAL_DEFAULT_ENCODING;
}
}
public void setFlushmode(FlushMode flushMode) {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setFlushmode(flushMode);
}
}
public FlushMode getFlushmode() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getFlushmode();
} else {
return IConnection.DEFAULT_FLUSH_MODE;
}
}
public void setOption(String name, Object value) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setOption(name, value);
}
}
public Object getOption(String name) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
return holder.getConnection().getOption(name);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelRuntimeException();
}
}
public long getNumberOfReceivedBytes() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if ((holder != null)) {
return holder.getConnection().getNumberOfReceivedBytes() - initialReceivedBytes;
} else {
throw newClosedChannelRuntimeException();
}
}
public long getNumberOfSendBytes() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if ((holder != null)) {
return holder.getConnection().getNumberOfSendBytes() - initialSendBytes;
} else {
throw newClosedChannelRuntimeException();
}
}
@SuppressWarnings("unchecked")
public Map<String, Class> getOptions() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getOptions();
} else {
throw newClosedChannelRuntimeException();
}
}
public void setWriteTransferRate(int bytesPerSecond) throws ClosedChannelException, IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().setWriteTransferRate(bytesPerSecond);
} catch (IOException ioe) {
destroy();
throw ioe;
}
}
}
public int getWriteTransferRate() throws ClosedChannelException, IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
return holder.getConnection().getWriteTransferRate();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
return INonBlockingConnection.UNLIMITED;
}
}
public int getMaxReadBufferThreshold() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getMaxReadBufferThreshold();
} else {
return Integer.MAX_VALUE;
}
}
public void setMaxReadBufferThreshold(int size) {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setMaxReadBufferThreshold(size);
}
}
public void setConnectionTimeoutMillis(long timeoutMillis) {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setConnectionTimeoutMillis(timeoutMillis);
}
}
public long getConnectionTimeoutMillis() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getConnectionTimeoutMillis();
} else {
return Long.MAX_VALUE;
}
}
public void setIdleTimeoutMillis(long timeoutInMillis) {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().setIdleTimeoutMillis(timeoutInMillis);
isIdleTimeoutOccured.set(false);
} else {
throw newClosedChannelRuntimeException();
}
}
public long getIdleTimeoutMillis() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getIdleTimeoutMillis();
} else {
return Long.MAX_VALUE;
}
}
public long getRemainingMillisToConnectionTimeout() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getConnectionTimeoutMillis();
} else {
return Long.MAX_VALUE;
}
}
public long getRemainingMillisToIdleTimeout() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getRemainingMillisToIdleTimeout();
} else {
return Long.MAX_VALUE;
}
}
public boolean isSecure() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().isSecure();
} else {
throw newClosedChannelRuntimeException();
}
}
public void activateSecuredMode() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().activateSecuredMode();
} catch (IOException ioe) {
destroy();
throw ioe;
}
}
}
public void deactivateSecuredMode() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().deactivateSecuredMode();
} catch (IOException ioe) {
destroy();
throw ioe;
}
}
}
public boolean isSecuredModeActivateable() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().isSecuredModeActivateable();
} else {
return false;
}
}
public void suspendReceiving() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().suspendReceiving();
} catch (IOException ioe) {
destroy();
throw ioe;
}
}
}
public boolean isReceivingSuspended() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().isReceivingSuspended();
} else {
return false;
}
}
public void resumeReceiving() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().resumeReceiving();
} catch (IOException ioe) {
destroy();
throw ioe;
}
}
}
public InetAddress getLocalAddress() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().getLocalAddress();
} else {
throw newClosedChannelRuntimeException();
}
}
public int getLocalPort() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().getLocalPort();
} else {
throw newClosedChannelRuntimeException();
}
}
public InetAddress getRemoteAddress() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().getRemoteAddress();
} else {
throw newClosedChannelRuntimeException();
}
}
public int getRemotePort() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().getRemotePort();
} else {
throw newClosedChannelRuntimeException();
}
}
public void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().write(buffers, writeCompletionHandler);
if (isAutoflush) {
flush();
}
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by writing " + DataConverter.toString(buffers) + " deregistering ");
}
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public long write(ByteBuffer[] buffers) throws IOException, BufferOverflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
long written = holder.getConnection().write(buffers);
if (isAutoflush) {
flush();
}
return written;
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public int write(ByteBuffer buffer) throws IOException, BufferOverflowException {
return (int) write(new ByteBuffer[] { buffer });
}
public void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(new ByteBuffer[] { buffer }, writeCompletionHandler);
}
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
return write(DataConverter.toByteBuffers(srcs, offset, length));
}
public void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffers(srcs, offset, length), writeCompletionHandler);
}
public long write(List<ByteBuffer> buffers) throws IOException, BufferOverflowException {
return write(buffers.toArray(new ByteBuffer[buffers.size()]));
}
public void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(buffers.toArray(new ByteBuffer[buffers.size()]), writeCompletionHandler);
}
public void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffer(bytes), writeCompletionHandler);
}
public int write(byte[] bytes, int offset, int length) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(bytes, offset, length));
}
public void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffer(bytes, offset, length), writeCompletionHandler);
}
public int write(byte b) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(b));
}
public int write(byte... bytes) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(bytes));
}
public int write(long l) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(l));
}
public int write(double d) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(d));
}
public int write(int i) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(i));
}
public int write(short s) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(s));
}
public int write(String message) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(message, getEncoding()));
}
public int write(String message, String encoding) throws IOException, BufferOverflowException {
return write(DataConverter.toByteBuffer(message, encoding));
}
public void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException {
write(DataConverter.toByteBuffer(message, encoding), writeCompletionHandler);
}
public void flush() throws ClosedChannelException, IOException, SocketTimeoutException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().flush();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public long transferFrom(FileChannel fileChannel) throws IOException, BufferOverflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
if (getFlushmode() == FlushMode.SYNC) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("tranfering file by using MappedByteBuffer (MAX_MAP_SIZE=" + AbstractNonBlockingStream.TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE + ")");
}
final long size = fileChannel.size();
long remaining = size;
long offset = 0;
long length = 0;
do {
if (remaining > AbstractNonBlockingStream.TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE) {
length = AbstractNonBlockingStream.TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE;
} else {
length = remaining;
}
MappedByteBuffer buffer = fileChannel.map(MapMode.READ_ONLY, offset, length);
long written = write(buffer);
offset += written;
remaining -= written;
} while (remaining > 0);
return size;
} else {
return transferFrom((ReadableByteChannel) fileChannel);
}
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public long transferFrom(ReadableByteChannel source) throws IOException, BufferOverflowException {
return transferFrom(source, AbstractNonBlockingStream.TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE);
}
public long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException, BufferOverflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
long transfered = 0;
int read = 0;
do {
ByteBuffer transferBuffer = ByteBuffer.allocate(chunkSize);
read = source.read(transferBuffer);
if (read > 0) {
if (transferBuffer.remaining() == 0) {
transferBuffer.flip();
write(transferBuffer);
} else {
transferBuffer.flip();
write(transferBuffer.slice());
}
transfered += read;
}
} while (read > 0);
return transfered;
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public int getPendingWriteDataSize() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().getPendingWriteDataSize();
} else {
throw newClosedChannelRuntimeException();
}
}
public void markWritePosition() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().markWritePosition();
} else {
throw newClosedChannelRuntimeException();
}
}
public void removeWriteMark() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().removeWriteMark();
}
}
public boolean resetToWriteMark() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().resetToWriteMark();
} else {
throw newClosedChannelRuntimeException();
}
}
public void markReadPosition() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().markReadPosition();
} else {
throw newClosedChannelRuntimeException();
}
}
public void removeReadMark() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
holder.getConnection().removeReadMark();
}
}
public boolean resetToReadMark() {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
return holder.getConnection().resetToReadMark();
} else {
throw newClosedChannelRuntimeException();
}
}
public int available() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().available();
} else {
return -1;
}
}
public int getReadBufferVersion() throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
return holder.getConnection().getReadBufferVersion();
} else {
return -1;
}
}
public int indexOf(String str) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().indexOf(str);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
return -1;
}
}
public int indexOf(String str, String encoding) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().indexOf(str, encoding);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
return -1;
}
}
public void unread(ByteBuffer[] buffers) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().unread(buffers);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelRuntimeException();
}
}
public void unread(byte[] bytes) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().unread(bytes);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelRuntimeException();
}
}
public void unread(ByteBuffer buffer) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().unread(buffer);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelRuntimeException();
}
}
public void unread(String text) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (isOpen && (holder != null)) {
try {
holder.getConnection().unread(text);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelRuntimeException();
}
}
public int read(ByteBuffer buffer) throws IOException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().read(buffer);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
return -1;
}
}
public byte readByte() throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readByte();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readByteBufferByDelimiter(delimiter);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readByteBufferByDelimiter(delimiter, maxLength);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readByteBufferByDelimiter(delimiter, encoding);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readByteBufferByDelimiter(delimiter, encoding, maxLength);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public ByteBuffer[] readByteBufferByLength(int length) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readByteBufferByLength(length);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public byte[] readBytesByDelimiter(String delimiter) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readBytesByDelimiter(delimiter);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public byte[] readBytesByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readBytesByDelimiter(delimiter, maxLength);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readBytesByDelimiter(delimiter, encoding);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readBytesByDelimiter(delimiter, encoding, maxLength);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public byte[] readBytesByLength(int length) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readBytesByLength(length);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public double readDouble() throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readDouble();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public int readInt() throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readInt();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public long readLong() throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readLong();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public short readShort() throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readShort();
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public String readStringByDelimiter(String delimiter) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readStringByDelimiter(delimiter);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public String readStringByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readStringByDelimiter(delimiter, maxLength);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readStringByDelimiter(delimiter, encoding);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readStringByDelimiter(delimiter, encoding, maxLength);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public String readStringByLength(int length) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readStringByLength(length);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().readStringByLength(length, encoding);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
public long transferTo(WritableByteChannel target, int length) throws IOException, BufferUnderflowException {
NativeConnectionHolder holder = nativeConnectionHolderRef.get();
if (holder != null) {
try {
return holder.getConnection().transferTo(target, length);
} catch (IOException ioe) {
destroy();
throw ioe;
}
} else {
throw newClosedChannelException();
}
}
private ExtendedClosedChannelException newClosedChannelException() {
return new ExtendedClosedChannelException("channel " + getId() + " is already closed");
}
private RuntimeException newClosedChannelRuntimeException() {
return new RuntimeException("channel " + getId() + " is already closed");
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/connection/NonBlockingConnectionPool.java | Java | art | 127,839 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body bgcolor="white">
Provides shared classes for nio-based network applications.<br>
</body>
</html>
| zzh-simple-hr | Zxsocket/src/org/xsocket/package.html | HTML | art | 189 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.DynamicMBean;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.ReflectionException;
/**
* Introspection based dynamic mbean, which exposes the getter and setter methods
* (default, protected and public visibility) of the underlying object by using introspection <br>
*
* <br/><br/><b>This is a xSocket internal class and subject to change</b>
*
* @author grro@xsocket.org
*/
public final class IntrospectionBasedDynamicMBean implements DynamicMBean {
private static final Logger LOG = Logger.getLogger(IntrospectionBasedDynamicMBean.class.getName());
private Object obj;
private final Map<String, Info> properties = new HashMap<String, Info>();
/**
* constructor
*
* @param obj the object to create a mbean for
*/
public IntrospectionBasedDynamicMBean(Object obj) {
this.obj = obj;
}
/**
* @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/
public Object getAttribute(String attribute) {
String methodName = "get" + attribute;
try {
Method method = getMethod(obj.getClass(), methodName, new Class[0]);
if (method == null) {
methodName = "is" + attribute;
method = getMethod(obj.getClass(), methodName, new Class[0]);
}
method.setAccessible(true);
return method.invoke(obj, new Object[0]);
} catch (InvocationTargetException ite) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured (InvocationTargetException) by accessing attribute " + attribute + ": " + ite.toString());
}
return null;
} catch (IllegalAccessException iae) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured (IllegalAccessException) by accessing attribute " + attribute + ": " + iae.toString());
}
return null;
}
}
@SuppressWarnings("unchecked")
private Method getMethod(Class clazz, String methodname, Class[] params) {
do {
try {
Method method = clazz.getDeclaredMethod(methodname, params);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException ignore) { }
for (Class interf : clazz.getInterfaces()) {
getMethod(interf, methodname, params);
}
clazz = clazz.getSuperclass();
} while (clazz != null);
return null;
}
/**
* {@inheritDoc}
*/
public AttributeList getAttributes(String[] attributes) {
AttributeList list = new AttributeList();
for (String attribute : attributes) {
list.add(new Attribute(attribute, getAttribute(attribute)));
}
return list;
}
/**
* {@inheritDoc}
*/
public void setAttribute(Attribute attribute) {
String methodName = "set" + attribute.getName();
Info info = getInfo(attribute.getName());
try {
Method method = getMethod(obj.getClass(), methodName, new Class[] { info.propertyType });
method.setAccessible(true);
method.invoke(obj, new Object[] { attribute.getValue() });
} catch (InvocationTargetException ite) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured (InvocationTargetException) by setting attribute " + ite.toString());
}
} catch (IllegalAccessException iae) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured (IllegalAccessException) by setting attribute " + iae.toString());
}
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public AttributeList setAttributes(AttributeList attributes) {
AttributeList result = new AttributeList();
Attribute[] attrs = (Attribute[]) attributes.toArray(new Attribute[attributes.size()]);
for (Attribute attr : attrs) {
setAttribute(attr);
result.add(new Attribute(attr.getName(), attr.getValue()));
}
return result;
}
/**
* {@inheritDoc}
*/
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
return null;
}
/**
* {@inheritDoc}
*/
public synchronized MBeanInfo getMBeanInfo() {
analyze(obj);
String[] attributes = properties.keySet().toArray(new String[properties.size()]);
MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[attributes.length];
for (int i = 0; i < attrs.length; i++) {
attrs[i] = properties.get(attributes[i]).asbMBeanAttributeInfo();
}
return new MBeanInfo(
obj.getClass().getName(),
"",
attrs,
null, // constructors
null,
null); // notifications
}
@SuppressWarnings("unchecked")
private void analyze(Object obj) {
Class clazz = obj.getClass();
do {
analyzeType(clazz);
for (Class interf: clazz.getInterfaces()) {
analyzeType(interf);
}
clazz = clazz.getSuperclass();
} while (clazz != null);
}
@SuppressWarnings("unchecked")
private void analyzeType(Class clazz) {
for (Method method : clazz.getDeclaredMethods()) {
String name = method.getName();
if (Modifier.isPrivate(method.getModifiers())) {
continue;
}
if ((name.length() > 3) && name.startsWith("get") && (method.getParameterTypes().length == 0)) {
Class propertyType = method.getReturnType();
if(isAcceptedPropertyType(propertyType)) {
Info info = getInfo(name.substring(3, name.length()));
info.isReadable = true;
info.propertyType = propertyType;
}
}
if ((name.length() > 2) && name.startsWith("is") && (method.getParameterTypes().length == 0)) {
Class propertyType = method.getReturnType();
if(isAcceptedPropertyType(propertyType)) {
Info info = getInfo(name.substring(2, name.length()));
info.isReadable = true;
info.propertyType = propertyType;
}
}
if ((name.length() > 3) && name.startsWith("set") && (method.getParameterTypes().length == 1)) {
Class propertyType = method.getParameterTypes()[0];
if(isAcceptedPropertyType(propertyType)) {
Info info = getInfo(name.substring(3, name.length()));
info.isWriteable = true;
info.propertyType = propertyType;
}
}
}
}
private Info getInfo(String name) {
Info info = properties.get(name);
if (info == null) {
info = new Info();
info.propertyName = name;
info.propertyDescription = "Property " + info.propertyName;
properties.put(name, info);
}
return info;
}
@SuppressWarnings("unchecked")
private boolean isAcceptedPropertyType(Class clazz) {
if (clazz.isAssignableFrom(List.class)) {
return true;
}
String name = clazz.getName();
return name.equals("int")
|| name.equals("java.lang.Integer")
|| name.equals("long")
|| name.equals("java.lang.Long")
|| name.equals("double")
|| name.equals("java.lang.Double")
|| name.equals("boolean")
|| name.equals("java.lang.Boolean")
|| name.equals("float")
|| name.equals("java.lang.String")
|| name.equals("java.util.Date")
|| name.equals("java.lang.Float");
}
private static class Info {
String propertyName = null;
@SuppressWarnings("unchecked")
Class propertyType = null;
String propertyDescription = null;
boolean isReadable = false;
boolean isWriteable = false;
boolean isIs = false;
MBeanAttributeInfo asbMBeanAttributeInfo() {
return new MBeanAttributeInfo(propertyName, propertyType.getName(), propertyDescription, isReadable, isWriteable, isIs);
}
}
} | zzh-simple-hr | Zxsocket/src/org/xsocket/IntrospectionBasedDynamicMBean.java | Java | art | 9,060 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation which defines if a method <i>should</i> be called in
* multithreaded context (default) or not. This annotation can be used
* to declare the desired execution modus of a call back method such as
* <code>onConnect</code> or <code>onData</code>. xSocket is free to
* perform a NONTHREADED-annotated method in a MULTITHREADED mode.
*
* E.g.
* <pre>
* class SmtpProtcolHandler implements IDataHandler, IConnectHandler {
* ...
*
* @Execution(Execution.NONTHREADED) // default is multithreaded
* public boolean onConnect(INonBlockingConnection connection) throws IOException {
* connection.write("220 my smtp server" + LINE_DELIMITER);
* return true;
* }
*
*
*
* public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException {
* ...
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Execution {
public static final int NONTHREADED = 0;
public static final int MULTITHREADED = 1;
int value() default MULTITHREADED;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/Execution.java | Java | art | 2,410 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.net.SocketAddress;
/**
* An connected endpoint, which receives/sends data only from/to from the assigned connected endpoint. E.g.
*
* <pre>
* ...
* IConnectedEndpoint endpoint = new ConnectedEndpoint(remoteHostname, remotePort, packageSize);
*
* UserDatagram request = new UserDatagram(packageSize);
* request.write("Hello peer, how are you?");
*
* endpoint.send(request);
* UserDatagram response = endpoint.receive(1000); // receive (timeout 1 sec)
*
* endpoint.close();
* ...
* </pre>
*
* @author grro@xsocket.org
*/
public interface IConnectedEndpoint extends IEndpoint {
/**
* return the connected remote address or null if not connected
*
* @return the connected address
*/
SocketAddress getRemoteSocketAddress();
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/IConnectedEndpoint.java | Java | art | 1,856 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* Implementation of the {@link IDispatcher}
*
* <br/><br/><b>This is a xSocket internal class and subject to change</b>
*
* @author grro@xsocket.org
*/
final class IoSocketDispatcher implements Runnable, Closeable {
private static final Logger LOG = Logger.getLogger(IoSocketDispatcher.class.getName());
static final String DISPATCHER_PREFIX = "xDispatcher";
private static final long TIMEOUT_SHUTDOWN_MILLIS = 5L * 1000L;
// queues
private final Queue<AbstractChannelBasedEndpoint> registerQueue = new ConcurrentLinkedQueue<AbstractChannelBasedEndpoint>();
private final Queue<AbstractChannelBasedEndpoint> deregisterQueue = new ConcurrentLinkedQueue<AbstractChannelBasedEndpoint>();
private final Queue<KeyUpdateTask> keyUpdateQueue = new ConcurrentLinkedQueue<KeyUpdateTask>();
// is open flag
private volatile boolean isOpen = true;
// connection handling
private final Selector selector;
// statistics
private long handledRegistractions ;
private long handledReads;
private long handledWrites;
/**
* constructor
*
*/
public IoSocketDispatcher() {
try {
selector = Selector.open();
} catch (IOException ioe) {
String text = "exception occured while opening selector. Reason: " + ioe.toString();
LOG.severe(text);
throw new RuntimeException(text, ioe);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public void run() {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("selector listening ...");
}
int handledTasks = 0;
while(isOpen) {
try {
int eventCount = selector.select();
handledTasks = performRegisterHandlerTasks();
handledTasks += performKeyUpdateTasks();
// handle read write events
if (eventCount > 0) {
Set selectedEventKeys = selector.selectedKeys();
Iterator it = selectedEventKeys.iterator();
// handle read & write
while (it.hasNext()) {
SelectionKey eventKey = (SelectionKey) it.next();
it.remove();
AbstractChannelBasedEndpoint handler = (AbstractChannelBasedEndpoint) eventKey.attachment();
// read data
if (eventKey.isValid() && eventKey.isReadable()) {
onReadableEvent(handler);
}
// write data
if (eventKey.isValid() && eventKey.isWritable()) {
onWriteableEvent(handler);
}
}
}
handledTasks += performDeregisterHandlerTasks();
} catch (Exception e) {
// eat and log exception
LOG.warning("[" + Thread.currentThread().getName() + "] exception occured while processing. Reason " + DataConverter.toString(e));
}
}
closeDispatcher();
}
private void onReadableEvent(AbstractChannelBasedEndpoint handler) {
try {
handler.onReadableEvent();
} catch (Exception e) {
// eat and log exception
LOG.warning("[" + Thread.currentThread().getName() + "] exception occured while handling readable event. Reason " + DataConverter.toString(e));
}
handledReads++;
}
private void onWriteableEvent(AbstractChannelBasedEndpoint handler) {
try {
handler.onWriteableEvent();
} catch (Exception e) {
// eat and log exception
LOG.warning("[" + Thread.currentThread().getName() + "] exception occured while handling writeable event. Reason " + DataConverter.toString(e));
}
handledWrites++;
}
/**
* {@inheritDoc}
*/
public void register(AbstractChannelBasedEndpoint handler) {
assert (!handler.getChannel().isBlocking());
boolean isWakeUpRequired = false;
if (registerQueue.isEmpty()) {
isWakeUpRequired = true;
}
registerQueue.add(handler);
if (isWakeUpRequired) {
wakeUp();
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("does not wake up selector, because register queue handling is currently running");
}
}
}
/**
* {@inheritDoc}
*/
public void deregister(AbstractChannelBasedEndpoint handler) {
boolean isWakeUpRequired = false;
if (deregisterQueue.isEmpty()) {
isWakeUpRequired = true;
}
deregisterQueue.add(handler);
if (isWakeUpRequired) {
wakeUp();
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("does not wake up selector, because deregister queue handling is currently running");
}
}
}
void wakeUp() {
selector.wakeup();
}
void setSelectionKeyToReadImmediately(final AbstractChannelBasedEndpoint handler) {
SelectionKey key = handler.getChannel().keyFor(selector);
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
}
private void setSelectionKeyToWriteImmediate(final AbstractChannelBasedEndpoint handler) {
SelectionKey key = handler.getChannel().keyFor(selector);
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
}
void initiateRead(final AbstractChannelBasedEndpoint handler) {
KeyUpdateTask task = new KeyUpdateTask(handler) {
public void run() {
setSelectionKeyToReadImmediately(handler);
}
};
keyUpdateQueue.add(task);
wakeUp();
}
void initiateWrite(final AbstractChannelBasedEndpoint handler) {
KeyUpdateTask task = new KeyUpdateTask(handler) {
public void run() {
setSelectionKeyToWriteImmediate(handler);
}
};
keyUpdateQueue.add(task);
wakeUp();
}
private int performRegisterHandlerTasks() throws IOException {
int handledTasks = 0;
while (true) {
AbstractChannelBasedEndpoint handler = registerQueue.poll();
if (handler == null) {
return handledTasks;
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("registering handler " + handler);
}
if (handler.getChannel().isOpen()) {
handler.getChannel().register(selector, SelectionKey.OP_READ, handler);
handledRegistractions++;
handledTasks++;
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("channel " + handler.getId() + " is already closed. Could not register it");
}
}
}
}
private int performKeyUpdateTasks() {
int handledTasks = 0;
while (true) {
KeyUpdateTask keyUpdateTask = keyUpdateQueue.poll();
if (keyUpdateTask == null) {
return handledTasks;
}
keyUpdateTask.init();
if (keyUpdateTask.getKey() != null) {
if (keyUpdateTask.getKey().isValid()) {
keyUpdateTask.run();
} else {
keyUpdateTask.getKey().cancel();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("handler " + keyUpdateTask.getHandler() + " (key) is invalid. ignore it");
}
}
}
handledTasks++;
}
}
private int performDeregisterHandlerTasks() {
int handledTasks = 0;
while (true) {
AbstractChannelBasedEndpoint handler = deregisterQueue.poll();
if (handler == null) {
return handledTasks;
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("registering handler " + handler);
}
SelectionKey key = handler.getChannel().keyFor(selector);
if ((key != null) && key.isValid()) {
key.cancel();
}
handledTasks++;
}
}
/**
* {@inheritDoc}
*/
public Set<AbstractChannelBasedEndpoint> getRegistered() {
Set<AbstractChannelBasedEndpoint> registered = new HashSet<AbstractChannelBasedEndpoint>();
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
AbstractChannelBasedEndpoint handler = (AbstractChannelBasedEndpoint) key.attachment();
registered.add(handler);
}
return registered;
}
private void closeDispatcher() {
LOG.fine("closing connections");
if (selector != null) {
try {
selector.close();
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by close selector within tearDown " + DataConverter.toString(e));
}
}
}
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
if (selector != null) {
Set<AbstractChannelBasedEndpoint> registered = getRegistered();
// initiate closing of open connections
for (AbstractChannelBasedEndpoint endpoint : registered) {
endpoint.onDispatcherClose();
}
// start closer thread
new Thread(new Closer(registered.size())).start();
}
}
/**
* returns if the dispatcher is open
*
* @return true, if the dispatcher is open
*/
public boolean isOpen() {
return isOpen;
}
/**
* statistic method which returns the number handled registrations
* @return the number handled registrations
*/
public long getNumberOfHandledRegistrations() {
return handledRegistractions;
}
/**
* statistic method which returns the number of handled reads
*
* @return the number of handled reads
*/
public long getNumberOfHandledReads() {
return handledReads;
}
/**
* statistic method which returns the number of handled writes
*
* @return the number of handled writes
*/
public long getNumberOfHandledWrites() {
return handledWrites;
}
@Override
public String toString() {
return "open channels " + getRegistered().size();
}
private class KeyUpdateTask implements Runnable {
private AbstractChannelBasedEndpoint handler = null;
private SelectionKey key = null;
public KeyUpdateTask(AbstractChannelBasedEndpoint handler) {
this.handler = handler;
}
void init() {
key = handler.getChannel().keyFor(selector);
}
AbstractChannelBasedEndpoint getHandler() {
return handler;
}
SelectionKey getKey() {
return key;
}
public void run() {
}
}
private class Closer implements Runnable {
private int openConnections = 0;
public Closer(int openConnections) {
this.openConnections = openConnections;
}
public void run() {
Thread.currentThread().setName("xDispatcherCloser");
long start = System.currentTimeMillis();
int terminatedConnections = 0;
do {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
if (System.currentTimeMillis() > (start + TIMEOUT_SHUTDOWN_MILLIS)) {
LOG.warning("shutdown timeout reached (" + DataConverter.toFormatedDuration(TIMEOUT_SHUTDOWN_MILLIS) + "). kill pending connections");
for (SelectionKey sk : selector.keys()) {
try {
terminatedConnections++;
sk.channel().close();
} catch (IOException ioe) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing " + ioe.toString());
}
}
}
break;
}
} while (getRegistered().size() > 0);
isOpen = false;
// wake up selector, so that isRunning-loop can be terminated
selector.wakeup();
if (((openConnections > 0) || (terminatedConnections > 0)) && ((openConnections > 0) && (terminatedConnections > 0))) {
LOG.info((openConnections - terminatedConnections) + " connections has been closed properly, "
+ terminatedConnections + " connections has been terminate unclean");
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("dispatcher " + this.hashCode() + " has been closed (shutdown time = " + DataConverter.toFormatedDuration(System.currentTimeMillis() - start) + ")");
}
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/IoSocketDispatcher.java | Java | art | 13,116 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
/**
* Endpoint handler, which will be used by receiving a datagram in a asynchronous manner. E.g.
*
* <pre>
* class MyHandler implements IDatagramHandler {
*
* public boolean onDatagram(IEndpoint localEndpoint) throws IOException {
* UserDatagram datagram = localEndpoint.receive(); // get the datagram
* ...
* return true; // true -> signal that this event has been handled
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public interface IDatagramHandler {
/**
* signals a incoming datagram
*
* @param localEndpoint the local endpoint
* @return true if the event has been handled
* @throws IOException If some other I/O error occurs
*/
boolean onDatagram(IEndpoint localEndpoint) throws IOException;
} | zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/IDatagramHandler.java | Java | art | 1,883 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body bgcolor="white">
Provides classes to send or receive datagram packets in a unicast and multicast
mode (one-to-many interaction) on the server and on the client side.<br>
Each packet sent or received on a Datagram socket is individually addressed
and routed. Multiple packets sent from one machine to another using
connection less may be routed differently, and may arrive in any order. <br>
</body>
</html>
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/package.html | HTML | art | 505 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import org.xsocket.DataConverter;
import org.xsocket.IDataSink;
import org.xsocket.IDataSource;
import org.xsocket.MaxReadSizeExceededException;
/**
* a datagram packet
*
*
* @author grro@xsocket.org
*/
public final class UserDatagram implements IDataSource, IDataSink {
private SocketAddress remoteSocketAddress = null;
private ByteBuffer data;
private String defaultEncoding = "UTF-8";
/**
* constructor. creates an empty packet
*
* @param size the packet size
*/
public UserDatagram(int size) {
init(remoteSocketAddress, ByteBuffer.allocate(size));
}
/**
* constructor. creates an empty packet by setting the target remote address
*
* @param remoteHost the destination hostname
* @param remotePort the destination port number
* @param size the packet size
*/
public UserDatagram(String remoteHost, int remotePort, int size) {
init(new InetSocketAddress(remoteHost, remotePort), ByteBuffer.allocate(size));
}
/**
* constructor. creates an empty packet by setting the target remote address
*
* @param remoteAddress the destination address
* @param remotePort the destination port number
* @param size the packet size
*/
public UserDatagram(InetAddress remoteAddress, int remotePort, int size) {
init(new InetSocketAddress(remoteAddress, remotePort), ByteBuffer.allocate(size));
}
/**
* constructor. creates an empty packet by setting the target remote address
*
* @param address the destination address
* @param size the packet size
*/
public UserDatagram(SocketAddress address, int size) {
init(address, ByteBuffer.allocate(size));
}
/**
* constructor. creates packet, and sets the content with the given buffer
*
* @param data the data which will be written into the buffer
*/
public UserDatagram(ByteBuffer data) {
this(null, data);
}
/**
* constructor. creates packet by setting the target remote address,
* and sets the content with the given buffer
*
* @param remoteSocketAddress the destination address
* @param data the data which will be written into the buffer
*/
public UserDatagram(SocketAddress remoteSocketAddress, ByteBuffer data) {
this(remoteSocketAddress, data, "UTF-8");
}
/**
* constructor. creates packet by setting the target remote address,
* and sets the content with the given buffer
*
* @param remoteSocketAddress the destination address
* @param data the data which will be written into the buffer
* @param defaultEncoding the default encoding to use
*/
UserDatagram(SocketAddress remoteSocketAddress, ByteBuffer data, String defaultEncoding) {
init(remoteSocketAddress, data);
this.defaultEncoding = defaultEncoding;
}
/**
* constructor. creates packet sets the content with the given byte array
*
* @param data the data which will be written into the buffer
*/
public UserDatagram(byte[] data) {
this(null, data);
}
/**
* constructor. creates packet by setting the target remote address,
* and sets the content with the given byte array
*
* @param remoteHost the destination hostname
* @param remotePort the destination port number
* @param data the data which will be written into the buffer
*/
public UserDatagram(String remoteHost, int remotePort, byte[] data) {
this(new InetSocketAddress(remoteHost, remotePort), data);
}
/**
* constructor. creates packet by setting the target remote address,
* and sets the content with the given byte array
*
* @param remoteSocketAddress the destination address
* @param data the data which will be written into the buffer
*/
public UserDatagram(SocketAddress remoteSocketAddress, byte[] data) {
ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.position(buffer.limit());
init(remoteSocketAddress, buffer);
}
private void init(SocketAddress remoteSocketAddress, ByteBuffer data) {
this.remoteSocketAddress = remoteSocketAddress;
this.data = data;
}
/**
* prepares the packet to send
*
*/
void prepareForSend() {
data.clear();
}
/**
* set the remote socket address
* @param remoteSocketAddress the remote socket address
*/
void setRemoteAddress(SocketAddress remoteSocketAddress) {
this.remoteSocketAddress = remoteSocketAddress;
}
/**
* return the underlying data buffer
*
* @return the underlying data buffer
*/
protected ByteBuffer getData() {
return data;
}
public String getEncoding() {
return defaultEncoding;
}
public void setEncoding(String encoding) {
this.defaultEncoding = encoding;
}
/**
* Returns the socket address of the machine to which this packet is being sent
* or from which the packet was received.
*
* @return the socket address
*/
public SocketAddress getRemoteSocketAddress() {
return remoteSocketAddress;
}
/**
* Returns the address of the machine to which this packet is being sent
* or from which the packet was received.
*
* @return the address
*/
public InetAddress getRemoteAddress() {
if (remoteSocketAddress instanceof InetSocketAddress) {
return ((InetSocketAddress) remoteSocketAddress).getAddress();
} else {
return null;
}
}
/**
* Returns the port number of the machine to which this packet is being sent
* or from which the packet was received.
*
* @return the port number
*/
public int getRemotePort() {
if (remoteSocketAddress instanceof InetSocketAddress) {
return ((InetSocketAddress) remoteSocketAddress).getPort();
} else {
return -1;
}
}
/**
* read a byte
*
* @return the byte value
* @throws BufferUnderflowException if the buffer`s limit has been reached
* @throws IOException If some other I/O error occurs
*/
public byte readByte() throws IOException, BufferUnderflowException {
return data.get();
}
/**
* read a ByteBuffer by using a length defintion
*
* @param length the amount of bytes to read
* @return the ByteBuffer
* @throws BufferUnderflowException if the buffer`s limit has been reached
* @throws IOException If some other I/O error occurs
*/
public ByteBuffer readSingleByteBufferByLength(int length) throws IOException, BufferUnderflowException {
if (length <= 0) {
if (length == 0) {
return ByteBuffer.allocate(0);
} else {
throw new IllegalArgumentException("length has to be positive");
}
}
int savedLimit = data.limit();
int savedPosition = data.position();
data.limit(data.position() + length);
ByteBuffer sliced = data.slice();
data.position(savedPosition + length);
data.limit(savedLimit);
return sliced;
}
/**
* {@inheritDoc}
*/
public byte[] readBytesByLength(int length) throws IOException, BufferUnderflowException {
return DataConverter.toBytes(readByteBufferByLength(length));
}
/**
* {@inheritDoc}
*/
public String readStringByLength(int length, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
return DataConverter.toString(readByteBufferByLength(length), encoding);
}
/**
* {@inheritDoc}
*/
public String readStringByLength(int length) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
return readStringByLength(length, defaultEncoding);
}
/**
* {@inheritDoc}
*/
public double readDouble() throws IOException, BufferUnderflowException {
return data.getDouble();
}
/**
* {@inheritDoc}
*/
public int readInt() throws IOException, BufferUnderflowException {
return data.getInt();
}
/**
* {@inheritDoc}
*/
public short readShort() throws IOException, BufferUnderflowException {
return data.getShort();
}
/**
* {@inheritDoc}
*/
public long readLong() throws IOException, BufferUnderflowException {
return data.getLong();
}
/**
* {@inheritDoc}
*/
public ByteBuffer readByteBuffer() throws IOException, BufferUnderflowException {
ByteBuffer sliced = data.slice();
data.position(data.limit());
return sliced;
}
/**
* {@inheritDoc}
*/
public byte[] readBytes() throws IOException, BufferUnderflowException {
return DataConverter.toBytes(readByteBuffer());
}
/**
* {@inheritDoc}
*/
public String readString() throws IOException, BufferUnderflowException, UnsupportedEncodingException {
return readString(defaultEncoding);
}
/**
* {@inheritDoc}
*/
public String readString(String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
return DataConverter.toString(readByteBuffer(), encoding);
}
/**
* {@inheritDoc}
*/
public int read(ByteBuffer buffer) throws IOException {
int size = buffer.remaining();
int available = buffer.remaining();
if (available == 0) {
return -1;
}
if (available < size) {
size = available;
}
if (size > 0) {
ByteBuffer[] bufs = readByteBufferByLength(size);
for (ByteBuffer buf : bufs) {
while (buf.hasRemaining()) {
buffer.put(buf);
}
}
}
return size;
}
/**
* {@inheritDoc}
*/
public String readStringByDelimiter(String delimiter) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
return readStringByDelimiter(delimiter, defaultEncoding);
}
/**
* {@inheritDoc}
*/
public String readStringByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException, UnsupportedEncodingException {
return readStringByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public String readStringByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
return readStringByDelimiter(delimiter, defaultEncoding, maxLength);
}
/**
* {@inheritDoc}
*/
public String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, UnsupportedEncodingException, MaxReadSizeExceededException {
return DataConverter.toString(readByteBufferByDelimiter(delimiter, encoding, maxLength), encoding);
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter) throws IOException, BufferUnderflowException {
return readByteBufferByDelimiter(delimiter, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
return readByteBufferByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return readByteBufferByDelimiter(delimiter, defaultEncoding, maxLength);
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return new ByteBuffer[] { readSingleByteBufferByDelimiter(delimiter, encoding, maxLength) };
}
/**
* {@inheritDoc}
*/
public ByteBuffer[] readByteBufferByLength(int length) throws IOException, BufferUnderflowException {
return new ByteBuffer[] { readSingleByteBufferByLength(length) };
}
/**
* {@inheritDoc}
*/
public ByteBuffer readSingleByteBufferByDelimiter(String delimiter) throws IOException, BufferUnderflowException {
return readSingleByteBufferByDelimiter(delimiter, defaultEncoding);
}
/**
* {@inheritDoc}
*/
public ByteBuffer readSingleByteBufferByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
return readSingleByteBufferByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public ByteBuffer readSingleByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
byte[] delimiterBytes = delimiter.getBytes(encoding);
int startPos = findDelimiter(data, delimiterBytes, maxLength);
if (startPos >= 0) {
int savedLimit = data.limit();
data.limit(startPos);
ByteBuffer result = data.slice();
data.limit(savedLimit);
data.position(startPos + delimiterBytes.length);
return result;
} else {
throw new BufferUnderflowException();
}
}
/**
* {@inheritDoc}
*/
public byte[] readBytesByDelimiter(String delimiter) throws IOException, BufferUnderflowException {
return readBytesByDelimiter(delimiter, defaultEncoding);
}
/**
* {@inheritDoc}
*/
public byte[] readBytesByDelimiter(String delimiter, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return readBytesByDelimiter(delimiter, defaultEncoding, maxLength);
}
/**
* {@inheritDoc}
*/
public byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, BufferUnderflowException {
return readBytesByDelimiter(delimiter, encoding, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return DataConverter.toBytes(readByteBufferByDelimiter(delimiter, defaultEncoding, maxLength));
}
public long transferTo(WritableByteChannel target, int length) throws IOException, ClosedChannelException, BufferUnderflowException {
long written = 0;
ByteBuffer[] buffers = readByteBufferByLength(length);
for (ByteBuffer buffer : buffers) {
written += target.write(buffer);
}
return written;
}
private static int findDelimiter(ByteBuffer buffer, byte[] delimiter, int maxLength) throws MaxReadSizeExceededException {
int result = -1;
int delimiterPosition = 0;
// iterator over buffer content
for (int pos = buffer.position(); pos < buffer.limit(); pos++) {
byte b = buffer.get(pos);
if (b == delimiter[delimiterPosition]) {
delimiterPosition++;
if (delimiterPosition == delimiter.length) {
result = (pos - delimiterPosition + 1);
break;
}
} else {
delimiterPosition = 0;
}
}
if (result > maxLength) {
throw new MaxReadSizeExceededException();
}
return result;
}
/**
* {@inheritDoc}
*/
public int write(byte b) throws IOException, BufferOverflowException {
data.put(b);
return 1;
}
/**
* {@inheritDoc}
*/
public int write(short s) throws IOException, BufferOverflowException {
data.putShort(s);
return 2;
}
/**
* {@inheritDoc}
*/
public int write(byte... bytes) throws IOException, BufferOverflowException {
data.put(bytes);
return bytes.length;
}
/**
* {@inheritDoc}
*/
public int write(byte[] bytes, int offset, int length) throws IOException, BufferOverflowException {
data.put(bytes, offset, length);
return length;
}
/**
* {@inheritDoc}
*/
public int write(ByteBuffer buffer) throws IOException, BufferOverflowException {
int length = buffer.remaining();
data.put(buffer);
return length;
}
/**
* {@inheritDoc}
*/
public long write(ByteBuffer[] buffers) throws IOException, BufferOverflowException {
int length = 0;
for (ByteBuffer buffer : buffers) {
length += write(buffer);
}
return length;
}
/**
* {@inheritDoc}
*/
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
return write(DataConverter.toByteBuffers(srcs, offset, length));
}
/**
* {@inheritDoc}
*/
public long write(List<ByteBuffer> buffers) throws IOException, BufferOverflowException {
int length = 0;
for (ByteBuffer buffer : buffers) {
length += write(buffer);
}
return length;
}
/**
* {@inheritDoc}
*/
public int write(double d) throws IOException, BufferOverflowException {
data.putDouble(d);
return 8;
}
/**
* {@inheritDoc}
*/
public int write(int i) throws IOException, BufferOverflowException {
data.putInt(i);
return 4;
}
/**
* {@inheritDoc}
*/
public int write(long l) throws IOException, BufferOverflowException {
data.putLong(l);
return 8;
}
/**
* {@inheritDoc}
*/
public int write(String message) throws IOException, BufferOverflowException {
return write(message, defaultEncoding);
}
/**
* {@inheritDoc}
*/
public int write(String message, String encoding) throws IOException, BufferOverflowException {
byte[] bytes = message.getBytes(encoding);
data.put(bytes);
return bytes.length;
}
/**
* {@inheritDoc}
*/
public long transferFrom(FileChannel source) throws IOException, BufferOverflowException {
return transferFrom((ReadableByteChannel) source);
}
/**
* {@inheritDoc}
*/
public long transferFrom(ReadableByteChannel sourceChannel) throws IOException, BufferOverflowException {
return transferFrom(sourceChannel, 8196);
}
public long transferFrom(ReadableByteChannel sourceChannel, int chunkSize) throws IOException, BufferOverflowException {
long transfered = 0;
int read = 0;
do {
ByteBuffer transferBuffer = ByteBuffer.allocate(chunkSize);
read = sourceChannel.read(transferBuffer);
if (read > 0) {
if (transferBuffer.remaining() == 0) {
transferBuffer.flip();
write(transferBuffer);
} else {
transferBuffer.flip();
write(transferBuffer.slice());
}
transfered += read;
}
} while (read > 0);
return transfered;
}
/**
* get the packet size
*
* @return the packet size
*/
public int getSize() {
return data.limit();
}
/**
* get the remaining, unwritten packet size
*
* @return the remaining, unwritten packet size
*/
public int getRemaining() {
return data.remaining();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (remoteSocketAddress != null) {
sb.append("remoteAddress=" + remoteSocketAddress.toString() + " ");
} else {
sb.append("remoteAddress=null ");
}
if (data != null) {
ByteBuffer copy = data.duplicate();
copy.clear();
sb.append("data=" + DataConverter.toHexString(new ByteBuffer[] {copy}, 500) + " ");
} else {
sb.append("data=null ");
}
return sb.toString();
}
} | zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/UserDatagram.java | Java | art | 21,033 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* Endpoint implementation base
*
* @author grro@xsocket.org
*/
abstract class AbstractChannelBasedEndpoint extends AbstractEndpoint {
private static final Logger LOG = Logger.getLogger(AbstractChannelBasedEndpoint.class.getName());
private static final MemoryManager memoryManager = new MemoryManager(65536, false);
private static IoSocketDispatcher dispatcher = createDispatcher();
@SuppressWarnings("unchecked")
private static final Map<String ,Class> SUPPORTED_OPTIONS = new HashMap<String, Class>();
static {
SUPPORTED_OPTIONS.put(SO_RCVBUF, Integer.class);
SUPPORTED_OPTIONS.put(SO_SNDBUF, Integer.class);
SUPPORTED_OPTIONS.put(IP_TOS, Integer.class);
SUPPORTED_OPTIONS.put(SO_REUSEADDR, Boolean.class);
}
// socket
private final DatagramSocket socket;
private final DatagramChannel channel;
private final ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
// send queue
private final List<UserDatagram> sendQueue = Collections.synchronizedList(new LinkedList<UserDatagram>());
/**
* constructor
*
* @param addr the local address
* @param options the socket options
* @param datagramHandler the datagram handler
* @param receivePacketSize the receive packet size
* @param workerPool the workerpool to use
* @throws IOException If some I/O error occurs
*/
AbstractChannelBasedEndpoint(InetSocketAddress addr, Map<String, Object> options, IDatagramHandler datagramHandler, int receivePacketSize, Executor workerPool) throws IOException {
super(datagramHandler, receivePacketSize, workerPool);
channel = DatagramChannel.open();
channel.configureBlocking(false);
socket = channel.socket();
for (Entry<String, Object> entry : options.entrySet()) {
setOption(entry.getKey(), entry.getValue());
}
socket.bind(addr);
dispatcher.register(this);
logFine("enpoint has been bound to locale port " + getLocalPort() + " (server mode)");
}
private static IoSocketDispatcher createDispatcher() {
IoSocketDispatcher disp = new IoSocketDispatcher();
Thread t = new Thread(disp);
t.setName("DispatcherThread#" + disp.hashCode());
t.setDaemon(true);
t.start();
return disp;
}
protected final DatagramChannel getChannel() {
return channel;
}
/**
* {@inheritDoc}
*/
public final void close() {
if (isOpen()) {
try {
logFine("closing " + toCompactString());
channel.close();
} catch (IOException ioe) {
logFine("error occured by closing connection. Reason " + ioe.toString());
}
super.close();
}
}
/**
* {@inheritDoc}
*/
public final InetAddress getLocalAddress() {
return socket.getLocalAddress();
}
/**
* {@inheritDoc}
*/
public final int getLocalPort() {
return socket.getLocalPort();
}
/**
* {@inheritDoc}
*/
public final boolean isOpen() {
return channel.isOpen();
}
/**
* log a fine msg
*
* @param msg the log message
*/
private void logFine(String msg) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + "/:" + getLocalPort() + " " + getId() + "] " + msg);
}
}
/**
* {@inheritDoc}
*/
public void send(UserDatagram packet) throws IOException {
if (packet.getRemoteAddress() == null) {
throw new IOException("remote socket adress has to be set");
}
logFine("add datagram packet (" + packet + ") to write queue");
packet.prepareForSend();
sendQueue.add(packet);
logFine("update interest ops to write");
dispatcher.initiateWrite(this);
}
/**
* write the outgoing data to socket
*
*/
private void writePhysical() {
if (!sendQueue.isEmpty()) {
synchronized (sendQueue) {
for (UserDatagram packet : sendQueue) {
try {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + "/:" + getLocalPort() + " " + getId() + "] sending datagram " + packet.toString());
}
int dataToSend = packet.getSize();
int written = channel.send(packet.getData(), packet.getRemoteSocketAddress());
if (LOG.isLoggable(Level.FINE) && (dataToSend != written)) {
LOG.fine("Error occured by sending datagram. Size DataToSend=" + dataToSend + ", written=" + written);
}
} catch (IOException ioe) {
LOG.warning("could not write datagram to " + packet.getRemoteAddress() + " .Reason: " + DataConverter.toString(ioe));
}
}
sendQueue.clear();
}
}
}
/**
* a compact string of this endpoint
*/
public String toCompactString() {
return this.getClass().getSimpleName() + " " + socket.getLocalAddress().getCanonicalHostName() + ":" + getLocalPort();
}
final void onReadableEvent() {
if (isOpen()) {
try {
// perform non-blocking read operation
if (getReceiveSize() > 0) {
ByteBuffer readBuffer = memoryManager.acquireMemory(getReceiveSize());
readBuffer.order(byteOrder);
SocketAddress address = channel.receive(readBuffer);
// datagram is not immediately available
if (address == null) {
return;
// datagram is available
} else {
// nothing has been read
if (readBuffer.position() == 0) {
return;
}
readBuffer.flip();
onData(address, readBuffer);
}
}
} catch (IOException ioe) {
logFine("error occured while receiving. Reason: " + ioe.toString());
}
}
}
final void onWriteableEvent() throws IOException {
dispatcher.setSelectionKeyToReadImmediately(this);
writePhysical();
}
final void onDispatcherClose() {
close();
}
/**
* {@inheritDoc}
*/
protected AbstractChannelBasedEndpoint setOption(String name, Object value) throws IOException {
if (name.equals(IEndpoint.SO_SNDBUF)) {
socket.setSendBufferSize((Integer) value);
} else if (name.equals(IEndpoint.SO_REUSEADDR)) {
socket.setReuseAddress((Boolean) value);
} else if (name.equals(IEndpoint.SO_RCVBUF)) {
socket.setReceiveBufferSize((Integer) value);
} else if (name.equals(IEndpoint.IP_TOS)) {
socket.setTrafficClass((Integer) value);
} else {
LOG.warning("option " + name + " is not supproted for " + this.getClass().getName());
}
return this;
}
/**
* {@inheritDoc}
*/
public Object getOption(String name) throws IOException {
if (name.equals(IEndpoint.SO_SNDBUF)) {
return socket.getSendBufferSize();
} else if (name.equals(IEndpoint.SO_REUSEADDR)) {
return socket.getReuseAddress();
} else if (name.equals(IEndpoint.SO_RCVBUF)) {
return socket.getReceiveBufferSize();
} else if (name.equals(IEndpoint.IP_TOS)) {
return socket.getTrafficClass();
} else {
LOG.warning("option " + name + " is not supproted for " + this.getClass().getName());
return null;
}
}
@SuppressWarnings("unchecked")
public Map<String, Class> getOptions() {
return Collections.unmodifiableMap(SUPPORTED_OPTIONS);
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/AbstractChannelBasedEndpoint.java | Java | art | 8,765 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* non blocking Mutlicast endpoint <br><br>
*
* Caused by the missing channel support for multicast Datagram (JSE 6.0) this
* class is implemented by using the "classic" MulticastSocket
*
* @author grro@xsocket.org
*/
public final class MulticastEndpoint extends AbstractEndpoint {
/*
* * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4527345
*/
private static Logger LOG = Logger.getLogger(MulticastEndpoint.class.getName());
@SuppressWarnings("unchecked")
private static final Map<String ,Class> SUPPORTED_OPTIONS = new HashMap<String, Class>();
static {
SUPPORTED_OPTIONS.put(SO_RCVBUF, Integer.class);
SUPPORTED_OPTIONS.put(SO_SNDBUF, Integer.class);
SUPPORTED_OPTIONS.put(IP_TOS, Integer.class);
SUPPORTED_OPTIONS.put(SO_REUSEADDR, Boolean.class);
SUPPORTED_OPTIONS.put(SO_REUSEADDR, Boolean.class);
SUPPORTED_OPTIONS.put(IP_MULTICAST_TTL, Integer.class);
SUPPORTED_OPTIONS.put(IP_MULTICAST_LOOP, Boolean.class);
}
// run flag
private volatile boolean isRunning = true;
// socket
private final MulticastSocket socket;
private final InetSocketAddress multicastAddress;
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(InetAddress address, final int port) throws IOException {
this(address, port, new HashMap<String, Object>(), 0, null, getGlobalWorkerPool());
}
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @param receiveSize the size of the data packet to receive
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(String address, final int port, int receiveSize, IDatagramHandler datagramHandler) throws IOException {
this(InetAddress.getByName(address), port, new HashMap<String, Object>(), receiveSize, datagramHandler, getGlobalWorkerPool());
}
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @param receiveSize the size of the data packet to receive
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(InetAddress address, final int port, int receiveSize, IDatagramHandler datagramHandler) throws IOException {
this(address, port, new HashMap<String, Object>(), receiveSize, datagramHandler, getGlobalWorkerPool());
}
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @param receiveSize the size of the data packet to receive
* @param datagramHandler the datagram handler
* @param workerPool the workerPool
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(InetAddress address, final int port, int receiveSize, IDatagramHandler datagramHandler, Executor workerPool) throws IOException {
this(address, port, new HashMap<String, Object>(), receiveSize, datagramHandler, workerPool);
}
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @param options the socket options
* @param receiveSize the size of the data packet to receive
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(String address, int port, Map<String, Object> options, int receiveSize, IDatagramHandler datagramHandler) throws IOException {
this(InetAddress.getByName(address), port, options, receiveSize, datagramHandler, getGlobalWorkerPool());
}
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @param options the socket options
* @param receiveSize the size of the data packet to receive
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(InetAddress address, int port, Map<String, Object> options, int receiveSize, IDatagramHandler datagramHandler) throws IOException {
this(address, port, options, receiveSize, datagramHandler, getGlobalWorkerPool());
}
/**
* Constructs a datagram socket and
* connects it to the given address
*
* @param address the group address
* @param port the port
* @param options the socket options
* @param receiveSize the size of the data packet to receive
* @param datagramHandler the datagram handler
* @param workerPool the workerPool
* @throws IOException If some I/O error occurs
*/
public MulticastEndpoint(InetAddress address, int port, Map<String, Object> options, int receiveSize, IDatagramHandler datagramHandler, Executor workerPool) throws IOException {
super(datagramHandler, receiveSize, workerPool);
socket = new MulticastSocket(port);
for (Entry<String, Object> entry : options.entrySet()) {
setOption(entry.getKey(), entry.getValue());
}
socket.joinGroup(address);
multicastAddress = new InetSocketAddress(address, port);
if (datagramHandler != null) {
startReceiver();
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("upd multicast endpoint bound to " + address.getCanonicalHostName() + "/" + port);
}
}
private void startReceiver() {
Thread receiverThread = new Thread() {
public void run() {
while (isRunning) {
receiveData();
}
}
};
receiverThread.setDaemon(true);
receiverThread.setName("MulticastReceiver#" + hashCode());
receiverThread.start();
}
private void receiveData() {
try {
byte[] buf = new byte[getReceiveSize()];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
socket.receive(dp);
ByteBuffer data = ByteBuffer.wrap(dp.getData());
data.limit(dp.getLength()); // handles if received byte size is smaller than predefined receive size
onData(new InetSocketAddress(dp.getAddress(), dp.getPort()), data);
} catch(IOException e) {
if (!socket.isClosed() && (LOG.isLoggable(Level.FINE))) {
LOG.fine("error occured by receiving data. Reason: " + e.toString());
}
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return multicastAddress.toString() + " (ID=" + getId() + ")";
}
/**
* {@inheritDoc}
*/
public void close() {
if (isRunning) {
isRunning = false;
try {
socket.leaveGroup(multicastAddress.getAddress());
socket.close();
} catch (Exception e) {
// eat and log exception
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by closing multicast socket. Reason: " + e.toString());
}
}
super.close();
}
}
/**
* {@inheritDoc}
*/
public InetAddress getLocalAddress() {
return multicastAddress.getAddress();
}
/**
* {@inheritDoc}
*/
public int getLocalPort() {
return multicastAddress.getPort();
}
/**
* {@inheritDoc}
*/
public boolean isOpen() {
return !socket.isClosed();
}
/**
* {@inheritDoc}
*/
public void send(UserDatagram packet) throws ClosedChannelException, IOException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("[" + "/:" + getLocalPort() + " " + getId() + "] sending datagram " + packet.toString());
}
packet.prepareForSend();
byte[] bytes = new byte[packet.getData().remaining()];
packet.getData().get(bytes);
DatagramPacket dataPacket = new DatagramPacket(bytes, bytes.length, multicastAddress);
socket.send(dataPacket);
}
/**
* {@inheritDoc}
*/
protected MulticastEndpoint setOption(String name, Object value) throws IOException {
if (name.equals(IEndpoint.SO_SNDBUF)) {
socket.setSendBufferSize((Integer) value);
} else if (name.equals(IEndpoint.SO_REUSEADDR)) {
socket.setReuseAddress((Boolean) value);
} else if (name.equals(IEndpoint.SO_RCVBUF)) {
socket.setReceiveBufferSize((Integer) value);
} else if (name.equals(IEndpoint.IP_TOS)) {
socket.setTrafficClass((Integer) value);
} else if (name.equals(IEndpoint.IP_MULTICAST_TTL)) {
socket.setTimeToLive((Integer) value);
} else if (name.equals(IEndpoint.IP_MULTICAST_LOOP)) {
socket.setLoopbackMode((Boolean) value);
} else {
LOG.warning("option " + name + " is not supproted for " + this.getClass().getName());
}
return this;
}
/**
* {@inheritDoc}
*/
public Object getOption(String name) throws IOException {
if (name.equals(IEndpoint.SO_SNDBUF)) {
return socket.getSendBufferSize();
} else if (name.equals(IEndpoint.SO_REUSEADDR)) {
return socket.getReuseAddress();
} else if (name.equals(IEndpoint.SO_RCVBUF)) {
return socket.getReceiveBufferSize();
} else if (name.equals(IEndpoint.IP_TOS)) {
return socket.getTrafficClass();
} else if (name.equals(IEndpoint.IP_MULTICAST_TTL)) {
return socket.getTimeToLive();
} else if (name.equals(IEndpoint.IP_MULTICAST_LOOP)) {
return socket.getLoopbackMode();
} else {
LOG.warning("option " + name + " is not supproted for " + this.getClass().getName());
return null;
}
}
@SuppressWarnings("unchecked")
public Map<String, Class> getOptions() {
return Collections.unmodifiableMap(SUPPORTED_OPTIONS);
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/MulticastEndpoint.java | Java | art | 11,917 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* a Memory Manager implementation
*
* @author grro@xsocket.org
*/
class MemoryManager {
private static final Logger LOG = Logger.getLogger(MemoryManager.class.getName());
private List<SoftReference<ByteBuffer>> memoryBuffer = new ArrayList<SoftReference<ByteBuffer>>();
private boolean useDirectMemory = false;
private int preallocationSize = 4096;
/**
* constructor
*
* @param preallocationSize the preallocation size
* @param useDirectMemory true, if direct memory should be used
*/
MemoryManager(int preallocationSize, boolean useDirectMemory) {
this.preallocationSize = preallocationSize;
this.useDirectMemory = useDirectMemory;
}
/**
* return the free memory size
*
* @return the free memory size
*/
public final synchronized int getFreeBufferSize() {
int size = 0;
for (SoftReference<ByteBuffer> bufferRef: memoryBuffer) {
ByteBuffer buffer = bufferRef.get();
if (buffer != null) {
size += buffer.remaining();
}
}
return size;
}
private void recycleMemory(ByteBuffer buffer) {
if (buffer.hasRemaining()) {
memoryBuffer.add(new SoftReference<ByteBuffer>(buffer.slice()));
}
}
/**
* aquires free memory
*
* @param minSize the min size of the aquired memory
*/
public final synchronized ByteBuffer acquireMemory(int size) {
ByteBuffer buffer = null;
if (!memoryBuffer.isEmpty()) {
SoftReference<ByteBuffer> freeBuffer = memoryBuffer.remove(0);
buffer = freeBuffer.get();
// size sufficient?
if ((buffer != null) && (buffer.limit() < size)) {
buffer = null;
}
}
if (buffer == null) {
int allocationSize = getPreallocationSize();
if (getPreallocationSize() < allocationSize) {
allocationSize = size * 4;
}
buffer = newBuffer(size);
}
int savedLimit = buffer.limit();
buffer.limit(size);
ByteBuffer result = buffer.slice();
buffer.position(size);
buffer.limit(savedLimit);
ByteBuffer remaining = buffer.slice();
recycleMemory(remaining);
return result;
}
/**
* return the preallocation size
*
* @return the preallocation size
*/
int getPreallocationSize() {
return preallocationSize;
}
private final ByteBuffer newBuffer(int size) {
if (useDirectMemory) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("allocating " + DataConverter.toFormatedBytesSize(size) + " direct memory");
}
return ByteBuffer.allocateDirect(size);
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("allocating " + DataConverter.toFormatedBytesSize(size) + " heap memory");
}
return ByteBuffer.allocate(size);
}
}
} | zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/MemoryManager.java | Java | art | 4,061 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.DataConverter;
/**
* Endpoint implementation base
*
* @author grro@xsocket.org
*/
abstract class AbstractEndpoint implements IEndpoint {
private static final Logger LOG = Logger.getLogger(AbstractEndpoint.class.getName());
private static Executor GLOBAL_WORKERPOOL = Executors.newCachedThreadPool();
private static String idPrefix;
// ids
private static long nextId = 0;
private final String id;
// encoding
private String defaultEncoding = "UTF-8";
// receive data handling
private final Object readGuard = new Object();
private final ReceiveQueue receiveQueue = new ReceiveQueue();
private int receiveSize = -1;
// datagram handler
private final IDatagramHandler datagramHandler;
// worker pool
private Executor workerPool;
// statistics & jmx
private long openTime = -1;
private long lastTimeReceived = System.currentTimeMillis();
private long receivedBytes = 0;
static {
String base = null;
try {
base = InetAddress.getLocalHost().getCanonicalHostName();
} catch (Exception e) {
base = "locale";
}
int random = 0;
Random rand = new Random();
do {
random = rand.nextInt();
} while (random < 0);
idPrefix = Integer.toHexString(base.hashCode()) + "." + Long.toHexString(System.currentTimeMillis()) + "." + Integer.toHexString(random);
}
/**
* constructor
*
* @param useGlobalWorkerpool true, ifglobal worker pool should be used
* @param datagramHandler the datagram handler
* @param receiveSize the receive packet size
* @param workerPool the workerpool to use
*/
AbstractEndpoint(IDatagramHandler datagramHandler, int receiveSize, Executor workerPool) {
this.datagramHandler = datagramHandler;
this.receiveSize = receiveSize;
this.workerPool = workerPool;
id = idPrefix + "." + (++nextId);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
close();
}
});
openTime = System.currentTimeMillis();
}
protected static Executor getGlobalWorkerPool() {
return GLOBAL_WORKERPOOL;
}
public void close() {
}
/**
* return the worker pool
*
* @return the worker pool
*/
public Executor getWorkerpool() {
return workerPool;
}
/**
* {@inheritDoc}
*/
public final void setReceiveSize(int receivePacketSize) {
this.receiveSize = receivePacketSize;
}
/**
* {@inheritDoc}
*/
public final int getReceiveSize() {
return receiveSize;
}
protected final void onData(SocketAddress address, ByteBuffer data) {
UserDatagram packet = new UserDatagram(address, data, getDefaultEncoding());
receiveQueue.offer(packet);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + "/:" + getLocalPort() + " " + getId() + "] datagram received: " + packet.toString());
}
lastTimeReceived = System.currentTimeMillis();
receivedBytes += data.remaining();
if (datagramHandler != null) {
workerPool.execute(new HandlerProcessor());
}
}
/**
* {@inheritDoc}
*/
public final UserDatagram receive(long timeoutMillis) throws IOException, SocketTimeoutException {
UserDatagram datagram = null;
if (getReceiveSize() <= 0) {
throw new IOException("the receive packet size has not been set");
}
// no timeout set
if (timeoutMillis <= 0) {
datagram = receive();
// timeout set
} else {
long start = System.currentTimeMillis();
synchronized (readGuard) {
do {
datagram = receive();
if (datagram != null) {
break;
} else {
try {
readGuard.wait(timeoutMillis / 10);
} catch (InterruptedException ie) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
} while (System.currentTimeMillis() < (start + timeoutMillis));
}
}
if (datagram == null) {
throw new SocketTimeoutException("timeout " + DataConverter.toFormatedDuration(timeoutMillis) + " reached");
} else {
return datagram;
}
}
public UserDatagram receive() {
return receiveQueue.poll();
}
/**
* {@inheritDoc}
*/
public final String getDefaultEncoding() {
return defaultEncoding;
}
/**
* {@inheritDoc}
*/
public final void setDefaultEncoding(String defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
/**
* return the id
*
* @return the id
*/
public final String getId() {
return id;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return " received=" + DataConverter.toFormatedBytesSize(receivedBytes)
+ ", age=" + DataConverter.toFormatedDuration(System.currentTimeMillis() - openTime)
+ ", lastReceived=" + DataConverter.toFormatedDate(lastTimeReceived)
+ " [" + id + "]";
}
private static final class ReceiveQueue {
private List<UserDatagram> receiveQueue = new ArrayList<UserDatagram>();
private int modifyVersion = 0;
public synchronized void offer(UserDatagram userDatagram) {
modifyVersion++;
receiveQueue.add(userDatagram);
}
public synchronized UserDatagram poll() {
if (receiveQueue.isEmpty()) {
return null;
} else {
modifyVersion++;
return receiveQueue.remove(0);
}
}
public synchronized boolean isEmpty() {
modifyVersion++;
return receiveQueue.isEmpty();
}
@Override
public String toString() {
return receiveQueue.size() + " (modifyVersion=" + modifyVersion + ")";
}
}
private final class HandlerProcessor implements Runnable {
public void run() {
try {
if (!receiveQueue.isEmpty()) {
datagramHandler.onDatagram(AbstractEndpoint.this);
}
} catch (Exception e) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by performing onData task. Reason: " + e.toString());
}
throw new RuntimeException(e);
}
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/AbstractEndpoint.java | Java | art | 7,780 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* connected endpoint implementation
*
* @author grro@xsocket.org
*/
public final class ConnectedEndpoint extends AbstractChannelBasedEndpoint implements IConnectedEndpoint {
private static final Logger LOG = Logger.getLogger(ConnectedEndpoint.class.getName());
private final SocketAddress remoteAddress;
/**
* Constructs a <i>client/server</i> datagram socket and binds it to any
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @param host the remote host
* @param port the remote port
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(String host, int port) throws IOException {
this(new InetSocketAddress(host, port));
}
/**
* Constructs a <i>client/server</i> datagram socket and binds it to any
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(SocketAddress remoteAddress) throws IOException {
this(remoteAddress, -1);
}
/**
* Constructs a <i>client/server</i> datagram socket and binds it to the given
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @param remoteAddress the remote socket address
* @param receivePacketSize the receive packet size
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(SocketAddress remoteAddress, int receivePacketSize) throws IOException {
this(remoteAddress, receivePacketSize, null);
}
/**
* Constructs a <i>client/server</i> datagram socket and binds it to the given
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @param host the remote host
* @param port the remote port
* @param receivePacketSize the receive packet size
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(String host, int port, int receivePacketSize) throws IOException {
this(new InetSocketAddress(host, port), new HashMap<String, Object>(), receivePacketSize, null, getGlobalWorkerPool());
}
/**
* Constructs a <i>client/server</i> datagram socket and binds it to the given
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @param remoteAddress the remote socket address
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(SocketAddress remoteAddress, int receivePacketSize, IDatagramHandler datagramHandler) throws IOException {
this(remoteAddress, new HashMap<String, Object>(), receivePacketSize, datagramHandler, getGlobalWorkerPool());
}
/**
* Constructs a <i>client/server</i> datagram socket and binds it to the given
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @param remoteAddress the remote socket address
* @param socketOptions the socket options
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(SocketAddress remoteAddress, Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler) throws IOException {
this(remoteAddress, options, receivePacketSize, datagramHandler, getGlobalWorkerPool());
}
/**
* Constructs a <i>client/server</i> datagram socket and binds it to the given
* available port on the local host machine. The socket
* will be bound to the wildcard address, an IP address
* chosen by the kernel. The local socket will be connected
* to the server by using the passed over addresses
*
* @param remoteAddress the remote socket address
* @param socketOptions the socket options
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @param workerPool the worker pool
* @throws IOException If some I/O error occurs
*/
public ConnectedEndpoint(SocketAddress remoteAddress, Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler, Executor workerPool) throws IOException {
super(new InetSocketAddress(0), options, datagramHandler, receivePacketSize, workerPool);
this.remoteAddress = remoteAddress;
getChannel().connect(remoteAddress);
}
@Override
public void send(UserDatagram packet) throws IOException {
if (LOG.isLoggable(Level.FINER) && (packet.getRemoteSocketAddress() != null)) {
LOG.fine("remote address of given packet is already set with "
+ packet.getRemoteSocketAddress() + ". this value will be overriden by "
+ remoteAddress);
}
packet.setRemoteAddress(remoteAddress);
super.send(packet);
}
/**
* {@inheritDoc}
*/
public SocketAddress getRemoteSocketAddress() {
return remoteAddress;
}
/**
* {@inheritDoc}
*/
protected ConnectedEndpoint setOption(String name, Object value) throws IOException {
return (ConnectedEndpoint) super.setOption(name, value);
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/ConnectedEndpoint.java | Java | art | 7,658 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
/**
* Endpoint implementation
*
* @author grro@xsocket.org
*/
public final class Endpoint extends AbstractChannelBasedEndpoint {
/**
* Constructs a datagram socket and binds it to any
* available port on the local host machine.
*
* @throws IOException If some I/O error occurs
*/
public Endpoint() throws IOException {
this(0);
}
/**
* Constructs a datagram socket and binds it to any
* available port on the local host machine.
*
* @param receivePacketSize the receive packet size
* @throws IOException If some I/O error occurs
*/
public Endpoint(int receivePacketSize) throws IOException {
this(receivePacketSize, null);
}
/**
* Constructs a datagram socket and binds it to any
* available port on the local host machine.
*
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public Endpoint(int receivePacketSize, IDatagramHandler datagramHandler) throws IOException {
this(new HashMap<String, Object>(), receivePacketSize, datagramHandler, getGlobalWorkerPool(), new InetSocketAddress(0));
}
/**
* Constructs a datagram socket and binds it to any
* available port on the local host machine.
*
* @param options the socket options
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @throws IOException If some I/O error occurs
*/
public Endpoint(Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler) throws IOException {
this(options, receivePacketSize, datagramHandler, getGlobalWorkerPool(), new InetSocketAddress(0));
}
/**
* Constructs a datagram socket and binds it to any
* available port on the local host machine.
*
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @param workerPool the workerPool
* @throws IOException If some I/O error occurs
*/
public Endpoint(int receivePacketSize, IDatagramHandler datagramHandler, Executor workerPool) throws IOException {
this(new HashMap<String, Object>(), receivePacketSize, datagramHandler, workerPool, new InetSocketAddress(0));
}
/**
* Constructs a datagram socket and binds it to the given
* port on the local host machine.
*
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @param address the local address
* @param port the local port which must be between 0 and 65535 inclusive.
* @throws IOException If some I/O error occurs
*/
public Endpoint(int receivePacketSize, IDatagramHandler datagramHandler, InetAddress address, int port) throws IOException {
this(new HashMap<String, Object>(), receivePacketSize, datagramHandler, getGlobalWorkerPool(), address, port);
}
/**
* Constructs a datagram socket and binds it to the given
* port on the local host machine.
*
* @param options the socket options
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @param address the local address
* @param port the local port which must be between 0 and 65535 inclusive.
* @param workerPool the workerPool
* @throws IOException If some I/O error occurs
*/
public Endpoint(Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler, Executor workerPool, InetAddress address, int port) throws IOException {
super(new InetSocketAddress(address, port), options, datagramHandler, receivePacketSize, workerPool);
}
/**
* Constructs a datagram socket and binds it to the given
* port on the local host machine.
*
*
* @param options the socket options
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @param address the local address
* @param port the local port which must be between 0 and 65535 inclusive.
* @throws IOException If some I/O error occurs
*/
public Endpoint(Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler, InetAddress address, int port) throws IOException {
super(new InetSocketAddress(address, port), options, datagramHandler, receivePacketSize, getGlobalWorkerPool());
}
/**
* Constructs a datagram socket and binds it to the given
* port on the local host machine.
*
* @param receivePacketSize the receive packet size
* @param datagramHandler the datagram handler
* @param address the local address
* @param port the local port which must be between 0 and 65535 inclusive.
* @param workerPool the workerPool
* @throws IOException If some I/O error occurs
*/
public Endpoint(int receivePacketSize, IDatagramHandler datagramHandler, Executor workerPool, InetAddress address, int port) throws IOException {
super(new InetSocketAddress(address, port), new HashMap<String, Object>(), datagramHandler, receivePacketSize, workerPool);
}
private Endpoint(Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler, Executor workerPool, InetSocketAddress addr) throws IOException {
super(addr, options, datagramHandler, receivePacketSize, workerPool);
}
/**
* {@inheritDoc}
*/
protected Endpoint setOption(String name, Object value) throws IOException {
return (Endpoint) super.setOption(name, value);
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/Endpoint.java | Java | art | 7,251 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.datagram;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.Map;
/**
* An endpoint, which can be used to send and receive {@link UserDatagram}. E.g.
*
* <pre>
*
* // without datagram handler
* ...
* IEndpoint endpoint = new Endpoint(packageSize);
*
* UserDatagram request = new UserDatagram(remoteHostname, remotePort, packageSize);
* request.write("Hello peer, how are you?");
*
* endpoint.send(request);
* UserDatagram response = endpoint.receive(1000); // receive (timeout 1 sec)
*
* endpoint.close();
* ...
*
*
* // by using a handler
* ...
* MyHandler hdl = new MyHandler();
* IEndpoint endpoint = new Endpoint(packageSize, hdl);
*
* UserDatagram request = new UserDatagram(remoteHostname, remotePort, packageSize);
* request.write("Hello peer, how are you?");
*
* endpoint.send(request);
* // response will be handled by MyHandler
*
* // wait
* ...
* endpoint.close();
*
*
* class MyHandler implements IDatagramHandler {
*
* public boolean onDatagram(IEndpoint localEndpoint) throws IOException {
* UserDatagram datagram = localEndpoint.receive(); // get the datagram
* ...
* return true;
* }
* }
* </pre>
*
* @author grro@xsocket.org
*/
public interface IEndpoint extends Closeable {
public static final String SO_SNDBUF = "SOL_SOCKET.SO_SNDBUF";
public static final String SO_RCVBUF = "SOL_SOCKET.SO_RCVBUF";
public static final String SO_REUSEADDR = "SOL_SOCKET.SO_REUSEADDR";
public static final String SO_BROADCAST = "SOL_SOCKET.SO_BROADCAST";
public static final String IP_TOS = "IPPROTO_IP.IP_TOS";
public static final String IP_MULTICAST_TTL = "IPPROTO_IP.IP_MULTICAST_TTL";
public static final String IP_MULTICAST_LOOP = "IPPROTO_IP.IP_MULTICAST_LOOP";
/**
* returns, if the endpoint is open
*
*
* @return true if the endpoint is open
*/
boolean isOpen();
/**
* returns the address of the endpoint
*
* @return the address
*/
InetAddress getLocalAddress();
/**
* returns the port of the endpoint
*
* @return the port
*/
int getLocalPort();
/**
* sets the default encoding used by this endpoint
*
* @param encoding the default encoding
*/
void setDefaultEncoding(String encoding);
/**
* gets the default encoding used by this endpoint
*
* @return the default encoding
*/
String getDefaultEncoding();
/**
* send a datagram to the remote endpoint
*
* @param datagram the datagram to send
* @throws IOException If some other I/O error occurs
* @throws ClosedException if the underlying channel is closed
*/
void send(UserDatagram datagram) throws IOException;
/**
* set the size of the datagram that will be received
*
* @param receiveSize the receive size
*/
void setReceiveSize(int receiveSize);
/**
* get the size of the datagram that will be received
* @return the receive size
*/
int getReceiveSize();
/**
* receive a datagram packet (receive timeout = 0)
*
* @return the received datagram packet or null if no datagram is available
* @throws IOException If some other I/O error occurs
*/
UserDatagram receive() throws IOException;
/**
* receive a datagram packet
*
* @param timeoutMillis the receive timeout in millis
* @return the received datagram packet
* @throws SocketTimeoutException If the receive timeout has been reached
* @throws IOException If some other I/O error occurs
*/
UserDatagram receive(long timeoutMillis) throws IOException, SocketTimeoutException;
/**
* return the endpoint id
* @return the endpoint id
*/
String getId();
/**
* returns the vlaue of a option
*
* @param name the name of the option
* @return the value of the option
* @throws IOException In an I/O error occurs
*/
Object getOption(String name) throws IOException;
/**
* Returns an unmodifiable map of the options supported by this endpont.
*
* The key in the returned map is the name of a option, and its value
* is the type of the option value. The returned map will never contain null keys or values.
*
* @return An unmodifiable map of the options supported by this channel
*/
@SuppressWarnings("unchecked")
Map<String,Class> getOptions();
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/datagram/IEndpoint.java | Java | art | 5,570 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Serialized Task Queue
*
* <br/><br/><b>This is a xSocket internal class and subject to change</b>
*
* @author grro@xsocket.org
*/
public final class SerializedTaskQueue {
private static final Logger LOG = Logger.getLogger(SerializedTaskQueue.class.getName());
private final LinkedList<Runnable> multithreadedTaskQueue = new LinkedList<Runnable>();
private final ReentrantLock processLock = new ReentrantLock(false);
private final MultithreadedTaskProcessor multithreadedTaskProcessor = new MultithreadedTaskProcessor();
/**
* process a task non threaded synchronized by the internal task queue. If the
* task queue is empty the task will be processed by the current thread. If a task running
* or the task queue size is not empty, the task will be executed by a dedicated thread.
*
* @param task the task to process
* @param workerpool the workerpool
*/
public void performNonThreaded(Runnable task, Executor workerpool) {
// got lock -> process nonthreaded
if (processLock.tryLock()) {
try {
// are there pending tasks -> run task multithreaded
synchronized (multithreadedTaskQueue) {
if (!multithreadedTaskQueue.isEmpty()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("multithreaded tasks are in queue . register non threaded task " + task.toString() + " to multithreaded queue (non threaded task will be performed multithreaded)");
}
performMultiThreaded(task, workerpool);
return;
}
}
task.run();
} finally {
processLock.unlock();
}
// task are running -> perform task multithreaded
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("a task is already running. register non threaded task " + task.toString() + " to perform it multithreaded");
}
performMultiThreaded(task, workerpool);
}
}
/**
* process a task multi threaded synchronized by the internal task queue. The task will
* be processed by a dedicated thread. The given worker pool <i>can</i> be used to perform this
* tasks (as well as other task of the queue).
*
* @param task the task to process
* @param workerpool the workerpool
*/
public void performMultiThreaded(Runnable task, Executor workerpool) {
// add task to queue
synchronized (multithreadedTaskQueue) {
// (Multithreaded) worker is not running
if (multithreadedTaskQueue.isEmpty()) {
multithreadedTaskQueue.addLast(task);
try {
workerpool.execute(multithreadedTaskProcessor);
} catch (RejectedExecutionException ree) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("task has been rejected by worker pool " + workerpool + " (worker pool cosed?) performing task by starting a new thread");
}
Thread t = new Thread(multithreadedTaskProcessor, "SerializedTaskQueueFallbackThread");
t.setDaemon(true);
t.start();
}
} else {
multithreadedTaskQueue.addLast(task);
}
}
}
private void performPendingTasks() {
// lock process
processLock.lock();
try {
// handle all pending tasks
while (true) {
// get task from queue
Runnable task = null;
synchronized (multithreadedTaskQueue) {
if (!multithreadedTaskQueue.isEmpty()) {
task = multithreadedTaskQueue.get(0);
}
}
// perform it
if (task != null) {
try {
task.run();
} catch (Throwable t) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("error occured by processing " + task + " " + t.toString());
}
}
}
// is queue empty?
synchronized (multithreadedTaskQueue) {
multithreadedTaskQueue.remove(task);
if (multithreadedTaskQueue.isEmpty()) {
return;
}
}
}
} finally {
processLock.unlock();
}
}
private final class MultithreadedTaskProcessor implements Runnable {
public void run() {
performPendingTasks();
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/SerializedTaskQueue.java | Java | art | 5,435 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.IOException;
/**
* Checked exception thrown when a write operation reaches the predefined limit
*
* @author grro
*/
public class MaxWriteSizeExceededException extends IOException {
private static final long serialVersionUID = 4459338235510678984L;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/MaxWriteSizeExceededException.java | Java | art | 1,315 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.IOException;
/**
* Checked exception thrown when a read operation reaches the predefined limit,
* without getting the required data
*
* @author grro
*/
public class MaxReadSizeExceededException extends IOException {
private static final long serialVersionUID = -1906216307105182850L;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/MaxReadSizeExceededException.java | Java | art | 1,355 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.IOException;
/**
* The LifeCycle defines call back methods, which notifies life cycle events <br><br>
*
* @author grro@xsocket.org
*/
public interface ILifeCycle {
/**
* notifies that the entity has been loaded
* and initialized
*
*/
void onInit();
/**
* notifies that the entity will be destroyed
*
* @throws IOException if an exception occurs. The exception will be (logged and) swallowed
*/
void onDestroy() throws IOException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/ILifeCycle.java | Java | art | 1,535 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* WorkerPool implementation
*
* @author grro@xsocket.org
*/
public final class WorkerPool extends ThreadPoolExecutor {
private static final Logger LOG = Logger.getLogger(WorkerPool.class.getName());
/**
* constructor
*
* @param maxSize max worker size
*/
public WorkerPool(int maxSize) {
this(0, maxSize, 60, TimeUnit.SECONDS, false);
}
/**
* constructor
*
* @param minSize min worker size
* @param maxSize max worker size
*/
public WorkerPool(int minSize, int maxSize) {
this(minSize, maxSize, 60, TimeUnit.SECONDS, false);
}
/**
* constructor
*
* @param minSize min worker size
* @param maxSize max worker size
* @param taskqueuesize the task queue size
*/
public WorkerPool(int minSize, int maxSize, int taskqueuesize) {
this(minSize, maxSize, 60, TimeUnit.SECONDS, taskqueuesize, false);
}
/**
* constructor
*
* @param minSize min worker size
* @param maxSize max worker size
* @param keepalive the keepalive
* @param timeunit the timeunit
* @param isDaemon true, if worker threads are daemon threads
*/
public WorkerPool(int minSize, int maxSize, long keepalive, TimeUnit timeunit, boolean isDaemon) {
this(minSize, maxSize, keepalive, timeunit, Integer.MAX_VALUE, isDaemon);
}
/**
* constructor
*
* @param minSize min worker size
* @param maxSize max worker size
* @param keepalive the keepalive
* @param timeunit the timeunit
* @param taskqueuesize the task queue size
* @param isDaemon true, if worker threads are daemon threads
*/
public WorkerPool(int minSize, int maxSize, long keepalive, TimeUnit timeunit, int taskqueuesize, boolean isDaemon) {
super(minSize, maxSize, keepalive, timeunit, new WorkerPoolAwareQueue(taskqueuesize), new DefaultThreadFactory(isDaemon));
((WorkerPoolAwareQueue) getQueue()).init(this);
}
@SuppressWarnings("serial")
private static final class WorkerPoolAwareQueue extends LinkedBlockingQueue<Runnable> {
private WorkerPool workerPool;
public WorkerPoolAwareQueue(int capacity) {
super(capacity);
}
public void init(WorkerPool workerPool) {
this.workerPool = workerPool;
}
public boolean offer(Runnable task) {
// active count smaller than pool size?
if (workerPool.getActiveCount() < workerPool.getPoolSize()) {
// add the task to the queue. The task should be handled immediately
// because free worker threads should be available (all threads of
// the workerpool listens the queue for new tasks)
return super.offer(task);
}
// max size reached?
if (workerPool.getPoolSize() >= workerPool.getMaximumPoolSize()) {
// add the task to the end of the queue. The task have to wait
// until one of the threads becomes free to handle the task
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("add task to queue waiting for the next free one");
}
return super.offer(task);
// ... no
} else {
// return false, which forces starting a new thread. The new
// thread performs the task and will be added to workerpool
// after performing the task
// As result the workerpool is increased. If the thread reach
// its keepalive timeout (waiting for new tasks), the thread
// will terminate itself
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("initiate creating a new thread");
}
return false;
}
}
}
private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private final boolean isDaemon;
DefaultThreadFactory(boolean isDaemon) {
this.isDaemon = isDaemon;
namePrefix = "xWorkerPool-" + poolNumber.getAndIncrement() + "-thread-";
}
public Thread newThread(Runnable r) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("creating new thread");
}
Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
t.setDaemon(isDaemon);
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/WorkerPool.java | Java | art | 6,608 |
/*
* Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
/**
* A data sink is an I/O resource capable of receiving data.
*
* @author grro@xsocket.org
*/
public interface IDataSink {
/**
* writes a byte to the data sink
*
* @param b the byte to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(byte b) throws IOException, BufferOverflowException;
/**
* writes bytes to the data sink
*
* @param bytes the bytes to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(byte... bytes) throws IOException, BufferOverflowException;
/**
* writes bytes to the data sink
*
* @param bytes the bytes to write
* @param offset The offset of the sub array to be used; must be non-negative and no larger than array.length. The new buffer`s position will be set to this value.
* @param length The length of the sub array to be used; must be non-negative and no larger than array.length - offset. The new buffer`s limit will be set to offset + length.
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(byte[] bytes, int offset, int length) throws IOException, BufferOverflowException;
/**
* see {@link WritableByteChannel#write(ByteBuffer)}
*/
int write(ByteBuffer buffer) throws IOException, BufferOverflowException;
/**
* see {@link GatheringByteChannel#write(ByteBuffer[])}
*/
long write(ByteBuffer[] buffers) throws IOException, BufferOverflowException;
/**
* see {@link GatheringByteChannel#write(ByteBuffer[], int, int)}
*/
long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
/**
* writes a list of bytes to the data sink
*
* @param buffers the bytes to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
long write(List<ByteBuffer> buffers) throws IOException, BufferOverflowException;
/**
* writes a int to the data sink
*
* @param i the int value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(int i) throws IOException, BufferOverflowException;
/**
* writes a short to the data sink
*
* @param s the short value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(short s) throws IOException, BufferOverflowException;
/**
* writes a long to the data sink
*
* @param l the int value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(long l) throws IOException, BufferOverflowException;
/**
* writes a double to the data sink
*
* @param d the int value to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(double d) throws IOException, BufferOverflowException;
/**
* writes a message
*
* @param message the message to write
* @return the number of written bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
int write(String message) throws IOException, BufferOverflowException;
/**
* transfer the data of the source file channel to this data sink
*
* @param source the source channel
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
long transferFrom(FileChannel source) throws IOException, BufferOverflowException;
/**
* transfer the data of the source channel to this data sink by using the default chunk size
*
* @param source the source channel
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
long transferFrom(ReadableByteChannel source) throws IOException, BufferOverflowException;
/**
* transfer the data of the source channel to this data sink
*
* @param source the source channel
* @param chunkSize the chunk size to use
* @return the number of transfered bytes
* @throws BufferOverflowException If the no enough space is available
* @throws IOException If some other I/O error occurs
*/
long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException, BufferOverflowException;
}
| zzh-simple-hr | Zxsocket/src/org/xsocket/IDataSink.java | Java | art | 6,662 |
/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
/**
*
* @author grro@xsocket.org
*/
public final class SSLTestContextFactory {
public static final String PASSWORD = "secret";
private SSLTestContextFactory() {
}
public static String getTestKeyStoreFilename() {
String filename = null;
URL keystoreUrl = SSLTestContextFactory.class.getResource("keystore.jks");
if ((keystoreUrl != null) && (new File(keystoreUrl.getFile()).exists())) {
filename = keystoreUrl.getFile();
} else {
filename = new File("src" + File.separator + "test" + File.separator
+ "resources" + File.separator + "org" + File.separator
+ "xsocket" + File.separator + "keystore.jks").getAbsolutePath();
}
return filename;
}
public static SSLContext getSSLContext() {
try {
String filename = getTestKeyStoreFilename();
char[] passphrase = PASSWORD.toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(filename), passphrase);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext;
} catch (Exception e) {
return null;
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/SSLTestContextFactory.java | Java | art | 2,698 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.QAUtil;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;
import org.xsocket.connection.ConnectionUtils;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
public final class EchoServer implements Closeable {
private IServer server = null;
EchoServer(int listenPort) throws Exception {
IHandler hdl = new EchoHandler();
////////////////////////
// uncomment following code for using the first visit throttling filter
// FirstVisitThrottlingFilter firstVisitFilter = new FirstVisitThrottlingFilter(5);
// HandlerChain chain = new HandlerChain();
// chain.addLast(firstVisitFilter);
// chain.addLast(hdl);
// hdl = chain;
server = new Server(listenPort, hdl);
server.setFlushMode(FlushMode.ASYNC); // performance improvement
ConnectionUtils.start(server);
ConnectionUtils.registerMBean(server);
}
public static void main(String... args) throws Exception {
if (args.length != 1) {
System.out.println("usage org.xsocket.stream.EchoServer <listenport>");
System.exit(-1);
}
System.setProperty("org.xsocket.connection.server.workerpoolSize", "10");
new EchoServer(Integer.parseInt(args[0]));
}
public InetAddress getLocalAddress() {
return server.getLocalAddress();
}
public void close() throws IOException {
if (server != null) {
server.close();
}
}
@Execution(Execution.NONTHREADED) // performance improvement, but don't set to 'single threaded' mode if long running (I/O, network) operations will be performed within onData
private static final class EchoHandler implements IDataHandler {
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
ByteBuffer[] data = connection.readByteBufferByLength(connection.available());
connection.write(data);
return true;
}
}
private static final class FirstVisitThrottlingFilter implements IConnectHandler {
private final Set<String> knownIps = new HashSet<String>();
private int writeRate = 0;
FirstVisitThrottlingFilter(int writeRate) {
this.writeRate = writeRate;
}
public boolean onConnect(INonBlockingConnection connection) throws IOException {
String ipAddress = connection.getRemoteAddress().getHostAddress();
if (!knownIps.contains(ipAddress)) {
knownIps.add(ipAddress);
connection.setFlushmode(FlushMode.ASYNC);
connection.setWriteTransferRate(writeRate);
}
return false; // false -> successor element in handler chain will be called (true -> chain processing will be terminated)
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/EchoServer.java | Java | art | 4,287 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.nio.ByteBuffer;
import org.xsocket.QAUtil;
/**
*
* @author grro@xsocket.org
*/
public final class DeleteMe {
public static void main(String[] args) throws Exception {
Stream stream = new Stream();
ByteBuffer buffer1 = QAUtil.generateByteBuffer(1000);
ByteBuffer buffer2 = QAUtil.generateByteBuffer(1000);
ByteBuffer[] buffers = new ByteBuffer[2];
buffers[0] = buffer1;
buffers[1] = buffer2;
while (true) {
stream.append(buffers, 2000);
int available = stream.available();
stream.readByteBufferByLength(available);
}
}
private static final class Stream extends AbstractNonBlockingStream {
@Override
protected boolean isDataWriteable() {
return true;
}
@Override
protected boolean isMoreInputDataExpected() {
return true;
}
public boolean isOpen() {
return true;
}
public void append(ByteBuffer[] buffers, int size) {
super.appendDataToReadBuffer(buffers, size);
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/DeleteMe.java | Java | art | 2,081 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.NonBlockingConnection;
/**
*
* @author grro@xsocket.org
*/
public final class NonBlockingClient {
public static void main(String... args) throws Exception {
if (args.length != 3) {
System.out.println("usage org.xsocket.stream.NonBlockingClient <host> <port> <path>");
System.exit(-1);
}
new NonBlockingClient().call(args[0], Integer.parseInt(args[1]), args[2]);
}
public void call(String host, int port, String path) throws IOException {
INonBlockingConnection connection = null;
try {
connection = new NonBlockingConnection(host, port, new DataHandler());
connection.write("GET " + path + " HTTP\r\n\r\n");
// do somthing else
try {
Thread.sleep(300);
} catch (InterruptedException ignore) { }
} finally {
if (connection != null) {
connection.close();
}
}
}
private static final class DataHandler implements IDataHandler {
private boolean isHeader = true;
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
String line = null;
do {
line = connection.readStringByDelimiter("\r\n").trim();;
if ((line.length() > 0) && isHeader) {
System.out.println(line);
}
} while (line.length() > 0);
isHeader = false;
return true;
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/NonBlockingClient.java | Java | art | 2,679 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
@Execution(Execution.NONTHREADED)
public final class EchoHandler implements IConnectHandler, IDataHandler {
public static final String DELIMITER = "\r\n";
public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
connection.setFlushmode(FlushMode.ASYNC);
connection.setAutoflush(false);
return true;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException {
ByteBuffer[] buffer = connection.readByteBufferByDelimiter(DELIMITER, Integer.MAX_VALUE);
connection.write(buffer);
connection.write(DELIMITER);
connection.flush();
return true;
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/EchoHandler.java | Java | art | 2,194 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.Resource;
import org.xsocket.SSLTestContextFactory;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.NonBlockingConnection;
import org.xsocket.connection.Server;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
public final class ThreadedSSLProxy extends Server {
public ThreadedSSLProxy(int listenPort, String forwardHost, int forwardPort, boolean prestartSSL) throws Exception {
super(listenPort, new ClientToProxyHandler(InetAddress.getByName(forwardHost), forwardPort, prestartSSL), SSLTestContextFactory.getSSLContext(), prestartSSL);
}
public static void main(String... args) throws Exception {
if (args.length != 3) {
System.out.println("usage org.xsocket.stream.Proxy <listenport> <forwardhost> <forwardport> <prestartSSL>");
System.exit(-1);
}
ThreadedSSLProxy proxy = new ThreadedSSLProxy(Integer.parseInt(args[0]), args[1], Integer.parseInt(args[2]), Boolean.parseBoolean(args[3]));
ConnectionUtils.registerMBean(proxy);
proxy.run();
}
private static class ProxyHandler implements IDataHandler, IConnectHandler, IDisconnectHandler {
private boolean prestartSSL = true;
public ProxyHandler(boolean prestartSSL) {
this.prestartSSL = prestartSSL;
}
public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (!prestartSSL) {
connection.activateSecuredMode();
}
return true;
}
public boolean onDisconnect(INonBlockingConnection connection) throws IOException {
INonBlockingConnection reverseConnection = (INonBlockingConnection) connection.getAttachment();
if (reverseConnection != null) {
connection.setAttachment(null);
reverseConnection.close();
}
return true;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
INonBlockingConnection forwardConnection = (INonBlockingConnection) connection.getAttachment();
ByteBuffer[] data = connection.readByteBufferByLength(connection.available());
forwardConnection.write(data);
return true;
}
}
private static final class ClientToProxyHandler extends ProxyHandler implements IConnectHandler {
private InetAddress forwardHost = null;
private int forwardPort = 0;
private boolean prestartSSL = true;
@Resource
private IServer srv = null;
public ClientToProxyHandler(InetAddress forwardHost, int forwardPort, boolean prestartSSL) {
super(prestartSSL);
this.prestartSSL = prestartSSL;
this.forwardHost = forwardHost;
this.forwardPort = forwardPort;
}
public boolean onConnect(INonBlockingConnection clientToProxyConnection) throws IOException {
super.onConnect(clientToProxyConnection);
clientToProxyConnection.setFlushmode(FlushMode.ASYNC); // set flush mode async for performance reasons
Executor workerPool = srv.getWorkerpool(); // performance optimization -> using server worker pool for client connection, too
INonBlockingConnection proxyToServerConnection = new NonBlockingConnection(forwardHost, forwardPort, new ProxyHandler(prestartSSL), workerPool);
proxyToServerConnection.setFlushmode(FlushMode.ASYNC); // set flush mode async for performance reasons
proxyToServerConnection.setAttachment(clientToProxyConnection);
clientToProxyConnection.setAttachment(proxyToServerConnection);
return true;
}
public boolean onDisconnect(INonBlockingConnection clientToProxyConnection) throws IOException {
return super.onDisconnect(clientToProxyConnection);
}
public boolean onData(INonBlockingConnection clientToProxyConnection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return super.onData(clientToProxyConnection);
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/ThreadedSSLProxy.java | Java | art | 5,523 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
*
* @author grro@xsocket.org
*/
final class JavaProcess {
private ConsoleReader reader = null;
private Process p = null;
public void start(String classname, String jarFileURI, String... params) throws IOException {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
terminate();
}
});
System.out.println("loading jar file " + jarFileURI + " ...");
URL url = new URL(jarFileURI);
InputStream is = url.openStream();
File jarFile = File.createTempFile("test", "test");
jarFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(jarFile);
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytes_read);
}
fos.close();
is.close();
String[] args = new String[params.length + 4];
args[0] = "java";
args[1] = "-cp";
args[2] = jarFile.getAbsolutePath();
args[3] = classname;
System.arraycopy(params, 0, args, 4, params.length);
StringBuilder sb = new StringBuilder();
for (String arg : args) {
sb.append(arg + " ");
}
System.out.println("execute " + sb);
ProcessBuilder pb = new ProcessBuilder(args);
p = pb.start();
reader = new ConsoleReader(p.getInputStream());
new Thread(reader).start();
}
public void terminate() {
try {
p.destroy();
reader.terminate();
} catch (Exception ignore) { }
}
private static final class ConsoleReader implements Runnable {
private Thread t = null;
private InputStream is = null;
ConsoleReader(InputStream is) {
this.is = is;
}
public void run() {
t = Thread.currentThread();
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void terminate() {
t.interrupt();
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/JavaProcess.java | Java | art | 3,373 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import org.junit.Test;
import org.xsocket.connection.BlockingConnection;
import org.xsocket.connection.IBlockingConnection;
/**
*
* @author grro@xsocket.org
*/
public final class SimpleImapClient {
private int i = 0;
public static void main(String[] args) throws IOException {
if (args.length != 4) {
System.out.println("usage org.xsocket.connection.SimpleImapClient <host> <port> <user> <pwd>");
System.exit(-1);
}
new SimpleImapClient().launch(args[0], Integer.parseInt(args[1]), args[2], args[3]);
}
public void launch(String host, int port, String user, String pwd) throws IOException {
IBlockingConnection con = new BlockingConnection(host, port);
System.out.println(con.readStringByDelimiter("\r\n"));
String response = call(con, "LOGIN " + user + " " +pwd);
response = call(con, "SELECT INBOX");
response = call(con, "FETCH 1:1 (INTERNALDATE BODY[HEADER.FIELDS (RECEIVED FROM SUBJECT)])");
con.close();
}
private String call(IBlockingConnection con, String cmd) throws IOException {
StringBuilder sb = new StringBuilder();
String tag = "A" + (i++);
String request = tag + " " + cmd + "\r\n";
System.out.println(request);
con.write(request);
String line = null;
do {
line = con.readStringByDelimiter("\r\n");
sb.append(line + "\r\n");
} while (!line.trim().startsWith(tag));
String response = sb.toString();
System.out.println(response);
return response;
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/SimpleImapClient.java | Java | art | 2,605 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferUnderflowException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.xsocket.DataConverter;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;
import org.xsocket.connection.ConnectionUtils;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
public final class SimpleSmtpServer extends Server {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("usage org.xsocket.connection.SimpleSmtpServer <port> <message file dir>");
System.exit(-1);
}
int port = Integer.parseInt(args[0]);
String outDir = args[1];
if (!new File(outDir).exists()) {
System.out.println(outDir + " does not exists. creating directory");
new File(outDir).mkdirs();
}
System.out.println("writing mails to directory " + outDir);
IServer server = new SimpleSmtpServer(port, outDir);
server.setFlushMode(FlushMode.ASYNC);
ConnectionUtils.registerMBean(server);
server.run();
}
public SimpleSmtpServer(int port, String outDir) throws IOException {
super(port, new SmtpProtocolHandler(outDir));
}
/**
* simple, minimal SMTP protocol handler, which doesn't implement any security/spam protection rule
*
*/
@Execution(Execution.NONTHREADED)
private static final class SmtpProtocolHandler implements IConnectHandler, IDataHandler {
private String msgFileDir = null;
private int countReceivedMessages = 0;
public SmtpProtocolHandler(String msgFileDir) {
this.msgFileDir = msgFileDir;
}
public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
connection.setAttachment(new SessionData());
connection.write("220 SMTP ready \r\n");
return true;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
SessionData sessionData = (SessionData) connection.getAttachment();
String cmd = connection.readStringByDelimiter("\r\n").toUpperCase();
if (cmd.startsWith("HELO")) {
connection.write("250 SMTP Service\r\n");
} else if (cmd.startsWith("MAIL FROM:")) {
String originator = cmd.substring("MAIL FROM:".length(), cmd.length()).trim();
sessionData.setOriginator(originator);
connection.write("250 " + originator + " is syntactically correct\r\n");
} else if (cmd.startsWith("RCPT TO:")) {
String recipient = cmd.substring("RCPT TO:".length(), cmd.length());
sessionData.addRecipients(recipient);
connection.write("250 " + recipient + " verified\r\n");
} else if(cmd.equals("DATA")) {
String timeStamp = "Received: from " + connection.getRemoteAddress() + "; " + new Date() + "\r\n"; // wrong date format! fix it
String msgId = connection.getId() + "." + sessionData.nextId();
File msgFile = new File(msgFileDir + File.separator + msgId + ".msg");
connection.setHandler(new DataHandler(msgFile, timeStamp, this));
connection.write("354 Enter message, ending with \".\"\r\n");
} else if (cmd.startsWith("QUIT")) {
connection.write("221 SMTP service closing connection\r\n");
connection.close();
} else {
connection.write("500 Unrecognized command\r\n");
}
return true;
}
String getMessageFileDirectory() {
return msgFileDir;
}
void setMessageFileDirectory(String msgFileDir) {
this.msgFileDir = msgFileDir;
}
int getCountReceivedMessages() {
return countReceivedMessages;
}
void incCountReceiveMessages() {
countReceivedMessages++;
}
}
@Execution(Execution.MULTITHREADED)
private static final class DataHandler implements IDataHandler {
private SmtpProtocolHandler smtpHandler;
private File file;
private String timeStamp;
private FileChannel fc;
public DataHandler(File file, String timeStamp, SmtpProtocolHandler smtpHandler) {
this.file = file;
this.timeStamp = timeStamp;
this.smtpHandler = smtpHandler;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (fc == null) {
file.createNewFile();
fc = new RandomAccessFile(file, "rw").getChannel();
fc.write(DataConverter.toByteBuffer(timeStamp, "US-ASCII"));
}
int delimiterPos = connection.indexOf("\r\n.\r\n");
if (delimiterPos != -1) {
connection.transferTo(fc, delimiterPos);
connection.readByteBufferByLength(5); // remove delimiter
fc.close();
fc = null;
smtpHandler.incCountReceiveMessages();
connection.setHandler(smtpHandler);
connection.write("250 OK\r\n");
} else if (connection.available() > 5) {
int size = connection.available() - 5;
connection.transferTo(fc, size);
}
return true;
}
}
private static final class SessionData {
private long id = 0;
private String originator = null;
private List<String> recipients = new ArrayList<String>();
long nextId() {
return id++;
}
String getOriginator() {
return originator;
}
void setOriginator(String originator) {
this.originator = originator;
}
List<String> getRecipients() {
return recipients;
}
void addRecipients(String recipient) {
recipients.add(recipient);
}
void reset() {
originator = null;
recipients.clear();
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/SimpleSmtpServer.java | Java | art | 7,148 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.xsocket.connection.INonBlockingConnection;
/**
*
* @author grro@xsocket.org
*/
public interface IHttpConnection extends INonBlockingConnection {
public HttpHeader readHeader() throws IOException, BufferUnderflowException;
public void writeHeader(HttpHeader header) throws IOException;
public static final class HttpHeader {
private String firstLine = null;
private List<String> headerLines = null;
HttpHeader(int statusCode) {
switch (statusCode) {
case 200:
firstLine = "HTTP/1.1 200 OK";
break;
case 404:
firstLine = "HTTP/1.1 404 Not found";
break;
default:
firstLine = "HTTP/1.1 400 Bad Request";
break;
}
headerLines = new ArrayList<String>();
}
HttpHeader(String rawHeader) {
int posFirstCRLF = rawHeader.indexOf("\r\n");
firstLine = rawHeader.substring(0, posFirstCRLF);
headerLines = Arrays.asList(rawHeader.substring(posFirstCRLF + 1, rawHeader.length()).split("\r\n"));
}
public String getMethod() {
return firstLine.split(" ")[0];
}
public final String getRequestURI() {
return firstLine.split(" ")[1];
}
public String[] getHeaderLines() {
return headerLines.toArray(new String[headerLines.size()]);
}
public void addHeaderLine(String headerLine) {
headerLines.add(headerLine);
}
String getFirstLine() {
return firstLine;
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/IHttpConnection.java | Java | art | 2,656 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferUnderflowException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.xsocket.DataConverter;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.SSLTestContextFactory;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;
import org.xsocket.connection.ConnectionUtils;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
public final class VerySimpleHttpServer extends Server {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("usage org.xsocket.connection.VerySimpleHttpServer <port>");
System.exit(-1);
}
int port = Integer.parseInt(args[0]);
IServer server = new VerySimpleHttpServer(port);
server.setFlushMode(FlushMode.ASYNC);
ConnectionUtils.registerMBean(server);
server.run();
}
public VerySimpleHttpServer(int port) throws IOException {
//super(port, new HttpProtocolHandler());
super(port, new HttpProtocolHandler(), SSLTestContextFactory.getSSLContext(), true);
}
@Execution(Execution.NONTHREADED)
private static final class HttpProtocolHandler implements IDataHandler {
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
String header = connection.readStringByDelimiter("\r\n\r\n");
connection.write("HTTP/1.0 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"content-length: 10\r\n" +
"\r\n" +
"1234567890");
return true;
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/VerySimpleHttpServer.java | Java | art | 3,012 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import org.xsocket.connection.IHttpConnection.HttpHeader;
/**
*
* @author grro@xsocket.org
*/
public interface IHttpMessageHandler {
public void onHttpMessage(IHttpConnection httpConnection) throws BufferUnderflowException, IOException;
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/IHttpMessageHandler.java | Java | art | 1,372 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.nio.ByteBuffer;
import org.junit.Assert;
import org.xsocket.QAUtil;
import org.xsocket.connection.BlockingConnection;
import org.xsocket.connection.IBlockingConnection;
/**
*
* @author grro@xsocket.org
*/
public final class LoadClient {
public static void main(String... args) throws Exception {
if (args.length != 4) {
System.out.println("usage org.xsocket.stream.LoadClient <hostname> <port> <numWorkers> <packetSize>");
System.exit(-1);
}
new LoadClient(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[2]));
}
LoadClient(final String hostname, final int port, int numWorkers, final int dataSize) throws Exception {
for (int i = 0; i < numWorkers; i++) {
Thread t = new Thread() {
@Override
public void run() {
try {
IBlockingConnection con = new BlockingConnection(hostname, port);
con.setAutoflush(false);
ByteBuffer data = QAUtil.generateByteBuffer(dataSize);
while (true) {
con.write(data);
con.flush();
data.rewind();
ByteBuffer[] response = con.readByteBufferByLength(dataSize);
if (!QAUtil.isEquals(new ByteBuffer[] { data }, response)) {
System.out.print("E");
} else {
System.out.print(".");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/LoadClient.java | Java | art | 2,531 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.LogFormatter;
/**
*
* @author grro@xsocket.org
*/
public final class SimpleSmtpClient {
private static final Logger LOG = Logger.getLogger(SimpleSmtpClient.class.getName());
private String host = null;
private int port = -1;
public static void main(String[] args) throws Exception {
Logger logger = Logger.getLogger(SimpleSmtpClient.class.getName());
logger.setLevel(Level.FINE);
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.FINE);
ch.setFormatter(new LogFormatter());
logger.addHandler(ch);
if (args.length != 3) {
System.out.println("usage org.xsocket.connection.SimpleSmtpClient <host> <port> <message file>");
System.exit(-1);
}
String host = args[0];
int port = Integer.parseInt(args[1]);
String file = args[2];
if (!new File(file).exists()) {
System.out.println("message file " + file + " does not exits");
System.exit(-1);
}
FileInputStream fos = new FileInputStream(file);
byte[] b = new byte[fos.available()];
fos.read(b);
fos.close ();
String msg = new String(b);
SimpleSmtpClient smtpClient = new SimpleSmtpClient(host, port);
smtpClient.send(msg);
}
public SimpleSmtpClient(String host, int port) throws IOException {
this.host = host;
this.port = port;
}
public void send(String message) throws IOException {
IBlockingConnection con = new BlockingConnection(host, port);
// read greeting
readResponse(con);
sendCmd(con, "Helo you");
readResponse(con);
int i = message.indexOf("From: ");
String sender = message.substring(i + "From: ".length(), message.indexOf("\r\n", i));
sendCmd(con, "Mail From: " + sender);
readResponse(con);
i = message.indexOf("To: ");
String receiver = message.substring(i + "To: ".length(), message.indexOf("\r\n", i));
sendCmd(con, "Rcpt To: " + receiver);
readResponse(con);
sendCmd(con, "Data");
readResponse(con);
String[] lines = message.split("\r\n");
for (String line : lines) {
if (line.startsWith(".")) {
line = "." + line;
}
con.write(line + "\r\n");
}
con.write("\r\n.\r\n");
sendCmd(con, "Quit");
readResponse(con);
con.close();
}
private void sendCmd(IBlockingConnection con, String cmd) throws IOException {
LOG.fine("sending " + cmd);
con.write(cmd + "\r\n");
}
private String readResponse(IBlockingConnection con) throws IOException {
String response = con.readStringByDelimiter("\r\n");
LOG.fine("receiving " + response);
return response;
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/SimpleSmtpClient.java | Java | art | 3,904 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import org.xsocket.connection.BlockingConnection;
import org.xsocket.connection.IBlockingConnection;
/**
*
* @author grro@xsocket.org
*/
public final class BlockingClient {
public static void main(String... args) throws Exception {
if (args.length != 3) {
System.out.println("usage org.xsocket.stream.BlockingClient <host> <port> <path>");
System.exit(-1);
}
new BlockingClient().call(args[0], Integer.parseInt(args[1]), args[2]);
}
public void call(String host, int port, String path) throws IOException {
IBlockingConnection connection = null;
try {
connection = new BlockingConnection(host, port);
connection.write("GET " + path + " HTTP\r\n\r\n");
int bodyLength = 0;
// print header
String line = null;
do {
line = connection.readStringByDelimiter("\r\n").trim();
if (line.startsWith("Content-Length:")) {
bodyLength = new Integer(line.substring("Content-Length:".length(), line.length()).trim());
}
if (line.length() > 0) {
System.out.println(line);
}
} while (line.length() > 0);
// print body
if (bodyLength > 0) {
System.out.println(connection.readStringByLength(bodyLength));
}
} finally {
if (connection != null) {
connection.close();
}
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/BlockingClient.java | Java | art | 2,423 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.Resource;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.NonBlockingConnection;
import org.xsocket.connection.Server;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
public final class Proxy extends Server {
public Proxy(int listenPort, String forwardHost, int forwardPort) throws Exception {
super(listenPort, new ClientToProxyHandler(InetAddress.getByName(forwardHost), forwardPort));
}
public static void main(String... args) throws Exception {
if (args.length != 3) {
System.out.println("usage org.xsocket.stream.Proxy <listenport> <forwardhost> <forwardport>");
System.exit(-1);
}
Proxy proxy = new Proxy(Integer.parseInt(args[0]), args[1], Integer.parseInt(args[2]));
ConnectionUtils.registerMBean(proxy);
proxy.run();
}
@Execution(Execution.NONTHREADED)
private static class ProxyHandler implements IDataHandler, IDisconnectHandler {
public boolean onDisconnect(INonBlockingConnection connection) throws IOException {
INonBlockingConnection reverseConnection = (INonBlockingConnection) connection.getAttachment();
if (reverseConnection != null) {
connection.setAttachment(null);
reverseConnection.close();
}
return true;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
INonBlockingConnection forwardConnection = (INonBlockingConnection) connection.getAttachment();
ByteBuffer[] data = connection.readByteBufferByLength(connection.available());
forwardConnection.write(data);
return true;
}
}
@Execution(Execution.NONTHREADED)
private static final class ClientToProxyHandler extends ProxyHandler implements IConnectHandler {
private InetAddress forwardHost = null;
private int forwardPort = 0;
@Resource
private IServer srv = null;
public ClientToProxyHandler(InetAddress forwardHost, int forwardPort) {
this.forwardHost = forwardHost;
this.forwardPort = forwardPort;
}
@Execution(Execution.MULTITHREADED)
public boolean onConnect(INonBlockingConnection clientToProxyConnection) throws IOException {
clientToProxyConnection.setFlushmode(FlushMode.ASYNC); // set flush mode async for performance reasons
Executor workerPool = srv.getWorkerpool(); // performance optimization -> using server worker pool for client connection, too
INonBlockingConnection proxyToServerConnection = new NonBlockingConnection(forwardHost, forwardPort, new ProxyHandler(), workerPool);
proxyToServerConnection.setFlushmode(FlushMode.ASYNC); // set flush mode async for performance reasons
proxyToServerConnection.setAttachment(clientToProxyConnection);
clientToProxyConnection.setAttachment(proxyToServerConnection);
return true;
}
public boolean onDisconnect(INonBlockingConnection clientToProxyConnection) throws IOException {
return super.onDisconnect(clientToProxyConnection);
}
public boolean onData(INonBlockingConnection clientToProxyConnection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return super.onData(clientToProxyConnection);
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/Proxy.java | Java | art | 4,837 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.Resource;
import org.xsocket.SSLTestContextFactory;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.NonBlockingConnection;
import org.xsocket.connection.Server;
import org.xsocket.connection.IConnection.FlushMode;
/**
*
* @author grro@xsocket.org
*/
public final class NonThreadedSSLProxy extends Server {
public NonThreadedSSLProxy(int listenPort, String forwardHost, int forwardPort, boolean prestartSSL) throws Exception {
super(listenPort, new ClientToProxyHandler(InetAddress.getByName(forwardHost), forwardPort, prestartSSL), SSLTestContextFactory.getSSLContext(), prestartSSL);
}
public static void main(String... args) throws Exception {
if (args.length != 3) {
System.out.println("usage org.xsocket.stream.Proxy <listenport> <forwardhost> <forwardport> <prestartSSL>");
System.exit(-1);
}
NonThreadedSSLProxy proxy = new NonThreadedSSLProxy(Integer.parseInt(args[0]), args[1], Integer.parseInt(args[2]), Boolean.parseBoolean(args[3]));
ConnectionUtils.registerMBean(proxy);
proxy.run();
}
@Execution(Execution.NONTHREADED)
private static class ProxyHandler implements IDataHandler, IConnectHandler, IDisconnectHandler {
private boolean prestartSSL = true;
public ProxyHandler(boolean prestartSSL) {
this.prestartSSL = prestartSSL;
}
public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
if (!prestartSSL) {
connection.activateSecuredMode();
}
return true;
}
public boolean onDisconnect(INonBlockingConnection connection) throws IOException {
INonBlockingConnection reverseConnection = (INonBlockingConnection) connection.getAttachment();
if (reverseConnection != null) {
connection.setAttachment(null);
reverseConnection.close();
}
return true;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
INonBlockingConnection forwardConnection = (INonBlockingConnection) connection.getAttachment();
ByteBuffer[] data = connection.readByteBufferByLength(connection.available());
forwardConnection.write(data);
return true;
}
}
@Execution(Execution.NONTHREADED)
private static final class ClientToProxyHandler extends ProxyHandler implements IConnectHandler {
private InetAddress forwardHost = null;
private int forwardPort = 0;
private boolean prestartSSL = true;
@Resource
private IServer srv = null;
public ClientToProxyHandler(InetAddress forwardHost, int forwardPort, boolean prestartSSL) {
super(prestartSSL);
this.prestartSSL = prestartSSL;
this.forwardHost = forwardHost;
this.forwardPort = forwardPort;
}
public boolean onConnect(INonBlockingConnection clientToProxyConnection) throws IOException {
super.onConnect(clientToProxyConnection);
clientToProxyConnection.setFlushmode(FlushMode.ASYNC); // set flush mode async for performance reasons
Executor workerPool = srv.getWorkerpool(); // performance optimization -> using server worker pool for client connection, too
INonBlockingConnection proxyToServerConnection = new NonBlockingConnection(forwardHost, forwardPort, new ProxyHandler(prestartSSL), workerPool);
proxyToServerConnection.setFlushmode(FlushMode.ASYNC); // set flush mode async for performance reasons
proxyToServerConnection.setAttachment(clientToProxyConnection);
clientToProxyConnection.setAttachment(proxyToServerConnection);
return true;
}
public boolean onDisconnect(INonBlockingConnection clientToProxyConnection) throws IOException {
return super.onDisconnect(clientToProxyConnection);
}
public boolean onData(INonBlockingConnection clientToProxyConnection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
return super.onData(clientToProxyConnection);
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/NonThreadedSSLProxy.java | Java | art | 5,607 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import org.xsocket.Execution;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
/**
*
* @author grro@xsocket.org
*/
@Execution(Execution.NONTHREADED)
public final class DevNullHandler implements IDataHandler {
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException {
connection.readByteBufferByLength(connection.available());
return true;
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/DevNullHandler.java | Java | art | 1,579 |
/*
* Copyright (c) xsocket.org, 2006-2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.xsocket.connection.BlockingConnection;
import org.xsocket.connection.IBlockingConnection;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;
import org.xsocket.connection.ConnectionUtils;
/**
*
* @author grro@xsocket.org
*/
public final class ServerPush {
public static void main(String... args) throws Exception {
IServer server = new Server(0, new Handler());
ConnectionUtils.start(server);
IBlockingConnection con = new BlockingConnection("localhost", server.getLocalPort());
for (int i = 0; i < 3; i++) {
System.out.println(con.readStringByDelimiter("\r\n"));
}
con.close();
server.close();
}
private static class Handler implements IConnectHandler {
private final Timer timer = new Timer(true);
public boolean onConnect(INonBlockingConnection connection) throws IOException {
Notifier notifier = new Notifier(connection);
timer.schedule(notifier, 500, 500);
return true;
}
}
private static final class Notifier extends TimerTask {
private INonBlockingConnection connection = null;
public Notifier(INonBlockingConnection connection) {
this.connection = connection;
}
@Override
public void run() {
try {
connection.write("pong\r\n");
} catch (Exception e) {
System.out.println("error occured by sending pong to " + connection.getRemoteAddress() + ":" + connection.getRemotePort());
}
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/connection/ServerPush.java | Java | art | 2,732 |
/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* helper class to collect and print statistics
*
* @author grro
*/
public final class Statistic {
private static final int SECTION_TIMERANGE = 30 * 1000;
private final ArrayList<Integer> times = new ArrayList<Integer>();
private ArrayList<Integer> tempTimes = new ArrayList<Integer>();
private long lastPrint = System.currentTimeMillis();
private long lastSection = System.currentTimeMillis();
private Timer timer = new Timer(true);
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
private boolean firstPrint = true;
public Statistic(boolean autoprint) {
if (autoprint) {
try {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println(print());
}
};
timer.schedule(timerTask, 5000, 5000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String printHeader() {
return "time; throughput; min; max; average; median; p90; p95; p99";
}
public synchronized void addValue(int value) {
times.add(value);
tempTimes.add(value);
}
@SuppressWarnings("unchecked")
public String print() {
StringBuilder sb = new StringBuilder();
ArrayList<Integer> copy = null;
synchronized (this) {
copy = (ArrayList<Integer>) times.clone();
}
Collections.sort(copy);
int sum = 0;
for (Integer i : copy) {
sum += i;
}
if (firstPrint) {
firstPrint = false;
sb.append("\r\n" + printHeader() + "\r\n");
}
sb.append(dateFormat.format(new Date()) + "; ");
ArrayList<Integer> tempTimesCopy = tempTimes;
tempTimes = new ArrayList<Integer>();
long elapsed = System.currentTimeMillis() - lastPrint;
lastPrint = System.currentTimeMillis();
sb.append(((tempTimesCopy.size() * 1000) / elapsed) + "; ");
if (copy.size() > 0) {
sb.append(copy.get(0) + "; ");
sb.append(copy.get(copy.size() - 1) + "; ");
sb.append((sum / copy.size()) + "; ");
sb.append(copy.get(copy.size() / 2) + "; ");
sb.append(copy.get((int) (copy.size() * 0.9)) + "; ");
sb.append(copy.get((int) (copy.size() * 0.95)) + "; ");
sb.append(copy.get((int) (copy.size() * 0.99)));
}
if (System.currentTimeMillis() > (lastSection + SECTION_TIMERANGE)) {
lastSection = System.currentTimeMillis();
times.clear();
sb.append("\r\n\r\n");
sb.append(printHeader());
}
return sb.toString();
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/Statistic.java | Java | art | 3,725 |
/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
/**
*
* @author grro
*/
public class LogFormatter extends Formatter {
private static final SimpleDateFormat DATEFORMAT = new SimpleDateFormat("kk:mm:ss,S");
@Override
public String format(LogRecord record) {
StringBuffer sb = new StringBuffer();
sb.append(DATEFORMAT.format(record.getMillis()));
sb.append(" ");
sb.append(record.getThreadID());
sb.append(" ");
sb.append(record.getLevel());
sb.append(" [");
String clazzname = record.getSourceClassName();
int i = clazzname.lastIndexOf(".");
clazzname = clazzname.substring(i + 1, clazzname.length());
sb.append(clazzname);
sb.append("#");
sb.append(record.getSourceMethodName());
sb.append("] ");
sb.append(record.getMessage() + "\n");
return sb.toString();
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/LogFormatter.java | Java | art | 1,949 |
/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Random;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Assert;
/**
*
* @author grro@xsocket.org
*/
public final class QAUtil {
private static String testMail =
"Received: from localhost (localhost [127.0.0.1])\r\n"
+ "by Semta.de with ESMTP id 881588961.1153334034540.1900236652.1\r\n"
+ "for feki@semta.de; Mi, 19 Jul 2006 20:34:00 +0200\r\n"
+ "Message-ID: <24807938.01153334039898.JavaMail.grro@127.0.0.1>\r\n"
+ "Date: Wed, 19 Jul 2006 20:33:59 +0200 (CEST)\r\n"
+ "From: feki2 <fekete99@web.de>\r\n"
+ "To: Gregor Roth <feki@semta.de>\r\n"
+ "Subject: Test mail\r\n"
+ "MIME-Version: 1.0\r\n"
+ "Content-Type: multipart/mixed;\r\n"
+ "boundary=\"----=_Part_1_14867177.1153334039707\"\r\n"
+ "\r\n"
+ "This is a multi-part message in MIME format.\r\n"
+ "------=_Part_1_14867177.1153334039707\r\n"
+ "Content-Type: multipart/mixed;\r\n"
+ "boundary=\"----=_Part_0_14158819.1153334039687\"\r\n"
+ "\r\n"
+ "------=_Part_0_14158819.1153334039687\r\n"
+ "Content-Type: text/plain; charset=us-ascii\r\n"
+ "Content-Transfer-Encoding: 7bit\r\n"
+ "\r\n"
+ "Halli Hallo\r\n"
+ "------=_Part_0_14158819.1153334039687\r\n"
+ "------=_Part_1_14867177.1153334039707--";
private static final int OFFSET = 48;
private static final Random random = new Random();
private QAUtil() { }
public static String getNameTestfile_4k() {
String filename = null;
URL keystoreUrl = QAUtil.class.getResource("Testfile_4k.html");
if (keystoreUrl != null) {
filename = keystoreUrl.getFile();
} else {
filename = new File("src" + File.separator + "test" + File.separator
+ "resources" + File.separator + "org" + File.separator
+ "xsocket" + File.separator + "Testfile_4k.html").getAbsolutePath();
}
if (!new File(filename).exists()) {
return null;
}
return filename;
}
public static String getNameTestfile_400k() {
String filename = null;
URL keystoreUrl = QAUtil.class.getResource("Testfile_400k.html");
if (keystoreUrl != null) {
filename = keystoreUrl.getFile();
} else {
filename = new File("src" + File.separator + "test" + File.separator
+ "resources" + File.separator + "org" + File.separator
+ "xsocket" + File.separator + "Testfile_400k.html").getAbsolutePath();
}
if (!new File(filename).exists()) {
return null;
}
return filename;
}
public static String getNameTestfile_40k() {
String filename = null;
URL keystoreUrl = QAUtil.class.getResource("Testfile_40k.html");
if (keystoreUrl != null) {
filename = keystoreUrl.getFile();
} else {
filename = new File("src" + File.separator + "test" + File.separator
+ "resources" + File.separator + "org" + File.separator
+ "xsocket" + File.separator + "connection" + File.separator + "Testfile_40k.html").getAbsolutePath();
}
if (!new File(filename).exists()) {
return null;
}
return filename;
}
public static ByteBuffer getAsByteBuffer() {
try {
Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer buf = encoder.encode(CharBuffer.wrap(testMail.toCharArray()));
return buf;
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
}
public static ByteBuffer generateByteBuffer(int length) {
ByteBuffer buffer = ByteBuffer.wrap(generateByteArray(length));
return buffer;
}
public static ByteBuffer generateDirectByteBuffer(int length) {
byte[] bytes = generateByteArray(length);
ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length);
buffer.put(bytes);
buffer.flip();
return buffer;
}
public static ByteBuffer[] generateDirectByteBufferArray(int elements, int length) {
ByteBuffer[] byteBufferArray = new ByteBuffer[elements];
for (int i = 0; i < elements; i++) {
byteBufferArray[i] = generateDirectByteBuffer(length);
}
return byteBufferArray;
}
public static byte[] generateByteArray(int length) {
byte[] bytes = new byte[length];
int item = OFFSET;
for (int i = 0; i < length; i++) {
bytes[i] = (byte) item;
item++;
if (item > (OFFSET + 9)) {
item = OFFSET;
}
}
return bytes;
}
public static byte[] generateRandomByteArray(int length) {
byte[] bytes = new byte[length];
random.nextBytes(bytes);
return bytes;
}
public static byte[] generateByteArray(int length, String delimiter) {
byte[] del = delimiter.getBytes();
byte[] data = generateByteArray(length);
byte[] result = new byte[del.length + data.length];
System.arraycopy(data, 0, result, 0, data.length);
System.arraycopy(del, 0, result, data.length, del.length);
return result;
}
public static boolean isEquals(byte[] b1, byte[] b2) {
if (b1.length != b2.length) {
return false;
}
for (int i = 0; i < b1.length; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
public static boolean isEquals(ByteBuffer[] b1, ByteBuffer[] b2) {
return isEquals(DataConverter.toByteBuffer(b1), DataConverter.toByteBuffer(b2));
}
public static boolean isEquals(File file, String text) throws IOException {
ByteBuffer buf = DataConverter.toByteBuffer(text, "UTF-8");
return isEquals(file, new ByteBuffer[] { buf } );
}
public static boolean isEquals(File file, ByteBuffer[] buffers) throws IOException {
int length = 0;
for (ByteBuffer byteBuffer : buffers) {
length += byteBuffer.remaining();
}
FileChannel fc = new RandomAccessFile(file, "r").getChannel();
ByteBuffer buf = ByteBuffer.allocate(length);
fc.read(buf);
buf.flip();
return isEquals(buf, buffers);
}
public static boolean isEquals(ByteBuffer b1, ByteBuffer[] b2) {
return isEquals(b1, DataConverter.toByteBuffer(b2));
}
public static boolean isEquals(ByteBuffer b1, ByteBuffer b2) {
if (b1.limit() != b2.limit()) {
return false;
}
if (b1.position() != b2.position()) {
return false;
}
if (b1.capacity() != b2.capacity()) {
return false;
}
for (int i = 0; i < b1.limit(); i++) {
if (b1.get(i) != b2.get(i)) {
return false;
}
}
return true;
}
public static void sleep(int sleepTime) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException ignore) { }
}
public static byte[] mergeByteArrays(byte[] b1, byte[] b2) {
byte[] result = new byte[b1.length + b2.length];
System.arraycopy(b1, 0, result, 0, b1.length);
System.arraycopy(b2, 0, result, b1.length, b2.length);
return result;
}
public static byte[] toArray(ByteBuffer buffer) {
byte[] array = new byte[buffer.limit() - buffer.position()];
if (buffer.hasArray()) {
int offset = buffer.arrayOffset() + buffer.position();
byte[] bufferArray = buffer.array();
System.arraycopy(bufferArray, offset, array, 0, array.length);
return array;
} else {
buffer.get(array);
return array;
}
}
public static void setLogLevel(String level) {
setLogLevel("org.xsocket", Level.parse(level));
}
public static void setLogLevel(Level level) {
setLogLevel("org.xsocket", level);
}
public static void setLogLevel(String namespace, String level) {
setLogLevel(namespace, Level.parse(level));
}
public static void setLogLevel(String namespace, Level level) {
Logger logger = Logger.getLogger(namespace);
logger.setLevel(level);
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(level);
ch.setFormatter(new LogFormatter());
logger.addHandler(ch);
}
public static void assertTimeout(long elapsed, long expected, long min, long max) {
System.out.println("elapsed time " + elapsed + " (expected=" + expected + ", min=" + min + ", max=" + max + ")");
Assert.assertTrue("elapsed time " + elapsed + " out of range (expected=" + expected + ", min=" + min + ", max=" + max + ")"
, (elapsed >= min) && (elapsed <= max));
}
public static InetAddress getRandomLocalAddress() throws IOException {
String hostname = InetAddress.getLocalHost().getHostName();
InetAddress[] addresses = InetAddress.getAllByName(hostname);
int i = new Random().nextInt();
if (i < 0) {
i = 0 - i;
}
i = i % addresses.length;
return addresses[i];
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/QAUtil.java | Java | art | 10,156 |
/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
*
* @author grro@xsocket.org
*/
public final class DebugPrintStream extends PrintStream {
private ByteArrayOutputStream os = new ByteArrayOutputStream();
public DebugPrintStream(PrintStream delegee) {
super(delegee);
}
@Override
public void write(byte[] data) throws IOException {
os.write(data);
super.write(data);
}
@Override
public void write(byte[] data, int off, int len) {
os.write(data, off, len);
super.write(data, off, len);
}
@Override
public void write(int data) {
os.write(data);
super.write(data);
}
public byte[] getData() {
return os.toByteArray();
}
public void clear() {
os = new ByteArrayOutputStream();
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/DebugPrintStream.java | Java | art | 1,850 |
/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javax.management.MBeanServer;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
/**
* Helper class to run a JMXConnectorServer by using rmi
*
* @author grro@xsocket.org
*/
public final class JmxServer {
private JMXConnectorServer server = null;
/**
* start the server
*
* @param name the name space
*/
public void start(String name) {
start(name, 1199);
}
/**
* start the server
*
* @param name the name space
* @param rmiPort the rmi port to use
* @return jmxservice url
*/
public JMXServiceURL start(String name, int rmiPort) {
try {
Registry registry = LocateRegistry.createRegistry(rmiPort);
registry.unbind(name);
} catch (Exception ignore) { }
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + "localhost" + ":" + rmiPort + "/" + name);
MBeanServer mbeanSrv = ManagementFactory.getPlatformMBeanServer();
server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbeanSrv);
server.start();
System.out.println("JMX RMI Agent has been bound on address");
System.out.println(url);
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* stops the server
*
*/
public void stop() {
try {
server.stop();
} catch (IOException ioe) {
// ignore
}
}
}
| zzh-simple-hr | Zxsocket/test/org/xsocket/JmxServer.java | Java | art | 2,703 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.example.ftpletservice;
import java.io.IOException;
import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpletResult;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class MyFtplet extends DefaultFtplet {
@Override
public FtpletResult onConnect(FtpSession session) throws FtpException,
IOException {
System.out.println("User connected to FtpServer");
return super.onConnect(session);
}
@Override
public FtpletResult onDisconnect(FtpSession session) throws FtpException,
IOException {
System.out.println("User connected to FtpServer");
return super.onDisconnect(session);
}
}
| zzh-simple-hr | Zftp/distribution/org/apache/ftpserver/example/ftpletservice/MyFtplet.java | Java | art | 1,689 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.example.ftpletservice.impl;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.ftpserver.example.ftpletservice.MyFtplet;
import org.apache.ftpserver.ftplet.Ftplet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
Dictionary<String, String> properties = new Hashtable<String, String>();
properties.put("name", "myftplet");
context.registerService(Ftplet.class.getName(), new MyFtplet(), properties);
}
public void stop(BundleContext context) throws Exception {
// do nothing
}
}
| zzh-simple-hr | Zftp/distribution/org/apache/ftpserver/example/ftpletservice/impl/Activator.java | Java | art | 1,638 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.example.osgiservice.impl;
import org.apache.ftpserver.FtpServer;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class FtpServerLifecycle {
private FtpServer server;
public FtpServer getServer() {
return server;
}
public void setServer(FtpServer server) {
this.server = server;
}
public void init() throws Exception {
server.start();
System.out.println("Server started");
}
public void destroy() throws Exception {
server.stop();
System.out.println("Server stopped");
}
}
| zzh-simple-hr | Zftp/distribution/org/apache/ftpserver/example/osgiservice/impl/FtpServerLifecycle.java | Java | art | 1,440 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.example.springwar;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ftpserver.FtpServer;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class FtpServerServlet extends HttpServlet {
private static final long serialVersionUID = 5539642787624981705L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
FtpServer server = (FtpServer) getServletContext().getAttribute(FtpServerListener.FTPSERVER_CONTEXT_NAME);
PrintWriter wr = resp.getWriter();
wr.print("<html>");
wr.print("<head>");
wr.print("<title>FtpServer status servlet</title>");
wr.print("</head>");
wr.print("<body>");
wr.print("<form method='post'>");
if(server.isStopped()) {
wr.print("<p>FtpServer is stopped.</p>");
} else {
if(server.isSuspended()) {
wr.print("<p>FtpServer is suspended.</p>");
wr.print("<p><input type='submit' name='resume' value='Resume'></p>");
wr.print("<p><input type='submit' name='stop' value='Stop'></p>");
} else {
wr.print("<p>FtpServer is running.</p>");
wr.print("<p><input type='submit' name='suspend' value='Suspend'></p>");
wr.print("<p><input type='submit' name='stop' value='Stop'></p>");
}
}
wr.print("</form>");
wr.print("</body>");
wr.print("</html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
FtpServer server = (FtpServer) getServletContext().getAttribute(FtpServerListener.FTPSERVER_CONTEXT_NAME);
if(req.getParameter("stop") != null) {
server.stop();
} else if(req.getParameter("resume") != null) {
server.resume();
} else if(req.getParameter("suspend") != null) {
server.suspend();
}
resp.sendRedirect("/");
}
}
| zzh-simple-hr | Zftp/distribution/org/apache/ftpserver/example/springwar/FtpServerServlet.java | Java | art | 3,200 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.example.springwar;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.ftpserver.FtpServer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class FtpServerListener implements ServletContextListener {
public static final String FTPSERVER_CONTEXT_NAME = "org.apache.ftpserver";
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("Stopping FtpServer");
FtpServer server = (FtpServer) sce.getServletContext().getAttribute(FTPSERVER_CONTEXT_NAME);
if(server != null) {
server.stop();
sce.getServletContext().removeAttribute(FTPSERVER_CONTEXT_NAME);
System.out.println("FtpServer stopped");
} else {
System.out.println("No running FtpServer found");
}
}
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Starting FtpServer");
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
FtpServer server = (FtpServer) ctx.getBean("myServer");
sce.getServletContext().setAttribute(FTPSERVER_CONTEXT_NAME, server);
try {
server.start();
System.out.println("FtpServer started");
} catch (Exception e) {
throw new RuntimeException("Failed to start FtpServer", e);
}
}
}
| zzh-simple-hr | Zftp/distribution/org/apache/ftpserver/example/springwar/FtpServerListener.java | Java | art | 2,513 |
package org.apache.ftpserver.example.springwar;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.ftplet.FtpException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestStart {
public static void main(String[] args) throws Exception {
System.out.println("Starting FtpServer");
ApplicationContext ctx = new ClassPathXmlApplicationContext("org/apache/ftpserver/example/springwar/applicationContext.xml");
FtpServer server = (FtpServer) ctx.getBean("myServer");
server.start();
System.out.println("FtpServer started");
}
}
| zzh-simple-hr | Zftp/distribution/org/apache/ftpserver/example/springwar/TestStart.java | Java | art | 746 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* A request for authorization for a specific task, for example write access.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface AuthorizationRequest {
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/AuthorizationRequest.java | Java | art | 1,046 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Ftplet exception class.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpException extends Exception {
private static final long serialVersionUID = -1328383839915898987L;
/**
* Default constructor.
*/
public FtpException() {
super();
}
/**
* Constructs a <code>FtpException</code> object with a message.
*
* @param msg
* a description of the exception
*/
public FtpException(String msg) {
super(msg);
}
/**
* Constructs a <code>FtpException</code> object with a
* <code>Throwable</code> cause.
*
* @param th
* the original cause
*/
public FtpException(Throwable th) {
super(th.getMessage());
}
/**
* Constructs a <code>BaseException</code> object with a
* <code>Throwable</code> cause.
* @param msg A description of the exception
*
* @param th
* The original cause
*/
public FtpException(String msg, Throwable th) {
super(msg);
}
/**
* Get the root cause.
* @return The root cause
* @deprecated Use {@link Exception#getCause()} instead
*/
public Throwable getRootCause() {
return getCause();
}
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpException.java | Java | art | 2,158 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.cert.Certificate;
import java.util.Date;
import java.util.UUID;
/**
* Defines an client session with the FTP server. The session is born when the
* client connects and dies when the client disconnects. Ftplet methods will
* always get the same session for one user and one connection. So the
* attributes set by <code>setAttribute()</code> will be always available later
* unless that attribute is removed or the client disconnects.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpSession {
/**
* Returns the IP address of the client that sent the request.
* @return The client {@link InetAddress}
*/
InetSocketAddress getClientAddress();
/**
* Returns the IP address of the server
* @return The server {@link InetAddress}
*/
InetSocketAddress getServerAddress();
/**
* Get FTP data connection factory, used to transfer data to and from the client.
* @return The {@link DataConnectionFactory}
*/
DataConnectionFactory getDataConnection();
/**
* Retrieve the certificates for the client, if running over SSL and with client authentication
* @return The Certificate chain, or null if the certificates are not avialble
*/
Certificate[] getClientCertificates();
/**
* Get connection time.
* @return Time when the client connected to the server
*/
Date getConnectionTime();
/**
* Get the login time.
* @return Time when the client logged into the server
*/
Date getLoginTime();
/**
* Get the number of failed logins.
* @return The number of failed logins. When login succeeds, this will return 0.
*/
int getFailedLogins();
/**
* Get last access time.
* @return The last time the session performed any action
*/
Date getLastAccessTime();
/**
* Returns maximum idle time. This time equals to
* {@link ConnectionManagerImpl#getDefaultIdleSec()} until user login, and
* {@link User#getMaxIdleTime()} after user login.
* @return The number of seconds the client is allowed to be idle before disconnected.
*/
int getMaxIdleTime();
/**
* Set maximum idle time in seconds. This time equals to
* {@link ConnectionManagerImpl#getDefaultIdleSec()} until user login, and
* {@link User#getMaxIdleTime()} after user login.
* @param maxIdleTimeSec The number of seconds the client is allowed to be idle before disconnected.
*/
void setMaxIdleTime(int maxIdleTimeSec);
/**
* Get user object.
* @return The current {@link User}
*/
User getUser();
/**
* Returns user name entered in USER command
*
* @return user name entered in USER command
*/
String getUserArgument();
/**
* Get the requested language.
* @return The language requested by the client
*/
String getLanguage();
/**
* Is the user logged in?
* @return true if the user is logged in
*/
boolean isLoggedIn();
/**
* Get user file system view.
* @return The {@link FileSystemView} for this session/user
*/
FileSystemView getFileSystemView();
/**
* Get file upload/download offset.
* @return The current file transfer offset, or 0 if non is set
*/
long getFileOffset();
/**
* Get rename from file object.
* @return The current rename from, or null if non is set
*/
FtpFile getRenameFrom();
/**
* Get the data type.
* @return The current {@link DataType} for this session
*/
DataType getDataType();
/**
* Get structure.
* @return The current {@link Structure} for this session
*/
Structure getStructure();
/**
* Returns the value of the named attribute as an Object.
* @param name The attribute name
* @return The attribute value, or null if no
* attribute of the given name exists.
*/
Object getAttribute(String name);
/**
* Stores an attribute in this request. It will be available until it was
* removed or when the connection ends.
* @param name The attribute name
* @param value The attribute value
*/
void setAttribute(String name, Object value);
/**
* Removes an attribute from this request.
* @param name The attribute name
*/
void removeAttribute(String name);
/**
* Write a reply to the client
*
* @param reply
* The reply that will be sent to the client
* @throws FtpException
*/
void write(FtpReply reply) throws FtpException;
/**
* Indicates whether the control socket for this session is secure, that is,
* running over SSL/TLS
*
* @return true if the control socket is secured
*/
boolean isSecure();
/**
* Get the unique ID for this session. This ID will be maintained for
* the entire session and is also available to MDC logging using the "session"
* identifier.
* @return The unique ID for this session
*/
public UUID getSessionId();
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpSession.java | Java | art | 6,071 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Interface for an authority granted to the user, typical example is write
* access or the number of concurrent logins
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface Authority {
/**
* Indicates weather this Authority can authorize a certain request
*
* @param request
* The request to authorize
* @return True if the request can be authorized by this Authority
*/
boolean canAuthorize(AuthorizationRequest request);
/**
* Authorize an {@link AuthorizationRequest}.
*
* @param request
* The {@link AuthorizationRequest}
* @return Returns a populated AuthorizationRequest as long as If
* {@link #canAuthorize(AuthorizationRequest)} returns true for the
* AuthorizationRequest, otherwise returns null.
* {@link #canAuthorize(AuthorizationRequest)} should always be checked before
* calling this method.
*/
AuthorizationRequest authorize(AuthorizationRequest request);
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/Authority.java | Java | art | 1,921 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Interface for a reply to an FTP request.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpReply {
/**
* 110 Restart marker reply. In this case, the text is exact and not left to
* the particular implementation; it must read: MARK yyyy = mmmm Where yyyy
* is User-process data stream marker, and mmmm server's equivalent marker
* (note the spaces between markers and "=").
*/
public static final int REPLY_110_RESTART_MARKER_REPLY = 110;
/**
* 120 Service ready in nnn minutes.
*/
public static final int REPLY_120_SERVICE_READY_IN_NNN_MINUTES = 120;
/**
* 125 Data connection already open; transfer starting.
*/
public static final int REPLY_125_DATA_CONNECTION_ALREADY_OPEN = 125;
/**
* 150 File status okay; about to open data connection.
*/
public static final int REPLY_150_FILE_STATUS_OKAY = 150;
/**
* 200 Command okay.
*/
public static final int REPLY_200_COMMAND_OKAY = 200;
/**
* 202 Command not implemented, superfluous at this site.
*/
public static final int REPLY_202_COMMAND_NOT_IMPLEMENTED = 202;
/**
* 211 System status, or system help reply.
*/
public static final int REPLY_211_SYSTEM_STATUS_REPLY = 211;
/**
* 212 Directory status.
*/
public static final int REPLY_212_DIRECTORY_STATUS = 212;
/**
* 213 File status.
*/
public static final int REPLY_213_FILE_STATUS = 213;
/**
* 214 Help message. On how to use the server or the meaning of a particular
* non-standard command. This reply is useful only to the human user.
*/
public static final int REPLY_214_HELP_MESSAGE = 214;
/**
* 215 NAME system type. Where NAME is an official system name from the list
* in the Assigned Numbers document.
*/
public static final int REPLY_215_NAME_SYSTEM_TYPE = 215;
/**
* 220 Service ready for new user.
*/
public static final int REPLY_220_SERVICE_READY = 220;
/**
* Service closing control connection. Logged out if appropriate.
*/
public static final int REPLY_221_CLOSING_CONTROL_CONNECTION = 221;
/**
* 225 Data connection open; no transfer in progress.
*/
public static final int REPLY_225_DATA_CONNECTION_OPEN_NO_TRANSFER_IN_PROGRESS = 225;
/**
* Closing data connection. Requested file action successful (for example,
* file transfer or file abort).
*/
public static final int REPLY_226_CLOSING_DATA_CONNECTION = 226;
/**
* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
*/
public static final int REPLY_227_ENTERING_PASSIVE_MODE = 227;
/**
* 230 User logged in, proceed.
*/
public static final int REPLY_230_USER_LOGGED_IN = 230;
/**
* 250 Requested file action okay, completed.
*/
public static final int REPLY_250_REQUESTED_FILE_ACTION_OKAY = 250;
/**
* 257 "PATHNAME" created.
*/
public static final int REPLY_257_PATHNAME_CREATED = 257;
/**
* 331 User name okay, need password.
*/
public static final int REPLY_331_USER_NAME_OKAY_NEED_PASSWORD = 331;
/**
* 332 Need account for login.
*/
public static final int REPLY_332_NEED_ACCOUNT_FOR_LOGIN = 332;
/**
* 350 Requested file action pending further information.
*/
public static final int REPLY_350_REQUESTED_FILE_ACTION_PENDING_FURTHER_INFORMATION = 350;
/**
* 421 Service not available, closing control connection. This may be a
* reply to any command if the service knows it must shut down.
*/
public static final int REPLY_421_SERVICE_NOT_AVAILABLE_CLOSING_CONTROL_CONNECTION = 421;
/**
* 425 Can't open data connection.
*/
public static final int REPLY_425_CANT_OPEN_DATA_CONNECTION = 425;
/**
* 426 Connection closed; transfer aborted.
*/
public static final int REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED = 426;
/**
* 450 Requested file action not taken. File unavailable (e.g., file busy).
*/
public static final int REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN = 450;
/**
* 451 Requested action aborted: local error in processing.
*/
public static final int REPLY_451_REQUESTED_ACTION_ABORTED = 451;
/**
* 452 Requested action not taken. Insufficient storage space in system.
*/
public static final int REPLY_452_REQUESTED_ACTION_NOT_TAKEN = 452;
/**
* 500 Syntax error, command unrecognized. This may include errors such as
* command line too long.
*/
public static final int REPLY_500_SYNTAX_ERROR_COMMAND_UNRECOGNIZED = 500;
/**
* 501 Syntax error in parameters or arguments.
*/
public static final int REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS = 501;
/**
* 502 Command not implemented.
*/
public static final int REPLY_502_COMMAND_NOT_IMPLEMENTED = 502;
/**
* 503 Bad sequence of commands.
*/
public static final int REPLY_503_BAD_SEQUENCE_OF_COMMANDS = 503;
/**
* 504 Command not implemented for that parameter.
*/
public static final int REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER = 504;
/**
* 530 Not logged in.
*/
public static final int REPLY_530_NOT_LOGGED_IN = 530;
/**
* 532 Need account for storing files.
*/
public static final int REPLY_532_NEED_ACCOUNT_FOR_STORING_FILES = 532;
/**
* 550 Requested action not taken. File unavailable (e.g., file not found,
* no access).
*/
public static final int REPLY_550_REQUESTED_ACTION_NOT_TAKEN = 550;
/**
* 551 Requested action aborted: page type unknown.
*/
public static final int REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN = 551;
/**
* 552 Requested file action aborted. Exceeded storage allocation (for
* current directory or dataset).
*/
public static final int REPLY_552_REQUESTED_FILE_ACTION_ABORTED_EXCEEDED_STORAGE = 552;
/**
* 553 Requested action not taken. File name not allowed.
*/
public static final int REPLY_553_REQUESTED_ACTION_NOT_TAKEN_FILE_NAME_NOT_ALLOWED = 553;
/**
* The reply code
*
* @return The reply code
*/
int getCode();
/**
* The reply message, might be multiple lines
*
* @return The reply message
*/
String getMessage();
/**
* Must implement toString to format the reply as described in the RFC. Most
* important is the handling of multi-line replies.
*
* @return The formated reply
*/
String toString();
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpReply.java | Java | art | 7,589 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface DataConnection {
/**
* Transfer data from the client (e.g. STOR).
* @param session The current {@link FtpSession}
* @param out
* The {@link OutputStream} containing the destination of the
* data from the client.
* @return The length of the transferred data
* @throws IOException
*/
long transferFromClient(FtpSession session, OutputStream out)
throws IOException;
/**
* Transfer data to the client (e.g. RETR).
* @param session The current {@link FtpSession}
* @param in
* Data to be transfered to the client
* @return The length of the transferred data
* @throws IOException
*/
long transferToClient(FtpSession session, InputStream in)
throws IOException;
/**
* Transfer a string to the client, e.g. during LIST
* @param session The current {@link FtpSession}
* @param str
* The string to transfer
* @throws IOException
*/
void transferToClient(FtpSession session, String str) throws IOException;
} | zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/DataConnection.java | Java | art | 2,128 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* FTP reply object.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpReply implements FtpReply {
private int code;
private String message;
private static final String CRLF = "\r\n";
/**
* Constructor for single-line messages
* @param code The reply code
* @param message The reply message
*/
public DefaultFtpReply(final int code, final String message) {
this.code = code;
this.message = message;
}
/**
* Constructor for multi-line replies
* @param code The reply code
* @param message The reply message, one line per String
*/
public DefaultFtpReply(final int code, final String[] message) {
this.code = code;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < message.length; i++) {
sb.append(message[i]);
sb.append('\n');
}
this.message = sb.toString();
}
/**
* @return the code
*/
public int getCode() {
return code;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
private boolean isDigit(char c) {
return c >= 48 && c <= 57;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
int code = getCode();
String notNullMessage = getMessage();
if (notNullMessage == null) {
notNullMessage = "";
}
StringBuffer sb = new StringBuffer();
// remove any carriage returns
notNullMessage = notNullMessage.replace("\r", "");
// remove trailing line feeds
if(notNullMessage.endsWith("\n")) {
notNullMessage = notNullMessage.substring(0, notNullMessage.length() - 1);
}
String[] lines = notNullMessage.split("\n");
// no newline
if (lines.length == 1) {
sb.append(code);
sb.append(" ");
sb.append(notNullMessage);
sb.append(CRLF);
} else {
sb.append(code);
sb.append("-");
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
if (i + 1 == lines.length) {
sb.append(code);
sb.append(" ");
}
// "If an intermediary line begins with a 3-digit number, the Server
// must pad the front to avoid confusion.
if(i > 0
&& i + 1 < lines.length
&& line.length() > 2
&& isDigit(line.charAt(0))
&& isDigit(line.charAt(1))
&& isDigit(line.charAt(2))
) {
sb.append(" ");
}
sb.append(line);
sb.append(CRLF);
}
}
return sb.toString();
}
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/DefaultFtpReply.java | Java | art | 3,861 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.util.List;
/**
* Basic user interface.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface User {
/**
* Get the user name.
* @return The user name, the same used for login
*/
String getName();
/**
* Get password.
* @return The users password or null if the user manager can not provide the password
*/
String getPassword();
/**
* Get all authorities granted to this user
*
* @return All authorities
*/
List<Authority> getAuthorities();
/**
* Get authorities of the specified type granted to this user
* @param clazz The type of {@link Authority}
* @return Authorities of the specified class
*/
List<Authority> getAuthorities(Class<? extends Authority> clazz);
/**
* Authorize a {@link AuthorizationRequest} for this user
*
* @param request
* The {@link AuthorizationRequest} to authorize
* @return A populated AuthorizationRequest if the user was authorized, null
* otherwise.
*/
AuthorizationRequest authorize(AuthorizationRequest request);
/**
* Get the maximum idle time in seconds. Zero or less idle time means no
* limit.
* @return The idle time in seconds
*/
int getMaxIdleTime();
/**
* Get the user enable status.
* @return true if the user is enabled
*/
boolean getEnabled();
/**
* Get the user home directory
* @return The path to the home directory for the user
*/
String getHomeDirectory();
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/User.java | Java | art | 2,453 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Represents a type of authentication request, typically anonymous or a
* username and password combination
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface Authentication {
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/Authentication.java | Java | art | 1,072 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.io.IOException;
/**
* Default ftplet implementation. All the callback method returns null. It is
* just an empty implementation. You can derive your ftplet implementation from
* this class.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtplet implements Ftplet {
public void init(FtpletContext ftpletContext) throws FtpException {
}
public void destroy() {
}
public FtpletResult onConnect(FtpSession session) throws FtpException,
IOException {
return null;
}
public FtpletResult onDisconnect(FtpSession session) throws FtpException,
IOException {
return null;
}
public FtpletResult beforeCommand(FtpSession session, FtpRequest request)
throws FtpException, IOException {
String command = request.getCommand().toUpperCase();
if ("DELE".equals(command)) {
return onDeleteStart(session, request);
} else if ("STOR".equals(command)) {
return onUploadStart(session, request);
} else if ("RETR".equals(command)) {
return onDownloadStart(session, request);
} else if ("RMD".equals(command)) {
return onRmdirStart(session, request);
} else if ("MKD".equals(command)) {
return onMkdirStart(session, request);
} else if ("APPE".equals(command)) {
return onAppendStart(session, request);
} else if ("STOU".equals(command)) {
return onUploadUniqueStart(session, request);
} else if ("RNTO".equals(command)) {
return onRenameStart(session, request);
} else if ("SITE".equals(command)) {
return onSite(session, request);
} else {
// TODO should we call a catch all?
return null;
}
}
public FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply)
throws FtpException, IOException {
// the reply is ignored for these callbacks
String command = request.getCommand().toUpperCase();
if ("PASS".equals(command)) {
return onLogin(session, request);
} else if ("DELE".equals(command)) {
return onDeleteEnd(session, request);
} else if ("STOR".equals(command)) {
return onUploadEnd(session, request);
} else if ("RETR".equals(command)) {
return onDownloadEnd(session, request);
} else if ("RMD".equals(command)) {
return onRmdirEnd(session, request);
} else if ("MKD".equals(command)) {
return onMkdirEnd(session, request);
} else if ("APPE".equals(command)) {
return onAppendEnd(session, request);
} else if ("STOU".equals(command)) {
return onUploadUniqueEnd(session, request);
} else if ("RNTO".equals(command)) {
return onRenameEnd(session, request);
} else {
// TODO should we call a catch all?
return null;
}
}
/**
* Override this method to intercept user logins
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onLogin(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept deletions
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onDeleteStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to handle deletions after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onDeleteEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept uploads
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to handle uploads after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept downloads
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onDownloadStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to handle downloads after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onDownloadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept deletion of directories
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onRmdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to handle deletion of directories after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onRmdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept creation of directories
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onMkdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to handle creation of directories after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onMkdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept file appends
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onAppendStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept file appends after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onAppendEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept unique uploads
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onUploadUniqueStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
return null;
}
/**
* Override this method to handle unique uploads after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onUploadUniqueEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept renames
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onRenameStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to handle renames after completion
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onRenameEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
/**
* Override this method to intercept SITE commands
* @param session The current {@link FtpSession}
* @param request The current {@link FtpRequest}
* @return The action for the container to take
* @throws FtpException
* @throws IOException
*/
public FtpletResult onSite(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return null;
}
} | zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/DefaultFtplet.java | Java | art | 11,888 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* This is the file abstraction used by the server.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpFile {
/**
* Get the full path from the base directory of the FileSystemView.
* @return a path where the path separator is '/' (even if the operating system
* uses another character as path separator).
*/
String getAbsolutePath();
/**
* Get the file name of the file
* @return the last part of the file path (the part after the last '/').
*/
String getName();
/**
* Is the file hidden?
* @return true if the {@link FtpFile} is hidden
*/
boolean isHidden();
/**
* Is it a directory?
* @return true if the {@link FtpFile} is a directory
*/
boolean isDirectory();
/**
* Is it a file?
* @return true if the {@link FtpFile} is a file, false if it is a directory
*/
boolean isFile();
/**
* Does this file exists?
* @return true if the {@link FtpFile} exists
*/
boolean doesExist();
/**
* Has read permission?
* @return true if the {@link FtpFile} is readable by the user
*/
boolean isReadable();
/**
* Has write permission?
* @return true if the {@link FtpFile} is writable by the user
*/
boolean isWritable();
/**
* Has delete permission?
* @return true if the {@link FtpFile} is removable by the user
*/
boolean isRemovable();
/**
* Get the owner name.
* @return The name of the owner of the {@link FtpFile}
*/
String getOwnerName();
/**
* Get owner group name.
* @return The name of the group that owns the {@link FtpFile}
*/
String getGroupName();
/**
* Get link count.
* @return The number of links for the {@link FtpFile}
*/
int getLinkCount();
/**
* Get last modified time in UTC.
* @return The timestamp of the last modified time for the {@link FtpFile}
*/
long getLastModified();
/**
* Set the last modified time stamp of a file
* @param time The last modified time, in milliseconds since the epoch. See {@link File#setLastModified(long)}.
*/
boolean setLastModified(long time);
/**
* Get file size.
* @return The size of the {@link FtpFile} in bytes
*/
long getSize();
/**
* Create directory.
* @return true if the operation was successful
*/
boolean mkdir();
/**
* Delete file.
* @return true if the operation was successful
*/
boolean delete();
/**
* Move file.
* @param destination The target {@link FtpFile} to move the current {@link FtpFile} to
* @return true if the operation was successful
*/
boolean move(FtpFile destination);
/**
* List file objects. If not a directory or does not exist, null will be
* returned. Files must be returned in alphabetical order.
* List must be immutable.
* @return The {@link List} of {@link FtpFile}s
*/
List<FtpFile> listFiles();
/**
* Create output stream for writing.
* @param offset The number of bytes at where to start writing.
* If the file is not random accessible,
* any offset other than zero will throw an exception.
* @return An {@link OutputStream} used to write to the {@link FtpFile}
* @throws IOException
*/
OutputStream createOutputStream(long offset) throws IOException;
/**
* Create input stream for reading.
* @param offset The number of bytes of where to start reading.
* If the file is not random accessible,
* any offset other than zero will throw an exception.
* @return An {@link InputStream} used to read the {@link FtpFile}
* @throws IOException
*/
InputStream createInputStream(long offset) throws IOException;
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpFile.java | Java | art | 4,919 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* This class encapsulates the return values of the ftplet methods.
*
* DEFAULT < NO_FTPLET < SKIP < DISCONNECT
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public enum FtpletResult {
/**
* This return value indicates that the next ftplet method will be called.
* If no other ftplet is available, the ftpserver will process the request.
*/
DEFAULT,
/**
* This return value indicates that the other ftplet methods will not be
* called but the ftpserver will continue processing this request.
*/
NO_FTPLET,
/**
* It indicates that the ftpserver will skip everything. No further
* processing (both ftplet and server) will be done for this request.
*/
SKIP,
/**
* It indicates that the server will skip and disconnect the client. No
* other request from the same client will be served.
*/
DISCONNECT;
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpletResult.java | Java | art | 1,778 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.io.IOException;
/**
* Defines methods that all ftplets must implement.
*
* A ftplet is a small Java program that runs within an FTP server. Ftplets
* receive and respond to requests from FTP clients.
*
* This interface defines methods to initialize a ftplet, to service requests,
* and to remove a ftplet from the server. These are known as life-cycle methods
* and are called in the following sequence:
*
* <ol>
* <li>The ftplet is constructed.</li>
* <li>Then initialized with the init method.</li>
* <li>All the callback methods will be invoked.</li>
* <li>The ftplet is taken out of service, then destroyed with the destroy
* method.</li>
* <li>Then garbage collected and finalized.</li>
* </ol>
*
* All the callback methods return FtpletEnum. If it returns null
* FtpletEnum.DEFAULT will be assumed. If any ftplet callback method throws
* exception, that particular connection will be disconnected.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface Ftplet {
/**
* Called by the ftplet container to indicate to a ftplet that the ftplet is
* being placed into service. The ftplet container calls the init method
* exactly once after instantiating the ftplet. The init method must
* complete successfully before the ftplet can receive any requests.
* @param ftpletContext The current {@link FtpletContext}
* @throws FtpException
*/
void init(FtpletContext ftpletContext) throws FtpException;
/**
* Called by the Ftplet container to indicate to a ftplet that the ftplet is
* being taken out of service. This method is only called once all threads
* within the ftplet's service method have exited. After the ftplet
* container calls this method, callback methods will not be executed. If
* the ftplet initialization method fails, this method will not be called.
*/
void destroy();
/**
* Called by the ftplet container before a command is executed by the
* server. The implementation should return based on the desired action to
* be taken by the server:
* <ul>
* <li>{@link FtpletResult#DEFAULT}: The server continues as normal and
* executes the command</li>
* <li>{@link FtpletResult#NO_FTPLET}: The server does not call any more
* Ftplets before this command but continues execution of the command as
* usual</li>
* <li>{@link FtpletResult#SKIP}: The server skips over execution of the
* command. Note that the Ftplet is responsible for returning the
* appropriate reply to the client, or the client might deadlock.</li>
* <li>{@link FtpletResult#DISCONNECT}: The server will immediately
* disconnect the client.</li>
* <li>Ftplet throws exception: Same as {@link FtpletResult#DISCONNECT}</li>
* </ul>
*
* @param session
* The current session
* @param request
* The current request
* @return The desired action to be performed by the server
* @throws FtpException
* @throws IOException
*/
FtpletResult beforeCommand(FtpSession session, FtpRequest request)
throws FtpException, IOException;
/**
* Called by the ftplet container after a command has been executed by the
* server. The implementation should return based on the desired action to
* be taken by the server:
* <ul>
* <li>{@link FtpletResult#DEFAULT}: The server continues as normal</li>
* <li>{@link FtpletResult#NO_FTPLET}: The server does not call any more
* Ftplets before this command but continues as normal</li>
* <li>{@link FtpletResult#SKIP}: Same as {@link FtpletResult#DEFAULT}</li>
* <li>{@link FtpletResult#DISCONNECT}: The server will immediately
* disconnect the client.</li>
* <li>Ftplet throws exception: Same as {@link FtpletResult#DISCONNECT}</li>
* </ul>
*
* @param session
* The current session
* @param request
* The current request
* @param reply
* the reply that was sent for this command. Implementations can
* use this to check the reply code and thus determine if the
* command was successfully processed or not.
* @return The desired action to be performed by the server
* @throws FtpException
* @throws IOException
*/
FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply)
throws FtpException, IOException;
/**
* Client connect notification method.
* @param session The current {@link FtpSession}
* @return The desired action to be performed by the server
* @throws FtpException
* @throws IOException
*/
FtpletResult onConnect(FtpSession session) throws FtpException, IOException;
/**
* Client disconnect notification method. This is the last callback method.
* @param session The current {@link FtpSession}
* @return The desired action to be performed by the server
* @throws FtpException
* @throws IOException
*/
FtpletResult onDisconnect(FtpSession session) throws FtpException,
IOException;
} | zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/Ftplet.java | Java | art | 6,014 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.net.InetAddress;
import java.util.Date;
/**
* This interface holds all the ftp server statistical information.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpStatistics {
/**
* Get the server start time.
* @return The {@link Date} when the server started
*/
Date getStartTime();
/**
* Get number of files uploaded.
* @return The total number of uploads
*/
int getTotalUploadNumber();
/**
* Get number of files downloaded.
* @return The total number of downloads
*/
int getTotalDownloadNumber();
/**
* Get number of files deleted.
* @return The total number of deletions
*/
int getTotalDeleteNumber();
/**
* Get total number of bytes uploaded.
* @return The total number of bytes uploaded
*/
long getTotalUploadSize();
/**
* Get total number of bytes downloaded.
* @return The total number of bytes downloaded
*/
long getTotalDownloadSize();
/**
* Get total directory created.
* @return The total number of created directories
*/
int getTotalDirectoryCreated();
/**
* Get total directory removed.
* @return The total number of removed directories
*/
int getTotalDirectoryRemoved();
/**
* Get total number of connections
* @return The total number of connections
*/
int getTotalConnectionNumber();
/**
* Get current number of connections.
* @return The current number of connections
*/
int getCurrentConnectionNumber();
/**
* Get total login number.
* @return The total number of logins
*/
int getTotalLoginNumber();
/**
* Get total failed login number.
* @return The total number of failed logins
*/
int getTotalFailedLoginNumber();
/**
* Get current login number
* @return The current number of logins
*/
int getCurrentLoginNumber();
/**
* Get total anonymous login number.
* @return The total number of anonymous logins
*/
int getTotalAnonymousLoginNumber();
/**
* Get current anonymous login number.
* @return The current number of anonymous logins
*/
int getCurrentAnonymousLoginNumber();
/**
* Get the login number for the specific user
* @param user The {@link User} for which to retrieve the number of logins
* @return The total number of logins for the provided user
*/
int getCurrentUserLoginNumber(User user);
/**
* Get the login number for the specific user from the ipAddress
*
* @param user
* login user account
* @param ipAddress
* the ip address of the remote user
* @return The total number of logins for the provided user and IP address
*/
int getCurrentUserLoginNumber(User user, InetAddress ipAddress);
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpStatistics.java | Java | art | 3,792 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* This is an abstraction over the user file system view.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FileSystemView {
/**
* Get the user home directory.
* @return The {@link FtpFile} for the users home directory
* @throws FtpException
*/
FtpFile getHomeDirectory() throws FtpException;
/**
* Get user current directory.
* @return The {@link FtpFile} for the users current directory
* @throws FtpException
*/
FtpFile getWorkingDirectory() throws FtpException;
/**
* Change directory.
* @param dir The path of the directory to set as the current directory for the user
* @return true if successful
* @throws FtpException
*/
boolean changeWorkingDirectory(String dir) throws FtpException;
/**
* Get file object.
* @param file The path to the file to get
* @return The {@link FtpFile} for the provided path
* @throws FtpException
*/
FtpFile getFile(String file) throws FtpException;
/**
* Does the file system support random file access?
* @return true if the file supports random access
* @throws FtpException
*/
boolean isRandomAccessible() throws FtpException;
/**
* Dispose file system view.
*/
void dispose();
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FileSystemView.java | Java | art | 2,191 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* A ftplet configuration object used by a ftplet container used to pass
* information to a ftplet during initialization. The configuration information
* contains initialization parameters.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpletContext {
/**
* Get the user manager.
* @return The {@link UserManager}
*/
UserManager getUserManager();
/**
* Get file system manager
* @return The {@link FileSystemFactory}
*/
FileSystemFactory getFileSystemManager();
/**
* Get ftp statistics.
* @return The {@link FtpStatistics}
*/
FtpStatistics getFtpStatistics();
/**
* Get Ftplet.
* @param name The name identifying the {@link Ftplet}
* @return The {@link Ftplet} registred with the provided name, or null if none exists
*/
Ftplet getFtplet(String name);
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpletContext.java | Java | art | 1,754 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Thrown if an authentication request fails
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class AuthenticationFailedException extends FtpException {
private static final long serialVersionUID = -1328383839915898987L;
/**
* Default constructor.
*/
public AuthenticationFailedException() {
super();
}
/**
* Constructs a <code>AuthenticationFailedException</code> object with a
* message.
*
* @param msg
* A description of the exception
*/
public AuthenticationFailedException(String msg) {
super(msg);
}
/**
* Constructs a <code>AuthenticationFailedException</code> object with a
* <code>Throwable</code> cause.
*
* @param th
* The original cause
*/
public AuthenticationFailedException(Throwable th) {
super(th);
}
/**
* Constructs a <code>AuthenticationFailedException</code> object with a
* <code>Throwable</code> cause.
* @param msg A description of the exception
*
* @param th
* The original cause
*/
public AuthenticationFailedException(String msg, Throwable th) {
super(msg, th);
}
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/AuthenticationFailedException.java | Java | art | 2,105 |