code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
/**
* Abstract HTTP message writer for non-blocking connections.
*
* @since 4.0
*/
public interface NHttpMessageWriter<T extends HttpMessage> {
/**
* Resets the writer. The writer will be ready to start serializing another
* HTTP message.
*/
void reset();
/**
* Serializes out the HTTP message head.
*
* @param message HTTP message.
* @throws IOException in case of an I/O error.
* @throws HttpException in case the HTTP message is malformed or
* violates the HTTP protocol.
*/
void write(T message) throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
/**
* Abstract client-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpClientHandler {
/**
* Triggered when a new outgoing connection is created.
*
* @param conn new outgoing HTTP connection.
* @param attachment an object that was attached to the session request
*/
void connected(NHttpClientConnection conn, Object attachment);
/**
* Triggered when the connection is ready to accept a new HTTP request.
* The protocol handler does not have to submit a request if it is not
* ready.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that is ready to accept a new HTTP request.
*/
void requestReady(NHttpClientConnection conn);
/**
* Triggered when an HTTP response is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP response object.
* <p/>
* If the response received encloses a response entity this method will
* be followed by a series of
* {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls
* to transfer the response content.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReceived(NHttpClientConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the response entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming response content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpClientConnection conn, ContentDecoder decoder);
/**
* Triggered when the underlying channel is ready for writing a next portion
* of the request entity through the corresponding content encoder.
* <p>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing request content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpClientConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpClientConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP response.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpClientConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpClientConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpClientConnection conn);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
/**
* Connection input/output control interface. It can be used to control interest
* in I/O event notifications for non-blocking HTTP connections.
* <p>
* Implementations of this interface are expected to be threading safe.
* Therefore it can be used to request / suspend I/O event notifications from
* any thread of execution.
*
* @since 4.0
*/
public interface IOControl {
/**
* Requests event notifications to be triggered when the underlying
* channel is ready for input operations.
*/
void requestInput();
/**
* Suspends event notifications about the underlying channel being
* ready for input operations.
*/
void suspendInput();
/**
* Requests event notifications to be triggered when the underlying
* channel is ready for output operations.
*/
void requestOutput();
/**
* Suspends event notifications about the underlying channel being
* ready for output operations.
*/
void suspendOutput();
/**
* Shuts down the underlying channel.
*
* @throws IOException
*/
void shutdown() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.params;
/**
* Parameter names for I/O reactors.
*
* @since 4.0
*/
public interface NIOReactorPNames {
/**
* Determines the size of the content input/output buffers used
* to buffer data while receiving or transmitting HTTP messages.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String CONTENT_BUFFER_SIZE = "http.nio.content-buffer-size";
/**
* Determines the time interval in milliseconds at which the
* I/O reactor wakes up to check for timed out sessions and session requests.
* <p>
* This parameter expects a value of type {@link Long}.
* </p>
*/
public static final String SELECT_INTERVAL = "http.nio.select-interval";
/**
* Determines the grace period the I/O reactors are expected to block
* waiting for individual worker threads to terminate cleanly.
* <p>
* This parameter expects a value of type {@link Long}.
* </p>
*/
public static final String GRACE_PERIOD = "http.nio.grace-period";
/**
* Determines whether interestOps() queueing is enabled for the I/O reactors.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*
* @since 4.1
*/
public static final String INTEREST_OPS_QUEUEING = "http.nio.interest-ops-queueing";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.params;
import org.apache.http.params.HttpParams;
/**
* Utility class for accessing I/O reactor parameters in {@link HttpParams}.
*
* @since 4.0
*
* @see NIOReactorPNames
*/
public final class NIOReactorParams implements NIOReactorPNames {
private NIOReactorParams() {
super();
}
/**
* Obtains the value of {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter.
* If not set, defaults to <code>4096</code>.
*
* @param params HTTP parameters.
* @return content buffer size.
*/
public static int getContentBufferSize(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter(CONTENT_BUFFER_SIZE, 4096);
}
/**
* Sets value of the {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter.
*
* @param params HTTP parameters.
* @param size content buffer size.
*/
public static void setContentBufferSize(final HttpParams params, int size) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter(CONTENT_BUFFER_SIZE, size);
}
/**
* Obtains the value of {@link NIOReactorPNames#SELECT_INTERVAL} parameter.
* If not set, defaults to <code>1000</code>.
*
* @param params HTTP parameters.
* @return I/O select interval in milliseconds.
*/
public static long getSelectInterval(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(SELECT_INTERVAL, 1000);
}
/**
* Sets value of the {@link NIOReactorPNames#SELECT_INTERVAL} parameter.
*
* @param params HTTP parameters.
* @param ms I/O select interval in milliseconds.
*/
public static void setSelectInterval(final HttpParams params, long ms) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(SELECT_INTERVAL, ms);
}
/**
* Obtains the value of {@link NIOReactorPNames#GRACE_PERIOD} parameter.
* If not set, defaults to <code>500</code>.
*
* @param params HTTP parameters.
* @return shutdown grace period in milliseconds.
*/
public static long getGracePeriod(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(GRACE_PERIOD, 500);
}
/**
* Sets value of the {@link NIOReactorPNames#GRACE_PERIOD} parameter.
*
* @param params HTTP parameters.
* @param ms shutdown grace period in milliseconds.
*/
public static void setGracePeriod(final HttpParams params, long ms) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(GRACE_PERIOD, ms);
}
/**
* Obtains the value of {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter.
* If not set, defaults to <code>false</code>.
*
* @param params HTTP parameters.
* @return interest ops queuing flag.
*
* @since 4.1
*/
public static boolean getInterestOpsQueueing(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter(INTEREST_OPS_QUEUEING, false);
}
/**
* Sets value of the {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter.
*
* @param params HTTP parameters.
* @param interestOpsQueueing interest ops queuing.
*
* @since 4.1
*/
public static void setInterestOpsQueueing(
final HttpParams params, boolean interestOpsQueueing) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter(INTEREST_OPS_QUEUEING, interestOpsQueueing);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.params;
import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams;
/**
* @since 4.0
*/
public class NIOReactorParamBean extends HttpAbstractParamBean {
public NIOReactorParamBean (final HttpParams params) {
super(params);
}
public void setContentBufferSize (int contentBufferSize) {
NIOReactorParams.setContentBufferSize(params, contentBufferSize);
}
public void setSelectInterval (long selectInterval) {
NIOReactorParams.setSelectInterval(params, selectInterval);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.nio.ContentEncoder;
/**
* A {@link WritableByteChannel} that delegates to a {@link ContentEncoder}.
* Attempts to close this channel are ignored, and {@link #isOpen} always
* returns <code>true</code>.
*
* @since 4.0
*/
public class ContentEncoderChannel implements WritableByteChannel {
private final ContentEncoder contentEncoder;
public ContentEncoderChannel(ContentEncoder contentEncoder) {
this.contentEncoder = contentEncoder;
}
public int write(ByteBuffer src) throws IOException {
return contentEncoder.write(src);
}
public void close() {}
public boolean isOpen() {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpClientConnection} used by
* {@link IOEventDispatch} implementations to inform client-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpClientIOTarget extends NHttpClientConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the client protocol handler.
*/
void consumeInput(NHttpClientHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the client protocol handler.
*/
void produceOutput(NHttpClientHandler handler);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* A content decoder capable of transferring data directly to a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentDecoder extends ContentDecoder {
/**
* Transfers a portion of entity content from the underlying network channel
* into the given file channel.<br>
*
* <b>Warning</b>: Many implementations cannot write beyond the length of the file.
* If the position exceeds the channel's size, some implementations
* may throw an IOException.
*
* @param dst the target FileChannel to transfer data into.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative.
* <b>Must be less than or equal to the size of the file</b>
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
* @throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel dst, long position, long count) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstract HTTP content decoder. HTTP content decoders can be used
* to read entity content from the underlying channel in small
* chunks and apply the required coding transformation.
*
* @since 4.0
*/
public interface ContentDecoder {
/**
* Reads a portion of content from the underlying channel
*
* @param dst The buffer into which entity content is to be transferred
* @return The number of bytes read, possibly zero, or -1 if the
* channel has reached end-of-stream
* @throws IOException if I/O error occurs while reading content
*/
int read(ByteBuffer dst) throws IOException;
/**
* Returns <code>true</code> if the entity has been received in its
* entirety.
*
* @return <code>true</code> if all the content has been consumed,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstract HTTP content encoder. HTTP content encoders can be used
* to apply the required coding transformation and write entity
* content to the underlying channel in small chunks.
*
* @since 4.0
*/
public interface ContentEncoder {
/**
* Writes a portion of entity content to the underlying channel.
*
* @param src The buffer from which content is to be retrieved
* @return The number of bytes read, possibly zero
* @throws IOException if I/O error occurs while writing content
*/
int write(ByteBuffer src) throws IOException;
/**
* Terminates the content stream.
*
* @throws IOException if I/O error occurs while writing content
*/
void complete() throws IOException;
/**
* Returns <code>true</code> if the entity has been transferred in its
* entirety.
*
* @return <code>true</code> if all the content has been produced,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentEncoder;
/**
* Buffer for storing content to be streamed out to a {@link ContentEncoder}.
*
* @since 4.0
*/
public interface ContentOutputBuffer {
/**
* Writes content from this buffer to the given {@link ContentEncoder}.
*
* @param encoder content encoder.
* @return number of bytes written.
* @throws IOException in case of an I/O error.
*/
int produceContent(ContentEncoder encoder) throws IOException;
/**
* Resets the buffer by clearing its state and stored content.
*/
void reset();
/**
* @deprecated No longer used.
*/
@Deprecated
void flush() throws IOException;
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this buffer.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, this method can throw a runtime exception. The exact type
* of runtime exception thrown by this method depends on implementation.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b, int off, int len) throws IOException;
/**
* Writes the specified byte to this buffer.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/**
* Indicates the content has been fully written.
* @exception IOException if an I/O error occurs.
*/
void writeCompleted() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* Implementation of the {@link ContentInputBuffer} interface that can be
* shared by multiple threads, usually the I/O dispatch of an I/O reactor and
* a worker thread.
* <p>
* The I/O dispatch thread is expect to transfer data from {@link ContentDecoder} to the buffer
* by calling {@link #consumeContent(ContentDecoder)}.
* <p>
* The worker thread is expected to read the data from the buffer by calling
* {@link #read()} or {@link #read(byte[], int, int)} methods.
* <p>
* In case of an abnormal situation or when no longer needed the buffer must be shut down
* using {@link #shutdown()} method.
*
* @since 4.0
*/
public class SharedInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
private final IOControl ioctrl;
private final ReentrantLock lock;
private final Condition condition;
private volatile boolean shutdown = false;
private volatile boolean endOfStream = false;
public SharedInputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
if (ioctrl == null) {
throw new IllegalArgumentException("I/O content control may not be null");
}
this.ioctrl = ioctrl;
this.lock = new ReentrantLock();
this.condition = this.lock.newCondition();
}
public void reset() {
if (this.shutdown) {
return;
}
this.lock.lock();
try {
clear();
this.endOfStream = false;
} finally {
this.lock.unlock();
}
}
public int consumeContent(final ContentDecoder decoder) throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
setInputMode();
int totalRead = 0;
int bytesRead;
while ((bytesRead = decoder.read(this.buffer)) > 0) {
totalRead += bytesRead;
}
if (bytesRead == -1 || decoder.isCompleted()) {
this.endOfStream = true;
}
if (!this.buffer.hasRemaining()) {
this.ioctrl.suspendInput();
}
this.condition.signalAll();
if (totalRead > 0) {
return totalRead;
} else {
if (this.endOfStream) {
return -1;
} else {
return 0;
}
}
} finally {
this.lock.unlock();
}
}
@Override
public boolean hasData() {
this.lock.lock();
try {
return super.hasData();
} finally {
this.lock.unlock();
}
}
@Override
public int available() {
this.lock.lock();
try {
return super.available();
} finally {
this.lock.unlock();
}
}
@Override
public int capacity() {
this.lock.lock();
try {
return super.capacity();
} finally {
this.lock.unlock();
}
}
@Override
public int length() {
this.lock.lock();
try {
return super.length();
} finally {
this.lock.unlock();
}
}
protected void waitForData() throws IOException {
this.lock.lock();
try {
try {
while (!super.hasData() && !this.endOfStream) {
if (this.shutdown) {
throw new InterruptedIOException("Input operation aborted");
}
this.ioctrl.requestInput();
this.condition.await();
}
} catch (InterruptedException ex) {
throw new IOException("Interrupted while waiting for more data");
}
} finally {
this.lock.unlock();
}
}
public void close() {
if (this.shutdown) {
return;
}
this.endOfStream = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
protected boolean isShutdown() {
return this.shutdown;
}
protected boolean isEndOfStream() {
return this.shutdown || (!hasData() && this.endOfStream);
}
public int read() throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
if (!hasData()) {
waitForData();
}
if (isEndOfStream()) {
return -1;
}
return this.buffer.get() & 0xff;
} finally {
this.lock.unlock();
}
}
public int read(final byte[] b, int off, int len) throws IOException {
if (this.shutdown) {
return -1;
}
if (b == null) {
return 0;
}
this.lock.lock();
try {
if (!hasData()) {
waitForData();
}
if (isEndOfStream()) {
return -1;
}
setOutputMode();
int chunk = len;
if (chunk > this.buffer.remaining()) {
chunk = this.buffer.remaining();
}
this.buffer.get(b, off, chunk);
return chunk;
} finally {
this.lock.unlock();
}
}
public int read(final byte[] b) throws IOException {
if (this.shutdown) {
return -1;
}
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Allocates {@link ByteBuffer} instances using
* {@link ByteBuffer#allocate(int)}.
*
* @since 4.0
*/
public class HeapByteBufferAllocator implements ByteBufferAllocator {
public ByteBuffer allocate(int size) {
return ByteBuffer.allocate(size);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Allocates {@link ByteBuffer} instances using
* {@link ByteBuffer#allocateDirect(int)}.
*
* @since 4.0
*/
public class DirectByteBufferAllocator implements ByteBufferAllocator {
public ByteBuffer allocate(int size) {
return ByteBuffer.allocateDirect(size);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Abstract interface to allocate {@link ByteBuffer} instances.
*
* @since 4.0
*/
public interface ByteBufferAllocator {
/**
* Allocates {@link ByteBuffer} of the given size.
*
* @param size the size of the buffer.
* @return byte buffer.
*/
ByteBuffer allocate(int size);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentEncoder;
/**
* Basic implementation of the {@link ContentOutputBuffer} interface.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
public class SimpleOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
private boolean endOfStream;
public SimpleOutputBuffer(int buffersize, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
this.endOfStream = false;
}
public int produceContent(final ContentEncoder encoder) throws IOException {
setOutputMode();
int bytesWritten = encoder.write(this.buffer);
if (!hasData() && this.endOfStream) {
encoder.complete();
}
return bytesWritten;
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
if (this.endOfStream) {
return;
}
setInputMode();
ensureCapacity(this.buffer.position() + len);
this.buffer.put(b, off, len);
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
if (this.endOfStream) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.endOfStream) {
return;
}
setInputMode();
ensureCapacity(this.capacity() + 1);
this.buffer.put((byte)b);
}
public void reset() {
super.clear();
this.endOfStream = false;
}
public void flush() {
}
public void writeCompleted() {
this.endOfStream = true;
}
public void shutdown() {
this.endOfStream = true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
/**
* Basic buffer properties.
*
* @since 4.0
*
* @deprecated Use {@link org.apache.http.io.BufferInfo}
*/
@Deprecated
public interface BufferInfo {
int length();
int capacity();
int available();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* Implementation of the {@link ContentOutputBuffer} interface that can be
* shared by multiple threads, usually the I/O dispatch of an I/O reactor and
* a worker thread.
* <p>
* The I/O dispatch thread is expected to transfer data from the buffer to
* {@link ContentEncoder} by calling {@link #produceContent(ContentEncoder)}.
* <p>
* The worker thread is expected to write data to the buffer by calling
* {@link #write(int)}, {@link #write(byte[], int, int)} or {@link #writeCompleted()}
* <p>
* In case of an abnormal situation or when no longer needed the buffer must be
* shut down using {@link #shutdown()} method.
*
* @since 4.0
*/
public class SharedOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
private final IOControl ioctrl;
private final ReentrantLock lock;
private final Condition condition;
private volatile boolean shutdown = false;
private volatile boolean endOfStream = false;
public SharedOutputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
if (ioctrl == null) {
throw new IllegalArgumentException("I/O content control may not be null");
}
this.ioctrl = ioctrl;
this.lock = new ReentrantLock();
this.condition = this.lock.newCondition();
}
public void reset() {
if (this.shutdown) {
return;
}
this.lock.lock();
try {
clear();
this.endOfStream = false;
} finally {
this.lock.unlock();
}
}
@Override
public boolean hasData() {
this.lock.lock();
try {
return super.hasData();
} finally {
this.lock.unlock();
}
}
@Override
public int available() {
this.lock.lock();
try {
return super.available();
} finally {
this.lock.unlock();
}
}
@Override
public int capacity() {
this.lock.lock();
try {
return super.capacity();
} finally {
this.lock.unlock();
}
}
@Override
public int length() {
this.lock.lock();
try {
return super.length();
} finally {
this.lock.unlock();
}
}
public int produceContent(final ContentEncoder encoder) throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
setOutputMode();
int bytesWritten = 0;
if (super.hasData()) {
bytesWritten = encoder.write(this.buffer);
if (encoder.isCompleted()) {
this.endOfStream = true;
}
}
if (!super.hasData()) {
// No more buffered content
// If at the end of the stream, terminate
if (this.endOfStream && !encoder.isCompleted()) {
encoder.complete();
}
if (!this.endOfStream) {
// suspend output events
this.ioctrl.suspendOutput();
}
}
this.condition.signalAll();
return bytesWritten;
} finally {
this.lock.unlock();
}
}
public void close() {
shutdown();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
this.lock.lock();
try {
if (this.shutdown || this.endOfStream) {
throw new IllegalStateException("Buffer already closed for writing");
}
setInputMode();
int remaining = len;
while (remaining > 0) {
if (!this.buffer.hasRemaining()) {
flushContent();
setInputMode();
}
int chunk = Math.min(remaining, this.buffer.remaining());
this.buffer.put(b, off, chunk);
remaining -= chunk;
off += chunk;
}
} finally {
this.lock.unlock();
}
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
this.lock.lock();
try {
if (this.shutdown || this.endOfStream) {
throw new IllegalStateException("Buffer already closed for writing");
}
setInputMode();
if (!this.buffer.hasRemaining()) {
flushContent();
setInputMode();
}
this.buffer.put((byte)b);
} finally {
this.lock.unlock();
}
}
public void flush() throws IOException {
}
private void flushContent() throws IOException {
this.lock.lock();
try {
try {
while (super.hasData()) {
if (this.shutdown) {
throw new InterruptedIOException("Output operation aborted");
}
this.ioctrl.requestOutput();
this.condition.await();
}
} catch (InterruptedException ex) {
throw new IOException("Interrupted while flushing the content buffer");
}
} finally {
this.lock.unlock();
}
}
public void writeCompleted() throws IOException {
this.lock.lock();
try {
if (this.endOfStream) {
return;
}
this.endOfStream = true;
this.ioctrl.requestOutput();
} finally {
this.lock.unlock();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
import org.apache.http.io.BufferInfo;
/**
* A buffer that expand its capacity on demand using {@link ByteBufferAllocator}
* interface. Internally, this class is backed by an instance of
* {@link ByteBuffer}.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
public class ExpandableBuffer implements BufferInfo, org.apache.http.nio.util.BufferInfo {
public final static int INPUT_MODE = 0;
public final static int OUTPUT_MODE = 1;
private int mode;
protected ByteBuffer buffer = null;
private final ByteBufferAllocator allocator;
/**
* Allocates buffer of the given size using the given allocator.
*
* @param buffersize the buffer size.
* @param allocator allocator to be used to allocate {@link ByteBuffer}s.
*/
public ExpandableBuffer(int buffersize, final ByteBufferAllocator allocator) {
super();
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
this.allocator = allocator;
this.buffer = allocator.allocate(buffersize);
this.mode = INPUT_MODE;
}
/**
* Returns the current mode:
* <p>
* {@link #INPUT_MODE}: the buffer is in the input mode.
* <p>
* {@link #OUTPUT_MODE}: the buffer is in the output mode.
*
* @return current input/output mode.
*/
protected int getMode() {
return this.mode;
}
/**
* Sets output mode. The buffer can now be read from.
*/
protected void setOutputMode() {
if (this.mode != OUTPUT_MODE) {
this.buffer.flip();
this.mode = OUTPUT_MODE;
}
}
/**
* Sets input mode. The buffer can now be written into.
*/
protected void setInputMode() {
if (this.mode != INPUT_MODE) {
if (this.buffer.hasRemaining()) {
this.buffer.compact();
} else {
this.buffer.clear();
}
this.mode = INPUT_MODE;
}
}
private void expandCapacity(int capacity) {
ByteBuffer oldbuffer = this.buffer;
this.buffer = allocator.allocate(capacity);
oldbuffer.flip();
this.buffer.put(oldbuffer);
}
/**
* Expands buffer's capacity.
*/
protected void expand() {
int newcapacity = (this.buffer.capacity() + 1) << 1;
if (newcapacity < 0) {
newcapacity = Integer.MAX_VALUE;
}
expandCapacity(newcapacity);
}
/**
* Ensures the buffer can accommodate the required capacity.
*
* @param requiredCapacity
*/
protected void ensureCapacity(int requiredCapacity) {
if (requiredCapacity > this.buffer.capacity()) {
expandCapacity(requiredCapacity);
}
}
/**
* Returns the total capacity of this buffer.
*
* @return total capacity.
*/
public int capacity() {
return this.buffer.capacity();
}
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
public boolean hasData() {
setOutputMode();
return this.buffer.hasRemaining();
}
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
public int length() {
setOutputMode();
return this.buffer.remaining();
}
/**
* Returns available capacity of this buffer.
*
* @return buffer length.
*/
public int available() {
setInputMode();
return this.buffer.remaining();
}
/**
* Clears buffer.
*/
protected void clear() {
this.buffer.clear();
this.mode = INPUT_MODE;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[mode=");
int mode = getMode();
if (mode == INPUT_MODE) {
sb.append("in");
} else {
sb.append("out");
}
sb.append(" pos=");
sb.append(this.buffer.position());
sb.append(" lim=");
sb.append(this.buffer.limit());
sb.append(" cap=");
sb.append(this.buffer.capacity());
sb.append("]");
return sb.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
/**
* Buffer for storing content streamed out from a {@link ContentDecoder}.
*
* @since 4.0
*/
public interface ContentInputBuffer {
/**
* Reads content from the given {@link ContentDecoder} and stores it in
* this buffer.
*
* @param decoder the content decoder.
* @return number of bytes read.
* @throws IOException in case of an I/O error.
*/
int consumeContent(ContentDecoder decoder) throws IOException;
/**
* Resets the buffer by clearing its state and stored content.
*/
void reset();
/**
* Reads up to <code>len</code> bytes of data from this buffer into
* an array of bytes. The exact number of bytes read depends how many bytes
* are stored in the buffer.
*
* <p> If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, this method can throw a runtime exception. The exact type
* of runtime exception thrown by this method depends on implementation.
* This method returns <code>-1</code> if the end of content stream has been
* reached.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Reads one byte from this buffer. If the buffer is empty this method can
* throw a runtime exception. The exact type of runtime exception thrown
* by this method depends on implementation. This method returns
* <code>-1</code> if the end of content stream has been reached.
*
* @return one byte
*/
int read() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
/**
* Basic implementation of the {@link ContentInputBuffer} interface.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
public class SimpleInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
private boolean endOfStream = false;
public SimpleInputBuffer(int buffersize, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
}
public void reset() {
this.endOfStream = false;
super.clear();
}
public int consumeContent(final ContentDecoder decoder) throws IOException {
setInputMode();
int totalRead = 0;
int bytesRead;
while ((bytesRead = decoder.read(this.buffer)) != -1) {
if (bytesRead == 0) {
if (!this.buffer.hasRemaining()) {
expand();
} else {
break;
}
} else {
totalRead += bytesRead;
}
}
if (bytesRead == -1 || decoder.isCompleted()) {
this.endOfStream = true;
}
return totalRead;
}
public boolean isEndOfStream() {
return !hasData() && this.endOfStream;
}
public int read() throws IOException {
if (isEndOfStream()) {
return -1;
}
return this.buffer.get() & 0xff;
}
public int read(final byte[] b, int off, int len) throws IOException {
if (isEndOfStream()) {
return -1;
}
if (b == null) {
return 0;
}
setOutputMode();
int chunk = len;
if (chunk > this.buffer.remaining()) {
chunk = this.buffer.remaining();
}
this.buffer.get(b, off, chunk);
return chunk;
}
public int read(final byte[] b) throws IOException {
if (isEndOfStream()) {
return -1;
}
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
public void shutdown() {
this.endOfStream = true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
/**
* Abstract non-blocking client-side HTTP connection interface. It can be used
* to submit HTTP requests and asynchronously receive HTTP responses.
*
* @see NHttpConnection
*
* @since 4.0
*/
public interface NHttpClientConnection extends NHttpConnection {
/**
* Submits {@link HttpRequest} to be sent to the target server.
*
* @param request HTTP request
* @throws IOException if I/O error occurs while submitting the request
* @throws HttpException if the HTTP request violates the HTTP protocol.
*/
void submitRequest(HttpRequest request) throws IOException, HttpException;
/**
* Returns <code>true</code> if an HTTP request has been submitted to the
* target server.
*
* @return <code>true</code> if an HTTP request has been submitted,
* <code>false</code> otherwise.
*/
boolean isRequestSubmitted();
/**
* Resets output state. This method can be used to prematurely terminate
* processing of the outgoing HTTP request.
*/
void resetOutput();
/**
* Resets input state. This method can be used to prematurely terminate
* processing of the incoming HTTP response.
*/
void resetInput();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.nio.channels.SelectionKey;
/**
* Helper class, representing an entry on an {@link java.nio.channels.SelectionKey#interestOps(int)
* interestOps(int)} queue.
*
* @since 4.1
*/
class InterestOpEntry {
private final SelectionKey key;
private final int eventMask;
public InterestOpEntry(final SelectionKey key, int eventMask) {
super();
if (key == null) {
throw new IllegalArgumentException("Selection key may not be null");
}
this.key = key;
this.eventMask = eventMask;
}
public SelectionKey getSelectionKey() {
return this.key;
}
public int getEventMask() {
return this.eventMask;
}
@Override
public boolean equals(Object obj) {
return this.key.equals(obj);
}
@Override
public int hashCode() {
return this.key.hashCode();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.nio.channels.Channel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.params.NIOReactorParams;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
/**
* Generic implementation of {@link IOReactor} that can run multiple
* {@link BaseIOReactor} instance in separate worker threads and distribute
* newly created I/O session equally across those I/O reactors for a more
* optimal resource utilization and a better I/O performance. Usually it is
* recommended to have one worker I/O reactor per physical CPU core.
* <p>
* <strong>Important note about exception handling</strong>
* <p>
* Protocol specific exceptions as well as those I/O exceptions thrown in the
* course of interaction with the session's channel are to be expected are to be
* dealt with by specific protocol handlers. These exceptions may result in
* termination of an individual session but should not affect the I/O reactor
* and all other active sessions. There are situations, however, when the I/O
* reactor itself encounters an internal problem such as an I/O exception in
* the underlying NIO classes or an unhandled runtime exception. Those types of
* exceptions are usually fatal and will cause the I/O reactor to shut down
* automatically.
* <p>
* There is a possibility to override this behavior and prevent I/O reactors
* from shutting down automatically in case of a runtime exception or an I/O
* exception in internal classes. This can be accomplished by providing a custom
* implementation of the {@link IOReactorExceptionHandler} interface.
* <p>
* If an I/O reactor is unable to automatically recover from an I/O or a runtime
* exception it will enter the shutdown mode. First off, it cancel all pending
* new session requests. Then it will attempt to close all active I/O sessions
* gracefully giving them some time to flush pending output data and terminate
* cleanly. Lastly, it will forcibly shut down those I/O sessions that still
* remain active after the grace period. This is a fairly complex process, where
* many things can fail at the same time and many different exceptions can be
* thrown in the course of the shutdown process. The I/O reactor will record all
* exceptions thrown during the shutdown process, including the original one
* that actually caused the shutdown in the first place, in an audit log. One
* can obtain the audit log using {@link #getAuditLog()}, examine exceptions
* thrown by the I/O reactor prior and in the course of the reactor shutdown
* and decide whether it is safe to restart the I/O reactor.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#SELECT_INTERVAL}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#GRACE_PERIOD}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#INTEREST_OPS_QUEUEING}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractMultiworkerIOReactor implements IOReactor {
protected volatile IOReactorStatus status;
protected final HttpParams params;
protected final Selector selector;
protected final long selectTimeout;
protected final boolean interestOpsQueueing;
private final int workerCount;
private final ThreadFactory threadFactory;
private final BaseIOReactor[] dispatchers;
private final Worker[] workers;
private final Thread[] threads;
private final Object statusLock;
protected IOReactorExceptionHandler exceptionHandler;
protected List<ExceptionEvent> auditLog;
private int currentWorker = 0;
/**
* Creates an instance of AbstractMultiworkerIOReactor.
*
* @param workerCount number of worker I/O reactors.
* @param threadFactory the factory to create threads.
* Can be <code>null</code>.
* @param params HTTP parameters.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public AbstractMultiworkerIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super();
if (workerCount <= 0) {
throw new IllegalArgumentException("Worker count may not be negative or zero");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
try {
this.selector = Selector.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening selector", ex);
}
this.params = params;
this.selectTimeout = NIOReactorParams.getSelectInterval(params);
this.interestOpsQueueing = NIOReactorParams.getInterestOpsQueueing(params);
this.statusLock = new Object();
this.workerCount = workerCount;
if (threadFactory != null) {
this.threadFactory = threadFactory;
} else {
this.threadFactory = new DefaultThreadFactory();
}
this.dispatchers = new BaseIOReactor[workerCount];
this.workers = new Worker[workerCount];
this.threads = new Thread[workerCount];
this.status = IOReactorStatus.INACTIVE;
}
public IOReactorStatus getStatus() {
return this.status;
}
/**
* Returns the audit log containing exceptions thrown by the I/O reactor
* prior and in the course of the reactor shutdown.
*
* @return audit log.
*/
public synchronized List<ExceptionEvent> getAuditLog() {
if (this.auditLog != null) {
return new ArrayList<ExceptionEvent>(this.auditLog);
} else {
return null;
}
}
/**
* Adds the given {@link Throwable} object with the given time stamp
* to the audit log.
*
* @param ex the exception thrown by the I/O reactor.
* @param timestamp the time stamp of the exception. Can be
* <code>null</code> in which case the current date / time will be used.
*/
protected synchronized void addExceptionEvent(final Throwable ex, Date timestamp) {
if (ex == null) {
return;
}
if (timestamp == null) {
timestamp = new Date();
}
if (this.auditLog == null) {
this.auditLog = new ArrayList<ExceptionEvent>();
}
this.auditLog.add(new ExceptionEvent(ex, timestamp));
}
/**
* Adds the given {@link Throwable} object to the audit log.
*
* @param ex the exception thrown by the I/O reactor.
*/
protected void addExceptionEvent(final Throwable ex) {
addExceptionEvent(ex, null);
}
/**
* Sets exception handler for this I/O reactor.
*
* @param exceptionHandler the exception handler.
*/
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
/**
* Triggered to process I/O events registered by the main {@link Selector}.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param count event count.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected abstract void processEvents(int count) throws IOReactorException;
/**
* Triggered to cancel pending session requests.
* <p>
* Super-classes can implement this method to react to the event.
*
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected abstract void cancelRequests() throws IOReactorException;
/**
* Activates the main I/O reactor as well as all worker I/O reactors.
* The I/O main reactor will start reacting to I/O events and triggering
* notification methods. The worker I/O reactor in their turn will start
* reacting to I/O events and dispatch I/O event notifications to the given
* {@link IOEventDispatch} interface.
* <p>
* This method will enter the infinite I/O select loop on
* the {@link Selector} instance associated with this I/O reactor and used
* to manage creation of new I/O channels. Once a new I/O channel has been
* created the processing of I/O events on that channel will be delegated
* to one of the worker I/O reactors.
* <p>
* The method will remain blocked unto the I/O reactor is shut down or the
* execution thread is interrupted.
*
* @see #processEvents(int)
* @see #cancelRequests()
*
* @throws InterruptedIOException if the dispatch thread is interrupted.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.SHUTDOWN_REQUEST) >= 0) {
this.status = IOReactorStatus.SHUT_DOWN;
this.statusLock.notifyAll();
return;
}
if (this.status.compareTo(IOReactorStatus.INACTIVE) != 0) {
throw new IllegalStateException("Illegal state: " + this.status);
}
this.status = IOReactorStatus.ACTIVE;
// Start I/O dispatchers
for (int i = 0; i < this.dispatchers.length; i++) {
BaseIOReactor dispatcher = new BaseIOReactor(this.selectTimeout, this.interestOpsQueueing);
dispatcher.setExceptionHandler(exceptionHandler);
this.dispatchers[i] = dispatcher;
}
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
this.workers[i] = new Worker(dispatcher, eventDispatch);
this.threads[i] = this.threadFactory.newThread(this.workers[i]);
}
}
try {
for (int i = 0; i < this.workerCount; i++) {
if (this.status != IOReactorStatus.ACTIVE) {
return;
}
this.threads[i].start();
}
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) == 0) {
processEvents(readyCount);
}
// Verify I/O dispatchers
for (int i = 0; i < this.workerCount; i++) {
Worker worker = this.workers[i];
Exception ex = worker.getException();
if (ex != null) {
throw new IOReactorException(
"I/O dispatch worker terminated abnormally", ex);
}
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
break;
}
}
} catch (ClosedSelectorException ex) {
addExceptionEvent(ex);
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
throw ex;
} finally {
doShutdown();
synchronized (this.statusLock) {
this.status = IOReactorStatus.SHUT_DOWN;
this.statusLock.notifyAll();
}
}
}
/**
* Activates the shutdown sequence for this reactor. This method will cancel
* all pending session requests, close out all active I/O channels,
* make an attempt to terminate all worker I/O reactors gracefully,
* and finally force-terminate those I/O reactors that failed to
* terminate after the specified grace period.
*
* @throws InterruptedIOException if the shutdown sequence has been
* interrupted.
*/
protected void doShutdown() throws InterruptedIOException {
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
}
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
}
/**
* Assigns the given channel entry to one of the worker I/O reactors.
*
* @param entry the channel entry.
*/
protected void addChannel(final ChannelEntry entry) {
// Distribute new channels among the workers
int i = Math.abs(this.currentWorker++ % this.workerCount);
this.dispatchers[i].addChannel(entry);
}
/**
* Registers the given channel with the main {@link Selector}.
*
* @param channel the channel.
* @param ops interest ops.
* @return selection key.
* @throws ClosedChannelException if the channel has been already closed.
*/
protected SelectionKey registerChannel(
final SelectableChannel channel, int ops) throws ClosedChannelException {
return channel.register(this.selector, ops);
}
/**
* Prepares the given {@link Socket} by resetting some of its properties.
*
* @param socket the socket
* @throws IOException in case of an I/O error.
*/
protected void prepareSocket(final Socket socket) throws IOException {
socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(this.params));
socket.setSoTimeout(HttpConnectionParams.getSoTimeout(this.params));
int linger = HttpConnectionParams.getLinger(this.params);
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
}
/**
* Blocks for the given period of time in milliseconds awaiting
* the completion of the reactor shutdown. If the value of
* <code>timeout</code> is set to <code>0</code> this method blocks
* indefinitely.
*
* @param timeout the maximum wait time.
* @throws InterruptedException if interrupted.
*/
protected void awaitShutdown(long timeout) throws InterruptedException {
synchronized (this.statusLock) {
long deadline = System.currentTimeMillis() + timeout;
long remaining = timeout;
while (this.status != IOReactorStatus.SHUT_DOWN) {
this.statusLock.wait(remaining);
if (timeout > 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
break;
}
}
}
}
}
public void shutdown() throws IOException {
shutdown(2000);
}
public void shutdown(long waitMs) throws IOException {
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
return;
}
if (this.status.compareTo(IOReactorStatus.INACTIVE) == 0) {
this.status = IOReactorStatus.SHUT_DOWN;
cancelRequests();
return;
}
this.status = IOReactorStatus.SHUTDOWN_REQUEST;
}
this.selector.wakeup();
try {
awaitShutdown(waitMs);
} catch (InterruptedException ignore) {
}
}
static void closeChannel(final Channel channel) {
try {
channel.close();
} catch (IOException ignore) {
}
}
static class Worker implements Runnable {
final BaseIOReactor dispatcher;
final IOEventDispatch eventDispatch;
private volatile Exception exception;
public Worker(final BaseIOReactor dispatcher, final IOEventDispatch eventDispatch) {
super();
this.dispatcher = dispatcher;
this.eventDispatch = eventDispatch;
}
public void run() {
try {
this.dispatcher.execute(this.eventDispatch);
} catch (Exception ex) {
this.exception = ex;
}
}
public Exception getException() {
return this.exception;
}
}
static class DefaultThreadFactory implements ThreadFactory {
private static volatile int COUNT = 0;
public Thread newThread(final Runnable r) {
return new Thread(r, "I/O dispatcher " + (++COUNT));
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.params.HttpParams;
@Deprecated
class SSLIOSessionHandlerAdaptor implements SSLSetupHandler {
private final SSLIOSessionHandler handler;
public SSLIOSessionHandlerAdaptor(final SSLIOSessionHandler handler) {
super();
this.handler = handler;
}
public void initalize(final SSLEngine sslengine, final HttpParams params) throws SSLException {
this.handler.initalize(sslengine, params);
}
public void verify(final IOSession iosession, final SSLSession sslsession) throws SSLException {
this.handler.verify(iosession.getRemoteAddress(), sslsession);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.net.SocketAddress;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import org.apache.http.params.HttpParams;
/**
* Callback interface that can be used to customize various aspects of
* the TLS/SSl protocol.
*
* @since 4.0
*
* @deprecated Use {@link SSLSetupHandler}
*/
@Deprecated
public interface SSLIOSessionHandler {
/**
* Triggered when the SSL connection is being initialized. Custom handlers
* can use this callback to customize properties of the {@link SSLEngine}
* used to establish the SSL session.
*
* @param sslengine the SSL engine.
* @param params HTTP parameters.
* @throws SSLException if case of SSL protocol error.
*/
void initalize(SSLEngine sslengine, HttpParams params)
throws SSLException;
/**
* Triggered when the SSL connection has been established and initial SSL
* handshake has been successfully completed. Custom handlers can use
* this callback to verify properties of the {@link SSLSession}.
* For instance this would be the right place to enforce SSL cipher
* strength, validate certificate chain and do hostname checks.
*
* @param remoteAddress the remote address of the connection.
* @param session newly created SSL session.
* @throws SSLException if case of SSL protocol error.
*/
void verify(SocketAddress remoteAddress, SSLSession session)
throws SSLException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
/**
* @since 4.0
*/
public enum SSLMode {
CLIENT,
SERVER
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.util.Date;
/**
* A {@link Throwable} instance along with a time stamp.
*
* @since 4.0
*/
public class ExceptionEvent {
private final Throwable ex;
private final long time;
public ExceptionEvent(final Throwable ex, final Date timestamp) {
super();
this.ex = ex;
if (timestamp != null) {
this.time = timestamp.getTime();
} else {
this.time = 0;
}
}
public ExceptionEvent(final Exception ex) {
this(ex, new Date());
}
public Throwable getCause() {
return ex;
}
public Date getTimestamp() {
return new Date(this.time);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(new Date(this.time));
buffer.append(" ");
buffer.append(this.ex);
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ExpandableBuffer;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
/**
* Default implementation of {@link SessionOutputBuffer} based on
* the {@link ExpandableBuffer} class.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
public class SessionOutputBufferImpl extends ExpandableBuffer implements SessionOutputBuffer {
private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF};
private CharBuffer charbuffer = null;
private Charset charset = null;
private CharsetEncoder charencoder = null;
public SessionOutputBufferImpl(
int buffersize,
int linebuffersize,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(buffersize, allocator);
this.charbuffer = CharBuffer.allocate(linebuffersize);
this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params));
this.charencoder = this.charset.newEncoder();
}
public SessionOutputBufferImpl(
int buffersize,
int linebuffersize,
final HttpParams params) {
this(buffersize, linebuffersize, new HeapByteBufferAllocator(), params);
}
public void reset(final HttpParams params) {
clear();
}
public int flush(final WritableByteChannel channel) throws IOException {
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
setOutputMode();
int noWritten = channel.write(this.buffer);
return noWritten;
}
public void write(final ByteBuffer src) {
if (src == null) {
return;
}
setInputMode();
int requiredCapacity = this.buffer.position() + src.remaining();
ensureCapacity(requiredCapacity);
this.buffer.put(src);
}
public void write(final ReadableByteChannel src) throws IOException {
if (src == null) {
return;
}
setInputMode();
src.read(this.buffer);
}
private void write(final byte[] b) {
if (b == null) {
return;
}
setInputMode();
int off = 0;
int len = b.length;
int requiredCapacity = this.buffer.position() + len;
ensureCapacity(requiredCapacity);
this.buffer.put(b, off, len);
}
private void writeCRLF() {
write(CRLF);
}
public void writeLine(final CharArrayBuffer linebuffer) throws CharacterCodingException {
if (linebuffer == null) {
return;
}
// Do not bother if the buffer is empty
if (linebuffer.length() > 0 ) {
setInputMode();
this.charencoder.reset();
// transfer the string in small chunks
int remaining = linebuffer.length();
int offset = 0;
while (remaining > 0) {
int l = this.charbuffer.remaining();
boolean eol = false;
if (remaining <= l) {
l = remaining;
// terminate the encoding process
eol = true;
}
this.charbuffer.put(linebuffer.buffer(), offset, l);
this.charbuffer.flip();
boolean retry = true;
while (retry) {
CoderResult result = this.charencoder.encode(this.charbuffer, this.buffer, eol);
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
expand();
}
retry = !result.isUnderflow();
}
this.charbuffer.compact();
offset += l;
remaining -= l;
}
// flush the encoder
boolean retry = true;
while (retry) {
CoderResult result = this.charencoder.flush(this.buffer);
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
expand();
}
retry = !result.isUnderflow();
}
}
writeCRLF();
}
public void writeLine(final String s) throws IOException {
if (s == null) {
return;
}
if (s.length() > 0) {
CharArrayBuffer tmp = new CharArrayBuffer(s.length());
tmp.append(s);
writeLine(tmp);
} else {
write(CRLF);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.ListenerEndpoint;
/**
* Listener endpoint callback interface used internally by I/O reactor
* implementations.
*
* @since 4.0
*/
public interface ListenerEndpointClosedCallback {
void endpointClosed(ListenerEndpoint endpoint);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
/**
* Default implementation of {@link ConnectingIOReactor}. This class extends
* {@link AbstractMultiworkerIOReactor} with capability to connect to remote
* hosts.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#SELECT_INTERVAL}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#GRACE_PERIOD}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#INTEREST_OPS_QUEUEING}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultConnectingIOReactor extends AbstractMultiworkerIOReactor
implements ConnectingIOReactor {
private final Queue<SessionRequestImpl> requestQueue;
private long lastTimeoutCheck;
public DefaultConnectingIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super(workerCount, threadFactory, params);
this.requestQueue = new ConcurrentLinkedQueue<SessionRequestImpl>();
this.lastTimeoutCheck = System.currentTimeMillis();
}
public DefaultConnectingIOReactor(
int workerCount,
final HttpParams params) throws IOReactorException {
this(workerCount, null, params);
}
@Override
protected void cancelRequests() throws IOReactorException {
SessionRequestImpl request;
while ((request = this.requestQueue.poll()) != null) {
request.cancel();
}
}
@Override
protected void processEvents(int readyCount) throws IOReactorException {
processSessionRequests();
if (readyCount > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
long currentTime = System.currentTimeMillis();
if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) {
this.lastTimeoutCheck = currentTime;
Set<SelectionKey> keys = this.selector.keys();
processTimeouts(keys);
}
}
private void processEvent(final SelectionKey key) {
try {
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key.channel();
// Get request handle
SessionRequestHandle requestHandle = (SessionRequestHandle) key.attachment();
SessionRequestImpl sessionRequest = requestHandle.getSessionRequest();
// Finish connection process
try {
channel.finishConnect();
} catch (IOException ex) {
sessionRequest.failed(ex);
}
key.cancel();
if (channel.isConnected()) {
try {
try {
prepareSocket(channel.socket());
} catch (IOException ex) {
if (this.exceptionHandler == null
|| !this.exceptionHandler.handle(ex)) {
throw new IOReactorException(
"Failure initalizing socket", ex);
}
}
ChannelEntry entry = new ChannelEntry(channel, sessionRequest);
addChannel(entry);
} catch (IOException ex) {
sessionRequest.failed(ex);
}
}
}
} catch (CancelledKeyException ex) {
key.attach(null);
}
}
private void processTimeouts(final Set<SelectionKey> keys) {
long now = System.currentTimeMillis();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
SelectionKey key = it.next();
Object attachment = key.attachment();
if (attachment instanceof SessionRequestHandle) {
SessionRequestHandle handle = (SessionRequestHandle) key.attachment();
SessionRequestImpl sessionRequest = handle.getSessionRequest();
int timeout = sessionRequest.getConnectTimeout();
if (timeout > 0) {
if (handle.getRequestTime() + timeout < now) {
sessionRequest.timeout();
}
}
}
}
}
public SessionRequest connect(
final SocketAddress remoteAddress,
final SocketAddress localAddress,
final Object attachment,
final SessionRequestCallback callback) {
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
throw new IllegalStateException("I/O reactor has been shut down");
}
SessionRequestImpl sessionRequest = new SessionRequestImpl(
remoteAddress, localAddress, attachment, callback);
sessionRequest.setConnectTimeout(HttpConnectionParams.getConnectionTimeout(this.params));
this.requestQueue.add(sessionRequest);
this.selector.wakeup();
return sessionRequest;
}
private void validateAddress(final SocketAddress address) throws UnknownHostException {
if (address == null) {
return;
}
if (address instanceof InetSocketAddress) {
InetSocketAddress endpoint = (InetSocketAddress) address;
if (endpoint.isUnresolved()) {
throw new UnknownHostException(endpoint.getHostName());
}
}
}
private void processSessionRequests() throws IOReactorException {
SessionRequestImpl request;
while ((request = this.requestQueue.poll()) != null) {
if (request.isCompleted()) {
continue;
}
SocketChannel socketChannel;
try {
socketChannel = SocketChannel.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening socket", ex);
}
try {
socketChannel.configureBlocking(false);
validateAddress(request.getLocalAddress());
validateAddress(request.getRemoteAddress());
if (request.getLocalAddress() != null) {
Socket sock = socketChannel.socket();
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(this.params));
sock.bind(request.getLocalAddress());
}
boolean connected = socketChannel.connect(request.getRemoteAddress());
if (connected) {
prepareSocket(socketChannel.socket());
ChannelEntry entry = new ChannelEntry(socketChannel, request);
addChannel(entry);
return;
}
} catch (IOException ex) {
closeChannel(socketChannel);
request.failed(ex);
return;
}
SessionRequestHandle requestHandle = new SessionRequestHandle(request);
try {
SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT,
requestHandle);
request.setKey(key);
} catch (IOException ex) {
closeChannel(socketChannel);
throw new IOReactorException("Failure registering channel " +
"with the selector", ex);
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.SessionRequest;
/**
* Session request handle class used by I/O reactor implementations to keep
* a reference to a {@link SessionRequest} along with the time the request
* was made.
* @since 4.0
*/
public class SessionRequestHandle {
private final SessionRequestImpl sessionRequest;
private final long requestTime;
public SessionRequestHandle(final SessionRequestImpl sessionRequest) {
super();
if (sessionRequest == null) {
throw new IllegalArgumentException("Session request may not be null");
}
this.sessionRequest = sessionRequest;
this.requestTime = System.currentTimeMillis();
}
public SessionRequestImpl getSessionRequest() {
return this.sessionRequest;
}
public long getRequestTime() {
return this.requestTime;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import org.apache.http.nio.reactor.ListenerEndpoint;
/**
* Default implementation of {@link ListenerEndpoint}.
*
* @since 4.0
*/
public class ListenerEndpointImpl implements ListenerEndpoint {
private volatile boolean completed;
private volatile boolean closed;
private volatile SelectionKey key;
private volatile SocketAddress address;
private volatile IOException exception;
private final ListenerEndpointClosedCallback callback;
public ListenerEndpointImpl(
final SocketAddress address,
final ListenerEndpointClosedCallback callback) {
super();
if (address == null) {
throw new IllegalArgumentException("Address may not be null");
}
this.address = address;
this.callback = callback;
}
public SocketAddress getAddress() {
return this.address;
}
public boolean isCompleted() {
return this.completed;
}
public IOException getException() {
return this.exception;
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
public void completed(final SocketAddress address) {
if (address == null) {
throw new IllegalArgumentException("Address may not be null");
}
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.address = address;
notifyAll();
}
}
public void failed(final IOException exception) {
if (exception == null) {
return;
}
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.exception = exception;
notifyAll();
}
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
this.closed = true;
synchronized (this) {
notifyAll();
}
}
protected void setKey(final SelectionKey key) {
this.key = key;
}
public boolean isClosed() {
return this.closed || (this.key != null && !this.key.isValid());
}
public void close() {
if (this.closed) {
return;
}
this.completed = true;
this.closed = true;
if (this.key != null) {
this.key.cancel();
Channel channel = this.key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
if (this.callback != null) {
this.callback.endpointClosed(this);
}
synchronized (this) {
notifyAll();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ExpandableBuffer;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
/**
* Default implementation of {@link SessionInputBuffer} based on
* the {@link ExpandableBuffer} class.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
public class SessionInputBufferImpl extends ExpandableBuffer implements SessionInputBuffer {
private CharBuffer charbuffer = null;
private Charset charset = null;
private CharsetDecoder chardecoder = null;
public SessionInputBufferImpl(
int buffersize,
int linebuffersize,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(buffersize, allocator);
this.charbuffer = CharBuffer.allocate(linebuffersize);
this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params));
this.chardecoder = this.charset.newDecoder();
}
public SessionInputBufferImpl(
int buffersize,
int linebuffersize,
final HttpParams params) {
this(buffersize, linebuffersize, new HeapByteBufferAllocator(), params);
}
public int fill(final ReadableByteChannel channel) throws IOException {
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
setInputMode();
if (!this.buffer.hasRemaining()) {
expand();
}
int readNo = channel.read(this.buffer);
return readNo;
}
public int read() {
setOutputMode();
return this.buffer.get() & 0xff;
}
public int read(final ByteBuffer dst, int maxLen) {
if (dst == null) {
return 0;
}
setOutputMode();
int len = Math.min(dst.remaining(), maxLen);
int chunk = Math.min(this.buffer.remaining(), len);
for (int i = 0; i < chunk; i++) {
dst.put(this.buffer.get());
}
return chunk;
}
public int read(final ByteBuffer dst) {
if (dst == null) {
return 0;
}
return read(dst, dst.remaining());
}
public int read(final WritableByteChannel dst, int maxLen) throws IOException {
if (dst == null) {
return 0;
}
setOutputMode();
int bytesRead;
if (this.buffer.remaining() > maxLen) {
int oldLimit = this.buffer.limit();
int newLimit = oldLimit - (this.buffer.remaining() - maxLen);
this.buffer.limit(newLimit);
bytesRead = dst.write(this.buffer);
this.buffer.limit(oldLimit);
} else {
bytesRead = dst.write(this.buffer);
}
return bytesRead;
}
public int read(final WritableByteChannel dst) throws IOException {
if (dst == null) {
return 0;
}
setOutputMode();
return dst.write(this.buffer);
}
public boolean readLine(
final CharArrayBuffer linebuffer,
boolean endOfStream) throws CharacterCodingException {
setOutputMode();
// See if there is LF char present in the buffer
int pos = -1;
boolean hasLine = false;
for (int i = this.buffer.position(); i < this.buffer.limit(); i++) {
int b = this.buffer.get(i);
if (b == HTTP.LF) {
hasLine = true;
pos = i + 1;
break;
}
}
if (!hasLine) {
if (endOfStream && this.buffer.hasRemaining()) {
// No more data. Get the rest
pos = this.buffer.limit();
} else {
// Either no complete line present in the buffer
// or no more data is expected
return false;
}
}
int origLimit = this.buffer.limit();
this.buffer.limit(pos);
int len = this.buffer.limit() - this.buffer.position();
// Ensure capacity of len assuming ASCII as the most likely charset
linebuffer.ensureCapacity(len);
this.chardecoder.reset();
for (;;) {
CoderResult result = this.chardecoder.decode(
this.buffer,
this.charbuffer,
true);
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
this.charbuffer.flip();
linebuffer.append(
this.charbuffer.array(),
this.charbuffer.position(),
this.charbuffer.remaining());
this.charbuffer.clear();
}
if (result.isUnderflow()) {
break;
}
}
this.buffer.limit(origLimit);
// flush the decoder
this.chardecoder.flush(this.charbuffer);
this.charbuffer.flip();
// append the decoded content to the line buffer
if (this.charbuffer.hasRemaining()) {
linebuffer.append(
this.charbuffer.array(),
this.charbuffer.position(),
this.charbuffer.remaining());
}
// discard LF if found
int l = linebuffer.length();
if (l > 0) {
if (linebuffer.charAt(l - 1) == HTTP.LF) {
l--;
linebuffer.setLength(l);
}
// discard CR if found
if (l > 0) {
if (linebuffer.charAt(l - 1) == HTTP.CR) {
l--;
linebuffer.setLength(l);
}
}
}
return true;
}
public String readLine(boolean endOfStream) throws CharacterCodingException {
CharArrayBuffer charbuffer = new CharArrayBuffer(64);
boolean found = readLine(charbuffer, endOfStream);
if (found) {
return charbuffer.toString();
} else {
return null;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.IOSession;
/**
* Generic implementation of {@link IOReactor} that can used as a subclass
* for more specialized I/O reactors. It is based on a single {@link Selector}
* instance.
*
* @since 4.0
*/
public abstract class AbstractIOReactor implements IOReactor {
private volatile IOReactorStatus status;
private final Object statusMutex;
private final long selectTimeout;
private final boolean interestOpsQueueing;
private final Selector selector;
private final Set<IOSession> sessions;
private final Queue<InterestOpEntry> interestOpsQueue;
private final Queue<IOSession> closedSessions;
private final Queue<ChannelEntry> newChannels;
/**
* Creates new AbstractIOReactor instance.
*
* @param selectTimeout the select timeout.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public AbstractIOReactor(long selectTimeout) throws IOReactorException {
this(selectTimeout, false);
}
/**
* Creates new AbstractIOReactor instance.
*
* @param selectTimeout the select timeout.
* @param interestOpsQueueing Ops queueing flag.
*
* @throws IOReactorException in case if a non-recoverable I/O error.
*
* @since 4.1
*/
public AbstractIOReactor(long selectTimeout, boolean interestOpsQueueing) throws IOReactorException {
super();
if (selectTimeout <= 0) {
throw new IllegalArgumentException("Select timeout may not be negative or zero");
}
this.selectTimeout = selectTimeout;
this.interestOpsQueueing = interestOpsQueueing;
this.sessions = Collections.synchronizedSet(new HashSet<IOSession>());
this.interestOpsQueue = new ConcurrentLinkedQueue<InterestOpEntry>();
this.closedSessions = new ConcurrentLinkedQueue<IOSession>();
this.newChannels = new ConcurrentLinkedQueue<ChannelEntry>();
try {
this.selector = Selector.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening selector", ex);
}
this.statusMutex = new Object();
this.status = IOReactorStatus.INACTIVE;
}
/**
* Triggered when the key signals {@link SelectionKey#OP_ACCEPT} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void acceptable(SelectionKey key);
/**
* Triggered when the key signals {@link SelectionKey#OP_CONNECT} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void connectable(SelectionKey key);
/**
* Triggered when the key signals {@link SelectionKey#OP_READ} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void readable(SelectionKey key);
/**
* Triggered when the key signals {@link SelectionKey#OP_WRITE} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void writable(SelectionKey key);
/**
* Triggered to verify whether the I/O session associated with the
* given selection key has not timed out.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
* @param now current time as long value.
*/
protected abstract void timeoutCheck(SelectionKey key, long now);
/**
* Triggered to validate keys currently registered with the selector. This
* method is called after each I/O select loop.
* <p>
* Super-classes can implement this method to run validity checks on
* active sessions and include additional processing that needs to be
* executed after each I/O select loop.
*
* @param keys all selection keys registered with the selector.
*/
protected abstract void validate(Set<SelectionKey> keys);
/**
* Triggered when new session has been created.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
* @param session new I/O session.
*/
protected abstract void sessionCreated(SelectionKey key, IOSession session);
/**
* Triggered when a session has been closed.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param session closed I/O session.
*/
protected abstract void sessionClosed(IOSession session);
/**
* Obtains {@link IOSession} instance associated with the given selection
* key.
*
* @param key the selection key.
* @return I/O session.
*/
protected abstract IOSession getSession(SelectionKey key);
public IOReactorStatus getStatus() {
return this.status;
}
/**
* Returns <code>true</code> if interest Ops queueing is enabled, <code>false</code> otherwise.
*
* @since 4.1
*/
public boolean getInterestOpsQueueing() {
return this.interestOpsQueueing;
}
/**
* Adds new channel entry. The channel will be asynchronously registered
* with the selector.
*
* @param channelEntry the channel entry.
*/
public void addChannel(final ChannelEntry channelEntry) {
if (channelEntry == null) {
throw new IllegalArgumentException("Channel entry may not be null");
}
this.newChannels.add(channelEntry);
this.selector.wakeup();
}
/**
* Activates the I/O reactor. The I/O reactor will start reacting to
* I/O events and triggering notification methods.
* <p>
* This method will enter the infinite I/O select loop on
* the {@link Selector} instance associated with this I/O reactor.
* <p>
* The method will remain blocked unto the I/O reactor is shut down or the
* execution thread is interrupted.
*
* @see #acceptable(SelectionKey)
* @see #connectable(SelectionKey)
* @see #readable(SelectionKey)
* @see #writable(SelectionKey)
* @see #timeoutCheck(SelectionKey, long)
* @see #validate(Set)
* @see #sessionCreated(SelectionKey, IOSession)
* @see #sessionClosed(IOSession)
*
* @throws InterruptedIOException if the dispatch thread is interrupted.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected void execute() throws InterruptedIOException, IOReactorException {
this.status = IOReactorStatus.ACTIVE;
try {
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status == IOReactorStatus.SHUT_DOWN) {
// Hard shut down. Exit select loop immediately
break;
}
if (this.status == IOReactorStatus.SHUTTING_DOWN) {
// Graceful shutdown in process
// Try to close things out nicely
closeSessions();
closeNewChannels();
}
// Process selected I/O events
if (readyCount > 0) {
processEvents(this.selector.selectedKeys());
}
// Validate active channels
validate(this.selector.keys());
// Process closed sessions
processClosedSessions();
// If active process new channels
if (this.status == IOReactorStatus.ACTIVE) {
processNewChannels();
}
// Exit select loop if graceful shutdown has been completed
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0
&& this.sessions.isEmpty()) {
break;
}
if (this.interestOpsQueueing) {
// process all pending interestOps() operations
processPendingInterestOps();
}
}
} catch (ClosedSelectorException ex) {
} finally {
hardShutdown();
synchronized (this.statusMutex) {
this.statusMutex.notifyAll();
}
}
}
private void processEvents(final Set<SelectionKey> selectedKeys) {
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
/**
* Processes new event on the given selection key.
*
* @param key the selection key that triggered an event.
*/
protected void processEvent(final SelectionKey key) {
try {
if (key.isAcceptable()) {
acceptable(key);
}
if (key.isConnectable()) {
connectable(key);
}
if (key.isReadable()) {
readable(key);
}
if (key.isWritable()) {
writable(key);
}
} catch (CancelledKeyException ex) {
IOSession session = getSession(key);
queueClosedSession(session);
key.attach(null);
}
}
/**
* Queues the given I/O session to be processed asynchronously as closed.
*
* @param session the closed I/O session.
*/
protected void queueClosedSession(final IOSession session) {
if (session != null) {
this.closedSessions.add(session);
}
}
private void processNewChannels() throws IOReactorException {
ChannelEntry entry;
while ((entry = this.newChannels.poll()) != null) {
SocketChannel channel;
SelectionKey key;
try {
channel = entry.getChannel();
channel.configureBlocking(false);
key = channel.register(this.selector, SelectionKey.OP_READ);
} catch (ClosedChannelException ex) {
SessionRequestImpl sessionRequest = entry.getSessionRequest();
if (sessionRequest != null) {
sessionRequest.failed(ex);
}
return;
} catch (IOException ex) {
throw new IOReactorException("Failure registering channel " +
"with the selector", ex);
}
SessionClosedCallback sessionClosedCallback = new SessionClosedCallback() {
public void sessionClosed(IOSession session) {
queueClosedSession(session);
}
};
InterestOpsCallback interestOpsCallback = null;
if (this.interestOpsQueueing) {
interestOpsCallback = new InterestOpsCallback() {
public void addInterestOps(final InterestOpEntry entry) {
queueInterestOps(entry);
}
};
}
IOSession session = new IOSessionImpl(key, interestOpsCallback, sessionClosedCallback);
int timeout = 0;
try {
timeout = channel.socket().getSoTimeout();
} catch (IOException ex) {
// Very unlikely to happen and is not fatal
// as the protocol layer is expected to overwrite
// this value anyways
}
session.setAttribute(IOSession.ATTACHMENT_KEY, entry.getAttachment());
session.setSocketTimeout(timeout);
this.sessions.add(session);
try {
SessionRequestImpl sessionRequest = entry.getSessionRequest();
if (sessionRequest != null) {
sessionRequest.completed(session);
}
sessionCreated(key, session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
}
}
}
private void processClosedSessions() {
IOSession session;
while ((session = this.closedSessions.poll()) != null) {
if (this.sessions.remove(session)) {
try {
sessionClosed(session);
} catch (CancelledKeyException ex) {
// ignore and move on
}
}
}
}
private void processPendingInterestOps() {
// validity check
if (!this.interestOpsQueueing) {
return;
}
InterestOpEntry entry;
while ((entry = this.interestOpsQueue.poll()) != null) {
// obtain the operation's details
SelectionKey key = entry.getSelectionKey();
int eventMask = entry.getEventMask();
if (key.isValid()) {
key.interestOps(eventMask);
}
}
}
private boolean queueInterestOps(final InterestOpEntry entry) {
// validity checks
if (!this.interestOpsQueueing) {
throw new IllegalStateException("Interest ops queueing not enabled");
}
if (entry == null) {
return false;
}
// add this operation to the interestOps() queue
this.interestOpsQueue.add(entry);
return true;
}
/**
* Closes out all I/O sessions maintained by this I/O reactor.
*/
protected void closeSessions() {
synchronized (this.sessions) {
for (Iterator<IOSession> it = this.sessions.iterator(); it.hasNext(); ) {
IOSession session = it.next();
session.close();
}
}
}
/**
* Closes out all new channels pending registration with the selector of
* this I/O reactor.
* @throws IOReactorException - not thrown currently
*/
protected void closeNewChannels() throws IOReactorException {
ChannelEntry entry;
while ((entry = this.newChannels.poll()) != null) {
SessionRequestImpl sessionRequest = entry.getSessionRequest();
if (sessionRequest != null) {
sessionRequest.cancel();
}
SocketChannel channel = entry.getChannel();
try {
channel.close();
} catch (IOException ignore) {
}
}
}
/**
* Closes out all active channels registered with the selector of
* this I/O reactor.
* @throws IOReactorException - not thrown currently
*/
protected void closeActiveChannels() throws IOReactorException {
try {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
IOSession session = getSession(key);
if (session != null) {
session.close();
}
}
this.selector.close();
} catch (IOException ignore) {
}
}
/**
* Attempts graceful shutdown of this I/O reactor.
*/
public void gracefulShutdown() {
synchronized (this.statusMutex) {
if (this.status != IOReactorStatus.ACTIVE) {
// Already shutting down
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
}
this.selector.wakeup();
}
/**
* Attempts force-shutdown of this I/O reactor.
*/
public void hardShutdown() throws IOReactorException {
synchronized (this.statusMutex) {
if (this.status == IOReactorStatus.SHUT_DOWN) {
// Already shut down
return;
}
this.status = IOReactorStatus.SHUT_DOWN;
}
closeNewChannels();
closeActiveChannels();
processClosedSessions();
}
/**
* Blocks for the given period of time in milliseconds awaiting
* the completion of the reactor shutdown.
*
* @param timeout the maximum wait time.
* @throws InterruptedException if interrupted.
*/
public void awaitShutdown(long timeout) throws InterruptedException {
synchronized (this.statusMutex) {
long deadline = System.currentTimeMillis() + timeout;
long remaining = timeout;
while (this.status != IOReactorStatus.SHUT_DOWN) {
this.statusMutex.wait(remaining);
if (timeout > 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
break;
}
}
}
}
}
public void shutdown(long gracePeriod) throws IOReactorException {
if (this.status != IOReactorStatus.INACTIVE) {
gracefulShutdown();
try {
awaitShutdown(gracePeriod);
} catch (InterruptedException ignore) {
}
}
if (this.status != IOReactorStatus.SHUT_DOWN) {
hardShutdown();
}
}
public void shutdown() throws IOReactorException {
shutdown(1000);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.HttpParams;
/**
* Default implementation of {@link ListeningIOReactor}. This class extends
* {@link AbstractMultiworkerIOReactor} with capability to listen for incoming
* connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#SELECT_INTERVAL}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#GRACE_PERIOD}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#INTEREST_OPS_QUEUEING}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultListeningIOReactor extends AbstractMultiworkerIOReactor
implements ListeningIOReactor {
private final Queue<ListenerEndpointImpl> requestQueue;
private final Set<ListenerEndpointImpl> endpoints;
private final Set<SocketAddress> pausedEndpoints;
private volatile boolean paused;
public DefaultListeningIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super(workerCount, threadFactory, params);
this.requestQueue = new ConcurrentLinkedQueue<ListenerEndpointImpl>();
this.endpoints = Collections.synchronizedSet(new HashSet<ListenerEndpointImpl>());
this.pausedEndpoints = new HashSet<SocketAddress>();
}
public DefaultListeningIOReactor(
int workerCount,
final HttpParams params) throws IOReactorException {
this(workerCount, null, params);
}
@Override
protected void cancelRequests() throws IOReactorException {
ListenerEndpointImpl request;
while ((request = this.requestQueue.poll()) != null) {
request.cancel();
}
}
@Override
protected void processEvents(int readyCount) throws IOReactorException {
if (!this.paused) {
processSessionRequests();
}
if (readyCount > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
}
private void processEvent(final SelectionKey key)
throws IOReactorException {
try {
if (key.isAcceptable()) {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = null;
try {
socketChannel = serverChannel.accept();
} catch (IOException ex) {
if (this.exceptionHandler == null ||
!this.exceptionHandler.handle(ex)) {
throw new IOReactorException(
"Failure accepting connection", ex);
}
}
if (socketChannel != null) {
try {
prepareSocket(socketChannel.socket());
} catch (IOException ex) {
if (this.exceptionHandler == null ||
!this.exceptionHandler.handle(ex)) {
throw new IOReactorException(
"Failure initalizing socket", ex);
}
}
ChannelEntry entry = new ChannelEntry(socketChannel);
addChannel(entry);
}
}
} catch (CancelledKeyException ex) {
ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment();
this.endpoints.remove(endpoint);
key.attach(null);
}
}
private ListenerEndpointImpl createEndpoint(final SocketAddress address) {
ListenerEndpointImpl endpoint = new ListenerEndpointImpl(
address,
new ListenerEndpointClosedCallback() {
public void endpointClosed(final ListenerEndpoint endpoint) {
endpoints.remove(endpoint);
}
});
return endpoint;
}
public ListenerEndpoint listen(final SocketAddress address) {
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
throw new IllegalStateException("I/O reactor has been shut down");
}
ListenerEndpointImpl request = createEndpoint(address);
this.requestQueue.add(request);
this.selector.wakeup();
return request;
}
private void processSessionRequests() throws IOReactorException {
ListenerEndpointImpl request;
while ((request = this.requestQueue.poll()) != null) {
SocketAddress address = request.getAddress();
ServerSocketChannel serverChannel;
try {
serverChannel = ServerSocketChannel.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening server socket", ex);
}
try {
serverChannel.configureBlocking(false);
serverChannel.socket().bind(address);
} catch (IOException ex) {
closeChannel(serverChannel);
request.failed(ex);
if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) {
throw new IOReactorException("Failure binding socket to address "
+ address, ex);
} else {
return;
}
}
try {
SelectionKey key = serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
key.attach(request);
request.setKey(key);
} catch (IOException ex) {
closeChannel(serverChannel);
throw new IOReactorException("Failure registering channel " +
"with the selector", ex);
}
this.endpoints.add(request);
request.completed(serverChannel.socket().getLocalSocketAddress());
}
}
public Set<ListenerEndpoint> getEndpoints() {
Set<ListenerEndpoint> set = new HashSet<ListenerEndpoint>();
synchronized (this.endpoints) {
Iterator<ListenerEndpointImpl> it = this.endpoints.iterator();
while (it.hasNext()) {
ListenerEndpoint endpoint = it.next();
if (!endpoint.isClosed()) {
set.add(endpoint);
} else {
it.remove();
}
}
}
return set;
}
public void pause() throws IOException {
if (this.paused) {
return;
}
this.paused = true;
synchronized (this.endpoints) {
Iterator<ListenerEndpointImpl> it = this.endpoints.iterator();
while (it.hasNext()) {
ListenerEndpoint endpoint = it.next();
if (!endpoint.isClosed()) {
endpoint.close();
this.pausedEndpoints.add(endpoint.getAddress());
}
}
this.endpoints.clear();
}
}
public void resume() throws IOException {
if (!this.paused) {
return;
}
this.paused = false;
for (SocketAddress address: this.pausedEndpoints) {
ListenerEndpointImpl request = createEndpoint(address);
this.requestQueue.add(request);
}
this.pausedEndpoints.clear();
this.selector.wakeup();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
/**
* Callback interface used internally by I/O session implementations to delegate execution
* of a {@link java.nio.channels.SelectionKey#interestOps(int)} operation to the I/O reactor.
*
* @since 4.1
*/
interface InterestOpsCallback {
void addInterestOps(InterestOpEntry entry);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
/**
* Default implementation of {@link SessionRequest}.
*
* @since 4.0
*/
public class SessionRequestImpl implements SessionRequest {
private volatile boolean completed;
private volatile SelectionKey key;
private final SocketAddress remoteAddress;
private final SocketAddress localAddress;
private final Object attachment;
private final SessionRequestCallback callback;
private volatile int connectTimeout;
private volatile IOSession session = null;
private volatile IOException exception = null;
public SessionRequestImpl(
final SocketAddress remoteAddress,
final SocketAddress localAddress,
final Object attachment,
final SessionRequestCallback callback) {
super();
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
this.remoteAddress = remoteAddress;
this.localAddress = localAddress;
this.attachment = attachment;
this.callback = callback;
this.connectTimeout = 0;
}
public SocketAddress getRemoteAddress() {
return this.remoteAddress;
}
public SocketAddress getLocalAddress() {
return this.localAddress;
}
public Object getAttachment() {
return this.attachment;
}
public boolean isCompleted() {
return this.completed;
}
protected void setKey(final SelectionKey key) {
this.key = key;
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
public IOSession getSession() {
synchronized (this) {
return this.session;
}
}
public IOException getException() {
synchronized (this) {
return this.exception;
}
}
public void completed(final IOSession session) {
if (session == null) {
throw new IllegalArgumentException("Session may not be null");
}
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.session = session;
if (this.callback != null) {
this.callback.completed(this);
}
notifyAll();
}
}
public void failed(final IOException exception) {
if (exception == null) {
return;
}
if (this.completed) {
return;
}
this.completed = true;
SelectionKey key = this.key;
if (key != null) {
key.cancel();
Channel channel = key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
synchronized (this) {
this.exception = exception;
if (this.callback != null) {
this.callback.failed(this);
}
notifyAll();
}
}
public void timeout() {
if (this.completed) {
return;
}
this.completed = true;
SelectionKey key = this.key;
if (key != null) {
key.cancel();
Channel channel = key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
synchronized (this) {
if (this.callback != null) {
this.callback.timeout(this);
}
}
}
public int getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(int timeout) {
if (this.connectTimeout != timeout) {
this.connectTimeout = timeout;
SelectionKey key = this.key;
if (key != null) {
key.selector().wakeup();
}
}
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
SelectionKey key = this.key;
if (key != null) {
key.cancel();
Channel channel = key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
synchronized (this) {
if (this.callback != null) {
this.callback.cancelled(this);
}
notifyAll();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.ByteChannel;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
/**
* Default implementation of {@link IOSession}.
*
* @since 4.0
*/
public class IOSessionImpl implements IOSession {
private final SelectionKey key;
private final ByteChannel channel;
private final Map<String, Object> attributes;
private final InterestOpsCallback interestOpsCallback;
private final SessionClosedCallback sessionClosedCallback;
private volatile int status;
private volatile int currentEventMask;
private volatile SessionBufferStatus bufferStatus;
private volatile int socketTimeout;
/**
* Creates new instance of IOSessionImpl.
*
* @param key the selection key.
* @param interestOpsCallback interestOps callback.
* @param sessionClosedCallback session closed callback.
*
* @since 4.1
*/
public IOSessionImpl(
final SelectionKey key,
final InterestOpsCallback interestOpsCallback,
final SessionClosedCallback sessionClosedCallback) {
super();
if (key == null) {
throw new IllegalArgumentException("Selection key may not be null");
}
this.key = key;
this.channel = (ByteChannel) this.key.channel();
this.interestOpsCallback = interestOpsCallback;
this.sessionClosedCallback = sessionClosedCallback;
this.attributes = Collections.synchronizedMap(new HashMap<String, Object>());
this.currentEventMask = 0;
this.socketTimeout = 0;
this.status = ACTIVE;
}
/**
* Creates new instance of IOSessionImpl.
*
* @param key the selection key.
* @param sessionClosedCallback session closed callback.
*/
public IOSessionImpl(
final SelectionKey key,
final SessionClosedCallback sessionClosedCallback) {
this(key, null, sessionClosedCallback);
}
public ByteChannel channel() {
return this.channel;
}
public SocketAddress getLocalAddress() {
Channel channel = this.channel;
if (channel instanceof SocketChannel) {
return ((SocketChannel)channel).socket().getLocalSocketAddress();
} else {
return null;
}
}
public SocketAddress getRemoteAddress() {
Channel channel = this.channel;
if (channel instanceof SocketChannel) {
return ((SocketChannel)channel).socket().getRemoteSocketAddress();
} else {
return null;
}
}
public synchronized int getEventMask() {
return this.interestOpsCallback != null ? this.currentEventMask : this.key.interestOps();
}
public synchronized void setEventMask(int ops) {
if (this.status == CLOSED) {
return;
}
if (this.interestOpsCallback != null) {
// update the current event mask
this.currentEventMask = ops;
// local variable
InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask);
// add this operation to the interestOps() queue
this.interestOpsCallback.addInterestOps(entry);
} else {
this.key.interestOps(ops);
}
this.key.selector().wakeup();
}
public synchronized void setEvent(int op) {
if (this.status == CLOSED) {
return;
}
if (this.interestOpsCallback != null) {
// update the current event mask
this.currentEventMask |= op;
// local variable
InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask);
// add this operation to the interestOps() queue
this.interestOpsCallback.addInterestOps(entry);
} else {
int ops = this.key.interestOps();
this.key.interestOps(ops | op);
}
this.key.selector().wakeup();
}
public synchronized void clearEvent(int op) {
if (this.status == CLOSED) {
return;
}
if (this.interestOpsCallback != null) {
// update the current event mask
this.currentEventMask &= ~op;
// local variable
InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask);
// add this operation to the interestOps() queue
this.interestOpsCallback.addInterestOps(entry);
} else {
int ops = this.key.interestOps();
this.key.interestOps(ops & ~op);
}
this.key.selector().wakeup();
}
public int getSocketTimeout() {
return this.socketTimeout;
}
public void setSocketTimeout(int timeout) {
this.socketTimeout = timeout;
}
public synchronized void close() {
if (this.status == CLOSED) {
return;
}
this.status = CLOSED;
this.key.cancel();
try {
this.key.channel().close();
} catch (IOException ex) {
// Munching exceptions is not nice
// but in this case it is justified
}
if (this.sessionClosedCallback != null) {
this.sessionClosedCallback.sessionClosed(this);
}
if (this.key.selector().isOpen()) {
this.key.selector().wakeup();
}
}
public int getStatus() {
return this.status;
}
public boolean isClosed() {
return this.status == CLOSED;
}
public void shutdown() {
// For this type of session, a close() does exactly
// what we need and nothing more.
close();
}
public boolean hasBufferedInput() {
SessionBufferStatus bufferStatus = this.bufferStatus;
return bufferStatus != null && bufferStatus.hasBufferedInput();
}
public boolean hasBufferedOutput() {
SessionBufferStatus bufferStatus = this.bufferStatus;
return bufferStatus != null && bufferStatus.hasBufferedOutput();
}
public void setBufferStatus(final SessionBufferStatus bufferStatus) {
this.bufferStatus = bufferStatus;
}
public Object getAttribute(final String name) {
return this.attributes.get(name);
}
public Object removeAttribute(final String name) {
return this.attributes.remove(name);
}
public void setAttribute(final String name, final Object obj) {
this.attributes.put(name, obj);
}
private static void formatOps(final StringBuffer buffer, int ops) {
buffer.append('[');
if ((ops & SelectionKey.OP_READ) > 0) {
buffer.append('r');
}
if ((ops & SelectionKey.OP_WRITE) > 0) {
buffer.append('w');
}
if ((ops & SelectionKey.OP_ACCEPT) > 0) {
buffer.append('a');
}
if ((ops & SelectionKey.OP_CONNECT) > 0) {
buffer.append('c');
}
buffer.append(']');
}
@Override
public synchronized String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
if (this.key.isValid()) {
buffer.append("interest ops: ");
formatOps(buffer, this.interestOpsCallback != null ?
this.currentEventMask : this.key.interestOps());
buffer.append("; ready ops: ");
formatOps(buffer, this.key.readyOps());
} else {
buffer.append("invalid");
}
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
import org.apache.http.params.HttpParams;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
/**
* A decorator class intended to transparently extend an {@link IOSession}
* with transport layer security capabilities based on the SSL/TLS protocol.
*
* @since 4.0
*/
public class SSLIOSession implements IOSession, SessionBufferStatus {
private final IOSession session;
private final SSLEngine sslEngine;
private final ByteBuffer inEncrypted;
private final ByteBuffer outEncrypted;
private final ByteBuffer inPlain;
private final ByteBuffer outPlain;
private final InternalByteChannel channel;
private final SSLSetupHandler handler;
private int appEventMask;
private SessionBufferStatus appBufferStatus;
private boolean endOfStream;
private volatile int status;
/**
* @since 4.1
*/
public SSLIOSession(
final IOSession session,
final SSLContext sslContext,
final SSLSetupHandler handler) {
super();
if (session == null) {
throw new IllegalArgumentException("IO session may not be null");
}
if (sslContext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
this.session = session;
this.appEventMask = session.getEventMask();
this.channel = new InternalByteChannel();
this.handler = handler;
// Override the status buffer interface
this.session.setBufferStatus(this);
SocketAddress address = session.getRemoteAddress();
if (address instanceof InetSocketAddress) {
String hostname = ((InetSocketAddress) address).getHostName();
int port = ((InetSocketAddress) address).getPort();
this.sslEngine = sslContext.createSSLEngine(hostname, port);
} else {
this.sslEngine = sslContext.createSSLEngine();
}
// Allocate buffers for network (encrypted) data
int netBuffersize = this.sslEngine.getSession().getPacketBufferSize();
this.inEncrypted = ByteBuffer.allocate(netBuffersize);
this.outEncrypted = ByteBuffer.allocate(netBuffersize);
// Allocate buffers for application (unencrypted) data
int appBuffersize = this.sslEngine.getSession().getApplicationBufferSize();
this.inPlain = ByteBuffer.allocate(appBuffersize);
this.outPlain = ByteBuffer.allocate(appBuffersize);
}
/**
* @deprecated
*/
@Deprecated
public SSLIOSession(
final IOSession session,
final SSLContext sslContext,
final SSLIOSessionHandler handler) {
this(session, sslContext, handler != null ? new SSLIOSessionHandlerAdaptor(handler) : null);
}
public synchronized void bind(
final SSLMode mode,
final HttpParams params) throws SSLException {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
switch (mode) {
case CLIENT:
this.sslEngine.setUseClientMode(true);
break;
case SERVER:
this.sslEngine.setUseClientMode(false);
break;
}
if (this.handler != null) {
this.handler.initalize(this.sslEngine, params);
}
this.sslEngine.beginHandshake();
doHandshake();
}
private void doHandshake() throws SSLException {
boolean handshaking = true;
SSLEngineResult result = null;
while (handshaking) {
switch (this.sslEngine.getHandshakeStatus()) {
case NEED_WRAP:
// Generate outgoing handshake data
this.outPlain.flip();
result = this.sslEngine.wrap(this.outPlain, this.outEncrypted);
this.outPlain.compact();
if (result.getStatus() != Status.OK) {
handshaking = false;
}
if (result.getStatus() == Status.CLOSED) {
this.status = CLOSED;
}
break;
case NEED_UNWRAP:
// Process incoming handshake data
this.inEncrypted.flip();
result = this.sslEngine.unwrap(this.inEncrypted, this.inPlain);
this.inEncrypted.compact();
if (result.getStatus() != Status.OK) {
handshaking = false;
}
if (result.getStatus() == Status.CLOSED) {
this.status = CLOSED;
}
if (result.getStatus() == Status.BUFFER_UNDERFLOW && this.endOfStream) {
this.status = CLOSED;
}
break;
case NEED_TASK:
Runnable r = this.sslEngine.getDelegatedTask();
r.run();
break;
case NOT_HANDSHAKING:
handshaking = false;
break;
case FINISHED:
break;
}
}
// The SSLEngine has just finished handshaking. This value is only generated by a call
// to SSLEngine.wrap()/unwrap() when that call finishes a handshake.
// It is never generated by SSLEngine.getHandshakeStatus().
if (result != null && result.getHandshakeStatus() == HandshakeStatus.FINISHED) {
if (this.handler != null) {
this.handler.verify(this.session, this.sslEngine.getSession());
}
}
}
private void updateEventMask() {
if (this.sslEngine.isInboundDone() && this.sslEngine.isOutboundDone()) {
this.status = CLOSED;
}
if (this.status == CLOSED) {
this.session.close();
return;
}
// Need to toggle the event mask for this channel?
int oldMask = this.session.getEventMask();
int newMask = oldMask;
switch (this.sslEngine.getHandshakeStatus()) {
case NEED_WRAP:
newMask = EventMask.READ_WRITE;
break;
case NEED_UNWRAP:
newMask = EventMask.READ;
break;
case NOT_HANDSHAKING:
newMask = this.appEventMask;
break;
case NEED_TASK:
break;
case FINISHED:
break;
}
// Do we have encrypted data ready to be sent?
if (this.outEncrypted.position() > 0) {
newMask = newMask | EventMask.WRITE;
}
// Update the mask if necessary
if (oldMask != newMask) {
this.session.setEventMask(newMask);
}
}
private int sendEncryptedData() throws IOException {
this.outEncrypted.flip();
int bytesWritten = this.session.channel().write(this.outEncrypted);
this.outEncrypted.compact();
return bytesWritten;
}
private int receiveEncryptedData() throws IOException {
return this.session.channel().read(this.inEncrypted);
}
private boolean decryptData() throws SSLException {
boolean decrypted = false;
SSLEngineResult.Status opStatus = Status.OK;
while (this.inEncrypted.position() > 0 && opStatus == Status.OK) {
this.inEncrypted.flip();
SSLEngineResult result = this.sslEngine.unwrap(this.inEncrypted, this.inPlain);
this.inEncrypted.compact();
opStatus = result.getStatus();
if (opStatus == Status.CLOSED) {
this.status = CLOSED;
}
if (opStatus == Status.BUFFER_UNDERFLOW && this.endOfStream) {
this.status = CLOSED;
}
if (opStatus == Status.OK) {
decrypted = true;
}
}
return decrypted;
}
public synchronized boolean isAppInputReady() throws IOException {
int bytesRead = receiveEncryptedData();
if (bytesRead == -1) {
this.endOfStream = true;
}
doHandshake();
decryptData();
// Some decrypted data is available or at the end of stream
return (this.appEventMask & SelectionKey.OP_READ) > 0
&& (this.inPlain.position() > 0
|| (this.appBufferStatus != null && this.appBufferStatus.hasBufferedInput())
|| (this.endOfStream && this.status == ACTIVE));
}
/**
* @throws IOException - not thrown currently
*/
public synchronized boolean isAppOutputReady() throws IOException {
return (this.appEventMask & SelectionKey.OP_WRITE) > 0
&& this.status == ACTIVE
&& this.sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING;
}
/**
* @throws IOException - not thrown currently
*/
public synchronized void inboundTransport() throws IOException {
updateEventMask();
}
public synchronized void outboundTransport() throws IOException {
sendEncryptedData();
doHandshake();
updateEventMask();
}
private synchronized int writePlain(final ByteBuffer src) throws SSLException {
if (src == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.status != ACTIVE) {
return -1;
}
if (this.outPlain.position() > 0) {
this.outPlain.flip();
this.sslEngine.wrap(this.outPlain, this.outEncrypted);
this.outPlain.compact();
}
if (this.outPlain.position() == 0) {
SSLEngineResult result = this.sslEngine.wrap(src, this.outEncrypted);
if (result.getStatus() == Status.CLOSED) {
this.status = CLOSED;
}
return result.bytesConsumed();
} else {
return 0;
}
}
/**
* @throws SSLException - not thrown currently
*/
private synchronized int readPlain(final ByteBuffer dst) throws SSLException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.inPlain.position() > 0) {
this.inPlain.flip();
int n = Math.min(this.inPlain.remaining(), dst.remaining());
for (int i = 0; i < n; i++) {
dst.put(this.inPlain.get());
}
this.inPlain.compact();
return n;
} else {
if (this.endOfStream) {
return -1;
} else {
return 0;
}
}
}
public void close() {
if (this.status != ACTIVE) {
return;
}
this.status = CLOSING;
synchronized(this) {
this.sslEngine.closeOutbound();
updateEventMask();
}
}
public void shutdown() {
this.status = CLOSED;
this.session.shutdown();
}
public int getStatus() {
return this.status;
}
public boolean isClosed() {
return this.status != ACTIVE;
}
public synchronized boolean isInboundDone() {
return this.sslEngine.isInboundDone();
}
public synchronized boolean isOutboundDone() {
return this.sslEngine.isOutboundDone();
}
public ByteChannel channel() {
return this.channel;
}
public SocketAddress getLocalAddress() {
return this.session.getLocalAddress();
}
public SocketAddress getRemoteAddress() {
return this.session.getRemoteAddress();
}
public synchronized int getEventMask() {
return this.appEventMask;
}
public synchronized void setEventMask(int ops) {
this.appEventMask = ops;
updateEventMask();
}
public synchronized void setEvent(int op) {
this.appEventMask = this.appEventMask | op;
updateEventMask();
}
public synchronized void clearEvent(int op) {
this.appEventMask = this.appEventMask & ~op;
updateEventMask();
}
public int getSocketTimeout() {
return this.session.getSocketTimeout();
}
public void setSocketTimeout(int timeout) {
this.session.setSocketTimeout(timeout);
}
public synchronized boolean hasBufferedInput() {
return (this.appBufferStatus != null && this.appBufferStatus.hasBufferedInput())
|| this.inEncrypted.position() > 0
|| this.inPlain.position() > 0;
}
public synchronized boolean hasBufferedOutput() {
return (this.appBufferStatus != null && this.appBufferStatus.hasBufferedOutput())
|| this.outEncrypted.position() > 0
|| this.outPlain.position() > 0;
}
public synchronized void setBufferStatus(final SessionBufferStatus status) {
this.appBufferStatus = status;
}
public Object getAttribute(final String name) {
return this.session.getAttribute(name);
}
public Object removeAttribute(final String name) {
return this.session.removeAttribute(name);
}
public void setAttribute(final String name, final Object obj) {
this.session.setAttribute(name, obj);
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(this.session);
buffer.append("[SSL handshake status: ");
buffer.append(this.sslEngine.getHandshakeStatus());
buffer.append("][");
buffer.append(this.inEncrypted.position());
buffer.append("][");
buffer.append(this.inPlain.position());
buffer.append("][");
buffer.append(this.outEncrypted.position());
buffer.append("][");
buffer.append(this.outPlain.position());
buffer.append("]");
return buffer.toString();
}
private class InternalByteChannel implements ByteChannel {
public int write(final ByteBuffer src) throws IOException {
return SSLIOSession.this.writePlain(src);
}
public int read(final ByteBuffer dst) throws IOException {
return SSLIOSession.this.readPlain(dst);
}
public void close() throws IOException {
SSLIOSession.this.close();
}
public boolean isOpen() {
return !SSLIOSession.this.isClosed();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.params.HttpParams;
/**
* Callback interface that can be used to customize various aspects of
* the TLS/SSl protocol.
*
* @since 4.1
*/
public interface SSLSetupHandler {
/**
* Triggered when the SSL connection is being initialized. Custom handlers
* can use this callback to customize properties of the {@link SSLEngine}
* used to establish the SSL session.
*
* @param sslengine the SSL engine.
* @param params HTTP parameters.
* @throws SSLException if case of SSL protocol error.
*/
void initalize(SSLEngine sslengine, HttpParams params)
throws SSLException;
/**
* Triggered when the SSL connection has been established and initial SSL
* handshake has been successfully completed. Custom handlers can use
* this callback to verify properties of the {@link SSLSession}.
* For instance this would be the right place to enforce SSL cipher
* strength, validate certificate chain and do hostname checks.
*
* @param iosession the underlying IOSession for the SSL connection.
* @param sslsession newly created SSL session.
* @throws SSLException if case of SSL protocol error.
*/
void verify(IOSession iosession, SSLSession sslsession)
throws SSLException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.IOSession;
/**
* Session callback interface used internally by I/O reactor implementations.
*
* @since 4.0
*/
public interface SessionClosedCallback {
void sessionClosed(IOSession session);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.InterruptedIOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOSession;
/**
* Default implementation of {@link AbstractIOReactor} that serves as a base
* for more advanced {@link IOReactor} implementations. This class adds
* support for the I/O event dispatching using {@link IOEventDispatch},
* management of buffering sessions, and session timeout handling.
*
* @since 4.0
*/
public class BaseIOReactor extends AbstractIOReactor {
private final long timeoutCheckInterval;
private final Set<IOSession> bufferingSessions;
private long lastTimeoutCheck;
private IOReactorExceptionHandler exceptionHandler = null;
private IOEventDispatch eventDispatch = null;
/**
* Creates new BaseIOReactor instance.
*
* @param selectTimeout the select timeout.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public BaseIOReactor(long selectTimeout) throws IOReactorException {
this(selectTimeout, false);
}
/**
* Creates new BaseIOReactor instance.
*
* @param selectTimeout the select timeout.
* @param interestOpsQueueing Ops queueing flag.
*
* @throws IOReactorException in case if a non-recoverable I/O error.
*
* @since 4.1
*/
public BaseIOReactor(
long selectTimeout, boolean interestOpsQueueing) throws IOReactorException {
super(selectTimeout, interestOpsQueueing);
this.bufferingSessions = new HashSet<IOSession>();
this.timeoutCheckInterval = selectTimeout;
this.lastTimeoutCheck = System.currentTimeMillis();
}
/**
* Activates the I/O reactor. The I/O reactor will start reacting to I/O
* events and dispatch I/O event notifications to the given
* {@link IOEventDispatch}.
*
* @throws InterruptedIOException if the dispatch thread is interrupted.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
this.eventDispatch = eventDispatch;
execute();
}
/**
* Sets exception handler for this I/O reactor.
*
* @param exceptionHandler the exception handler.
*/
public void setExceptionHandler(IOReactorExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
/**
* Handles the given {@link RuntimeException}. This method delegates
* handling of the exception to the {@link IOReactorExceptionHandler},
* if available.
*
* @param ex the runtime exception.
*/
protected void handleRuntimeException(final RuntimeException ex) {
if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) {
throw ex;
}
}
/**
* This I/O reactor implementation does not react to the
* {@link SelectionKey#OP_ACCEPT} event.
* <p>
* Super-classes can override this method to react to the event.
*/
@Override
protected void acceptable(final SelectionKey key) {
}
/**
* This I/O reactor implementation does not react to the
* {@link SelectionKey#OP_CONNECT} event.
* <p>
* Super-classes can override this method to react to the event.
*/
@Override
protected void connectable(final SelectionKey key) {
}
/**
* Processes {@link SelectionKey#OP_READ} event on the given selection key.
* This method dispatches the event notification to the
* {@link IOEventDispatch#inputReady(IOSession)} method.
*/
@Override
protected void readable(final SelectionKey key) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
handle.resetLastRead();
try {
this.eventDispatch.inputReady(session);
if (session.hasBufferedInput()) {
this.bufferingSessions.add(session);
}
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
/**
* Processes {@link SelectionKey#OP_WRITE} event on the given selection key.
* This method dispatches the event notification to the
* {@link IOEventDispatch#outputReady(IOSession)} method.
*/
@Override
protected void writable(final SelectionKey key) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
handle.resetLastWrite();
try {
this.eventDispatch.outputReady(session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
/**
* Verifies whether any of the sessions associated with the given selection
* keys timed out by invoking the {@link #timeoutCheck(SelectionKey, long)}
* method.
* <p>
* This method will also invoke the
* {@link IOEventDispatch#inputReady(IOSession)} method on all sessions
* that have buffered input data.
*/
@Override
protected void validate(final Set<SelectionKey> keys) {
long currentTime = System.currentTimeMillis();
if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) {
this.lastTimeoutCheck = currentTime;
if (keys != null) {
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
SelectionKey key = it.next();
timeoutCheck(key, currentTime);
}
}
}
if (!this.bufferingSessions.isEmpty()) {
for (Iterator<IOSession> it = this.bufferingSessions.iterator(); it.hasNext(); ) {
IOSession session = it.next();
if (!session.hasBufferedInput()) {
it.remove();
continue;
}
int ops = 0;
try {
ops = session.getEventMask();
} catch (CancelledKeyException ex) {
it.remove();
queueClosedSession(session);
continue;
}
if ((ops & EventMask.READ) > 0) {
try {
this.eventDispatch.inputReady(session);
} catch (CancelledKeyException ex) {
it.remove();
queueClosedSession(session);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
if (!session.hasBufferedInput()) {
it.remove();
}
}
}
}
}
/**
* Performs timeout check for the I/O session associated with the given
* selection key.
*/
@Override
protected void timeoutCheck(final SelectionKey key, long now) {
Object attachment = key.attachment();
if (attachment instanceof SessionHandle) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
int timeout = session.getSocketTimeout();
if (timeout > 0) {
if (handle.getLastAccessTime() + timeout < now) {
try {
this.eventDispatch.timeout(session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
}
}
}
/**
* Processes newly created I/O session. This method dispatches the event
* notification to the {@link IOEventDispatch#connected(IOSession)} method.
*/
@Override
protected void sessionCreated(final SelectionKey key, final IOSession session) {
SessionHandle handle = new SessionHandle(session);
key.attach(handle);
try {
this.eventDispatch.connected(session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
@Override
protected IOSession getSession(final SelectionKey key) {
Object attachment = key.attachment();
if (attachment instanceof SessionHandle) {
SessionHandle handle = (SessionHandle) attachment;
return handle.getSession();
} else {
return null;
}
}
/**
* Processes closed I/O session. This method dispatches the event
* notification to the {@link IOEventDispatch#disconnected(IOSession)}
* method.
*/
@Override
protected void sessionClosed(final IOSession session) {
try {
this.eventDispatch.disconnected(session);
} catch (CancelledKeyException ex) {
// ignore
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.nio.channels.SocketChannel;
/**
* {@link SocketChannel} entry maintained by the I/O reactor. If the channel
* represents an outgoing client connection, this entry also contains the
* original {@link SessionRequestImpl} used to request it.
*
* @since 4.0
*/
public class ChannelEntry {
private final SocketChannel channel;
private final SessionRequestImpl sessionRequest;
/**
* Creates new ChannelEntry.
*
* @param channel the channel
* @param sessionRequest original session request. Can be <code>null</code>
* if the channel represents an incoming server-side connection.
*/
public ChannelEntry(final SocketChannel channel, final SessionRequestImpl sessionRequest) {
super();
if (channel == null) {
throw new IllegalArgumentException("Socket channel may not be null");
}
this.channel = channel;
this.sessionRequest = sessionRequest;
}
/**
* Creates new ChannelEntry.
*
* @param channel the channel.
*/
public ChannelEntry(final SocketChannel channel) {
this(channel, null);
}
/**
* Returns the original session request, if available. If the channel
* entry represents an incoming server-side connection, returns
* <code>null</code>.
*
* @return the original session request, if client-side channel,
* <code>null</code> otherwise.
*/
public SessionRequestImpl getSessionRequest() {
return this.sessionRequest;
}
/**
* Returns the original session request attachment, if available.
*
* @return the original session request attachment, if available,
* <code>null</code> otherwise.
*/
public Object getAttachment() {
if (this.sessionRequest != null) {
return this.sessionRequest.getAttachment();
} else {
return null;
}
}
/**
* Returns the channel.
*
* @return the channel.
*/
public SocketChannel getChannel() {
return this.channel;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.IOSession;
/**
* Session handle class used by I/O reactor implementations to keep a reference
* to a {@link IOSession} along with information about time of last I/O
* operations on that session.
*
* @since 4.0
*/
public class SessionHandle {
private final IOSession session;
private final long startedTime;
private long lastReadTime;
private long lastWriteTime;
private long lastAccessTime;
public SessionHandle(final IOSession session) {
super();
if (session == null) {
throw new IllegalArgumentException("Session may not be null");
}
this.session = session;
long now = System.currentTimeMillis();
this.startedTime = now;
this.lastReadTime = now;
this.lastWriteTime = now;
this.lastAccessTime = now;
}
public IOSession getSession() {
return this.session;
}
public long getStartedTime() {
return this.startedTime;
}
public long getLastReadTime() {
return this.lastReadTime;
}
public long getLastWriteTime() {
return this.lastWriteTime;
}
public long getLastAccessTime() {
return this.lastAccessTime;
}
public void resetLastRead() {
long now = System.currentTimeMillis();
this.lastReadTime = now;
this.lastAccessTime = now;
}
public void resetLastWrite() {
long now = System.currentTimeMillis();
this.lastWriteTime = now;
this.lastAccessTime = now;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.protocol.HttpContext;
class SessionHttpContext implements HttpContext {
private final IOSession iosession;
public SessionHttpContext(final IOSession iosession) {
super();
this.iosession = iosession;
}
public Object getAttribute(final String id) {
return this.iosession.getAttribute(id);
}
public Object removeAttribute(final String id) {
return this.iosession.removeAttribute(id);
}
public void setAttribute(final String id, final Object obj) {
this.iosession.setAttribute(id, obj);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.http.ConnectionClosedException;
import org.apache.http.Header;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpInetConnection;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentLengthStrategy;
import org.apache.http.impl.HttpConnectionMetricsImpl;
import org.apache.http.impl.entity.LaxContentLengthStrategy;
import org.apache.http.impl.entity.StrictContentLengthStrategy;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.impl.nio.codecs.ChunkDecoder;
import org.apache.http.impl.nio.codecs.ChunkEncoder;
import org.apache.http.impl.nio.codecs.IdentityDecoder;
import org.apache.http.impl.nio.codecs.IdentityEncoder;
import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder;
import org.apache.http.impl.nio.codecs.LengthDelimitedEncoder;
import org.apache.http.impl.nio.reactor.SessionInputBufferImpl;
import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl;
import org.apache.http.io.HttpTransportMetrics;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
/**
* This class serves as a base for all {@link NHttpConnection} implementations
* and implements functionality common to both client and server
* HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* </ul>
*
* @since 4.0
*/
public class NHttpConnectionBase
implements NHttpConnection, HttpInetConnection, SessionBufferStatus {
protected final ContentLengthStrategy incomingContentStrategy;
protected final ContentLengthStrategy outgoingContentStrategy;
protected final SessionInputBufferImpl inbuf;
protected final SessionOutputBufferImpl outbuf;
protected final HttpTransportMetricsImpl inTransportMetrics;
protected final HttpTransportMetricsImpl outTransportMetrics;
protected final HttpConnectionMetricsImpl connMetrics;
protected HttpContext context;
protected IOSession session;
protected SocketAddress remote;
protected volatile ContentDecoder contentDecoder;
protected volatile boolean hasBufferedInput;
protected volatile ContentEncoder contentEncoder;
protected volatile boolean hasBufferedOutput;
protected volatile HttpRequest request;
protected volatile HttpResponse response;
protected volatile int status;
/**
* Creates a new instance of this class given the underlying I/O session.
*
* @param session the underlying I/O session.
* @param allocator byte buffer allocator.
* @param params HTTP parameters.
*/
public NHttpConnectionBase(
final IOSession session,
final ByteBufferAllocator allocator,
final HttpParams params) {
super();
if (session == null) {
throw new IllegalArgumentException("I/O session may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP params may not be null");
}
int buffersize = HttpConnectionParams.getSocketBufferSize(params);
int linebuffersize = buffersize;
if (linebuffersize > 512) {
linebuffersize = 512;
}
this.inbuf = new SessionInputBufferImpl(buffersize, linebuffersize, allocator, params);
this.outbuf = new SessionOutputBufferImpl(buffersize, linebuffersize, allocator, params);
this.incomingContentStrategy = new LaxContentLengthStrategy();
this.outgoingContentStrategy = new StrictContentLengthStrategy();
this.inTransportMetrics = createTransportMetrics();
this.outTransportMetrics = createTransportMetrics();
this.connMetrics = createConnectionMetrics(
this.inTransportMetrics,
this.outTransportMetrics);
setSession(session);
this.status = ACTIVE;
}
private void setSession(final IOSession session) {
this.session = session;
this.context = new SessionHttpContext(this.session);
this.session.setBufferStatus(this);
this.remote = this.session.getRemoteAddress();
}
/**
* @since 4.1
*/
protected HttpTransportMetricsImpl createTransportMetrics() {
return new HttpTransportMetricsImpl();
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
public int getStatus() {
return this.status;
}
public HttpContext getContext() {
return this.context;
}
public HttpRequest getHttpRequest() {
return this.request;
}
public HttpResponse getHttpResponse() {
return this.response;
}
public void requestInput() {
this.session.setEvent(EventMask.READ);
}
public void requestOutput() {
this.session.setEvent(EventMask.WRITE);
}
public void suspendInput() {
this.session.clearEvent(EventMask.READ);
}
public void suspendOutput() {
this.session.clearEvent(EventMask.WRITE);
}
/**
* Initializes a specific {@link ContentDecoder} implementation based on the
* properties of the given {@link HttpMessage} and generates an instance of
* {@link HttpEntity} matching the properties of the content decoder.
*
* @param message the HTTP message.
* @return HTTP entity.
* @throws HttpException in case of an HTTP protocol violation.
*/
protected HttpEntity prepareDecoder(final HttpMessage message) throws HttpException {
BasicHttpEntity entity = new BasicHttpEntity();
long len = this.incomingContentStrategy.determineLength(message);
this.contentDecoder = createContentDecoder(
len,
this.session.channel(),
this.inbuf,
this.inTransportMetrics);
if (len == ContentLengthStrategy.CHUNKED) {
entity.setChunked(true);
entity.setContentLength(-1);
} else if (len == ContentLengthStrategy.IDENTITY) {
entity.setChunked(false);
entity.setContentLength(-1);
} else {
entity.setChunked(false);
entity.setContentLength(len);
}
Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE);
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader);
}
Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING);
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader);
}
return entity;
}
/**
* Factory method for {@link ContentDecoder} instances.
*
* @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or
* {@link ContentLengthStrategy#IDENTITY}, if unknown.
* @param channel the session channel.
* @param buffer the session buffer.
* @param metrics transport metrics.
*
* @return content decoder.
*
* @since 4.1
*/
protected ContentDecoder createContentDecoder(
final long len,
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
if (len == ContentLengthStrategy.CHUNKED) {
return new ChunkDecoder(channel, buffer, metrics);
} else if (len == ContentLengthStrategy.IDENTITY) {
return new IdentityDecoder(channel, buffer, metrics);
} else {
return new LengthDelimitedDecoder(channel, buffer, metrics, len);
}
}
/**
* Initializes a specific {@link ContentEncoder} implementation based on the
* properties of the given {@link HttpMessage}.
*
* @param message the HTTP message.
* @throws HttpException in case of an HTTP protocol violation.
*/
protected void prepareEncoder(final HttpMessage message) throws HttpException {
long len = this.outgoingContentStrategy.determineLength(message);
this.contentEncoder = createContentEncoder(
len,
this.session.channel(),
this.outbuf,
this.outTransportMetrics);
}
/**
* Factory method for {@link ContentEncoder} instances.
*
* @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or
* {@link ContentLengthStrategy#IDENTITY}, if unknown.
* @param channel the session channel.
* @param buffer the session buffer.
* @param metrics transport metrics.
*
* @return content encoder.
*
* @since 4.1
*/
protected ContentEncoder createContentEncoder(
final long len,
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
if (len == ContentLengthStrategy.CHUNKED) {
return new ChunkEncoder(channel, buffer, metrics);
} else if (len == ContentLengthStrategy.IDENTITY) {
return new IdentityEncoder(channel, buffer, metrics);
} else {
return new LengthDelimitedEncoder(channel, buffer, metrics, len);
}
}
public boolean hasBufferedInput() {
return this.hasBufferedInput;
}
public boolean hasBufferedOutput() {
return this.hasBufferedOutput;
}
/**
* Assets if the connection is still open.
*
* @throws ConnectionClosedException in case the connection has already
* been closed.
*/
protected void assertNotClosed() throws ConnectionClosedException {
if (this.status != ACTIVE) {
throw new ConnectionClosedException("Connection is closed");
}
}
public void close() throws IOException {
if (this.status != ACTIVE) {
return;
}
this.status = CLOSING;
if (this.outbuf.hasData()) {
this.session.setEvent(EventMask.WRITE);
} else {
this.session.close();
this.status = CLOSED;
}
}
public boolean isOpen() {
return this.status == ACTIVE && !this.session.isClosed();
}
public boolean isStale() {
return this.session.isClosed();
}
public InetAddress getLocalAddress() {
SocketAddress address = this.session.getLocalAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getAddress();
} else {
return null;
}
}
public int getLocalPort() {
SocketAddress address = this.session.getLocalAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getPort();
} else {
return -1;
}
}
public InetAddress getRemoteAddress() {
SocketAddress address = this.session.getRemoteAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getAddress();
} else {
return null;
}
}
public int getRemotePort() {
SocketAddress address = this.session.getRemoteAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getPort();
} else {
return -1;
}
}
public void setSocketTimeout(int timeout) {
this.session.setSocketTimeout(timeout);
}
public int getSocketTimeout() {
return this.session.getSocketTimeout();
}
public void shutdown() throws IOException {
this.status = CLOSED;
this.session.shutdown();
}
public HttpConnectionMetrics getMetrics() {
return this.connMetrics;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
buffer.append(this.remote);
if (this.status == CLOSED) {
buffer.append("(closed)");
}
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) server-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch}
*/
@Deprecated
public class SSLServerIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "SSL_SESSION";
protected final NHttpServiceHandler handler;
protected final SSLContext sslcontext;
protected final SSLIOSessionHandler sslHandler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* by HTTP connections for creating {@link HttpRequest} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link DefaultNHttpServerConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpServerIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new DefaultNHttpServerConnection(
session,
createHttpRequestFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpServerIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
this.handler.connected(conn);
try {
sslSession.bind(SSLMode.SERVER, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
public void inputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to cleanly terminate
sslSession.shutdown();
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.ssl;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.impl.nio.DefaultNHttpServerConnection;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.impl.nio.reactor.SSLSetupHandler;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) server-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class SSLServerIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "http.nio.ssl-session";
private final NHttpServiceHandler handler;
private final SSLContext sslcontext;
private final SSLSetupHandler sslHandler;
private final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* by HTTP connections for creating {@link HttpRequest} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link DefaultNHttpServerConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpServerIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new DefaultNHttpServerConnection(
session,
createHttpRequestFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpServerIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
this.handler.connected(conn);
try {
sslSession.bind(SSLMode.SERVER, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpServerIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
private void ensureNotNull(final SSLIOSession ssliosession) {
if (ssliosession == null) {
throw new IllegalStateException("SSL I/O session is null");
}
}
public void inputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to cleanly terminate
sslSession.shutdown();
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.ssl;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultNHttpClientConnection;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.impl.nio.reactor.SSLSetupHandler;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) client-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class SSLClientIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "http.nio.ssl-session";
private final NHttpClientHandler handler;
private final SSLContext sslcontext;
private final SSLSetupHandler sslHandler;
private final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* by HTTP connections for creating {@link HttpResponse} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link DefaultNHttpClientConnection} based on the
* given SSL {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpClientIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new DefaultNHttpClientConnection(
session,
createHttpResponseFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpClientIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
this.handler.connected(conn, attachment);
try {
sslSession.bind(SSLMode.CLIENT, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpClientIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
private void ensureNotNull(final SSLIOSession ssliosession) {
if (ssliosession == null) {
throw new IllegalStateException("SSL I/O session is null");
}
}
public void inputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to terminate cleanly
sslSession.shutdown();
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.codecs.DefaultHttpRequestParser;
import org.apache.http.impl.nio.codecs.DefaultHttpResponseWriter;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
/**
* Default implementation of the {@link NHttpServerConnection} interface.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultNHttpServerConnection
extends NHttpConnectionBase implements NHttpServerIOTarget {
protected final NHttpMessageParser<HttpRequest> requestParser;
protected final NHttpMessageWriter<HttpResponse> responseWriter;
/**
* Creates a new instance of this class given the underlying I/O session.
*
* @param session the underlying I/O session.
* @param requestFactory HTTP request factory.
* @param allocator byte buffer allocator.
* @param params HTTP parameters.
*/
public DefaultNHttpServerConnection(
final IOSession session,
final HttpRequestFactory requestFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(session, allocator, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestParser = createRequestParser(this.inbuf, requestFactory, params);
this.responseWriter = createResponseWriter(this.outbuf, params);
}
/**
* Creates an instance of {@link NHttpMessageParser} to be used
* by this connection for parsing incoming {@link HttpRequest} messages.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpMessageParser} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageParser<HttpRequest> createRequestParser(
final SessionInputBuffer buffer,
final HttpRequestFactory requestFactory,
final HttpParams params) {
// override in derived class to specify a line parser
return new DefaultHttpRequestParser(buffer, null, requestFactory, params);
}
/**
* Creates an instance of {@link NHttpMessageWriter} to be used
* by this connection for writing out outgoing {@link HttpResponse}
* messages.
* <p>
* This method can be overridden by a super class in order to provide
* a different implementation of the {@link NHttpMessageWriter} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageWriter<HttpResponse> createResponseWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
// override in derived class to specify a line formatter
return new DefaultHttpResponseWriter(buffer, null, params);
}
public void resetInput() {
this.request = null;
this.contentDecoder = null;
this.requestParser.reset();
}
public void resetOutput() {
this.response = null;
this.contentEncoder = null;
this.responseWriter.reset();
}
public void consumeInput(final NHttpServiceHandler handler) {
if (this.status != ACTIVE) {
this.session.clearEvent(EventMask.READ);
return;
}
try {
if (this.request == null) {
int bytesRead;
do {
bytesRead = this.requestParser.fillBuffer(this.session.channel());
if (bytesRead > 0) {
this.inTransportMetrics.incrementBytesTransferred(bytesRead);
}
this.request = this.requestParser.parse();
} while (bytesRead > 0 && this.request == null);
if (this.request != null) {
if (this.request instanceof HttpEntityEnclosingRequest) {
// Receive incoming entity
HttpEntity entity = prepareDecoder(this.request);
((HttpEntityEnclosingRequest)this.request).setEntity(entity);
}
this.connMetrics.incrementRequestCount();
handler.requestReceived(this);
if (this.contentDecoder == null) {
// No request entity is expected
// Ready to receive a new request
resetInput();
}
}
if (bytesRead == -1) {
close();
}
}
if (this.contentDecoder != null) {
handler.inputReady(this, this.contentDecoder);
if (this.contentDecoder.isCompleted()) {
// Request entity received
// Ready to receive a new request
resetInput();
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} catch (HttpException ex) {
resetInput();
handler.exception(this, ex);
} finally {
// Finally set buffered input flag
this.hasBufferedInput = this.inbuf.hasData();
}
}
public void produceOutput(final NHttpServiceHandler handler) {
try {
if (this.outbuf.hasData()) {
int bytesWritten = this.outbuf.flush(this.session.channel());
if (bytesWritten > 0) {
this.outTransportMetrics.incrementBytesTransferred(bytesWritten);
}
}
if (!this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
resetOutput();
return;
} else {
if (this.contentEncoder != null) {
handler.outputReady(this, this.contentEncoder);
if (this.contentEncoder.isCompleted()) {
resetOutput();
}
}
}
if (this.contentEncoder == null && !this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
}
if (this.status != CLOSED) {
this.session.clearEvent(EventMask.WRITE);
handler.responseReady(this);
}
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} finally {
// Finally set the buffered output flag
this.hasBufferedOutput = this.outbuf.hasData();
}
}
public void submitResponse(final HttpResponse response) throws IOException, HttpException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertNotClosed();
if (this.response != null) {
throw new HttpException("Response already submitted");
}
this.responseWriter.write(response);
this.hasBufferedOutput = this.outbuf.hasData();
if (response.getStatusLine().getStatusCode() >= 200) {
this.connMetrics.incrementResponseCount();
if (response.getEntity() != null) {
this.response = response;
prepareEncoder(response);
}
}
this.session.setEvent(EventMask.WRITE);
}
public boolean isResponseSubmitted() {
return this.response != null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for plain
* (unencrypted) server-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultServerIOEventDispatch implements IOEventDispatch {
protected final ByteBufferAllocator allocator;
protected final NHttpServiceHandler handler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler.
*
* @param handler the server protocol handler.
* @param params HTTP parameters.
*/
public DefaultServerIOEventDispatch(
final NHttpServiceHandler handler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.allocator = createByteBufferAllocator();
this.handler = handler;
this.params = params;
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* by HTTP connections for creating {@link HttpRequest} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link DefaultNHttpServerConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpServerIOTarget} interface.
*
* @param session the underlying I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new DefaultNHttpServerConnection(
session,
createHttpRequestFactory(),
this.allocator,
this.params);
}
public void connected(final IOSession session) {
NHttpServerIOTarget conn = createConnection(session);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.handler.connected(conn);
}
public void disconnected(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpServerIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
public void inputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.consumeInput(this.handler);
}
public void outputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.produceOutput(this.handler);
}
public void timeout(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
this.handler.timeout(conn);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for plain
* (unencrypted) client-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultClientIOEventDispatch implements IOEventDispatch {
protected final ByteBufferAllocator allocator;
protected final NHttpClientHandler handler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler.
*
* @param handler the client protocol handler.
* @param params HTTP parameters.
*/
public DefaultClientIOEventDispatch(
final NHttpClientHandler handler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.allocator = createByteBufferAllocator();
this.handler = handler;
this.params = params;
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* by HTTP connections for creating {@link HttpResponse} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link DefaultNHttpClientConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpClientIOTarget} interface.
*
* @param session the underlying I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new DefaultNHttpClientConnection(
session,
createHttpResponseFactory(),
this.allocator,
this.params);
}
public void connected(final IOSession session) {
NHttpClientIOTarget conn = createConnection(session);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.handler.connected(conn, attachment);
}
public void disconnected(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpClientIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
public void inputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.consumeInput(this.handler);
}
public void outputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.produceOutput(this.handler);
}
public void timeout(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
this.handler.timeout(conn);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) client-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch}
*/
@Deprecated
public class SSLClientIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "SSL_SESSION";
protected final NHttpClientHandler handler;
protected final SSLContext sslcontext;
protected final SSLIOSessionHandler sslHandler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* by HTTP connections for creating {@link HttpResponse} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link DefaultNHttpClientConnection} based on the
* given SSL {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpClientIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new DefaultNHttpClientConnection(
session,
createHttpResponseFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpClientIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
this.handler.connected(conn, attachment);
try {
sslSession.bind(SSLMode.CLIENT, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
public void inputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to terminate cleanly
sslSession.shutdown();
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.nio.codecs.DefaultHttpRequestWriter;
import org.apache.http.impl.nio.codecs.DefaultHttpResponseParser;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
/**
* Default implementation of the {@link NHttpClientConnection} interface.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultNHttpClientConnection
extends NHttpConnectionBase implements NHttpClientIOTarget {
protected final NHttpMessageParser<HttpResponse> responseParser;
protected final NHttpMessageWriter<HttpRequest> requestWriter;
/**
* Creates a new instance of this class given the underlying I/O session.
*
* @param session the underlying I/O session.
* @param responseFactory HTTP response factory.
* @param allocator byte buffer allocator.
* @param params HTTP parameters.
*/
public DefaultNHttpClientConnection(
final IOSession session,
final HttpResponseFactory responseFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(session, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseParser = createResponseParser(this.inbuf, responseFactory, params);
this.requestWriter = createRequestWriter(this.outbuf, params);
this.hasBufferedInput = false;
this.hasBufferedOutput = false;
this.session.setBufferStatus(this);
}
/**
* Creates an instance of {@link NHttpMessageParser} to be used
* by this connection for parsing incoming {@link HttpResponse} messages.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpMessageParser} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
// override in derived class to specify a line parser
return new DefaultHttpResponseParser(buffer, null, responseFactory, params);
}
/**
* Creates an instance of {@link NHttpMessageWriter} to be used
* by this connection for writing out outgoing {@link HttpRequest} messages.
* <p>
* This method can be overridden by a super class in order to provide
* a different implementation of the {@link NHttpMessageWriter} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageWriter<HttpRequest> createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
// override in derived class to specify a line formatter
return new DefaultHttpRequestWriter(buffer, null, params);
}
public void resetInput() {
this.response = null;
this.contentDecoder = null;
this.responseParser.reset();
}
public void resetOutput() {
this.request = null;
this.contentEncoder = null;
this.requestWriter.reset();
}
public void consumeInput(final NHttpClientHandler handler) {
if (this.status != ACTIVE) {
this.session.clearEvent(EventMask.READ);
return;
}
try {
if (this.response == null) {
int bytesRead;
do {
bytesRead = this.responseParser.fillBuffer(this.session.channel());
if (bytesRead > 0) {
this.inTransportMetrics.incrementBytesTransferred(bytesRead);
}
this.response = this.responseParser.parse();
} while (bytesRead > 0 && this.response == null);
if (this.response != null) {
if (this.response.getStatusLine().getStatusCode() >= 200) {
HttpEntity entity = prepareDecoder(this.response);
this.response.setEntity(entity);
this.connMetrics.incrementResponseCount();
}
handler.responseReceived(this);
if (this.contentDecoder == null) {
resetInput();
}
}
if (bytesRead == -1) {
close();
}
}
if (this.contentDecoder != null) {
handler.inputReady(this, this.contentDecoder);
if (this.contentDecoder.isCompleted()) {
// Response entity received
// Ready to receive a new response
resetInput();
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} catch (HttpException ex) {
resetInput();
handler.exception(this, ex);
} finally {
// Finally set buffered input flag
this.hasBufferedInput = this.inbuf.hasData();
}
}
public void produceOutput(final NHttpClientHandler handler) {
try {
if (this.outbuf.hasData()) {
int bytesWritten = this.outbuf.flush(this.session.channel());
if (bytesWritten > 0) {
this.outTransportMetrics.incrementBytesTransferred(bytesWritten);
}
}
if (!this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
resetOutput();
return;
} else {
if (this.contentEncoder != null) {
handler.outputReady(this, this.contentEncoder);
if (this.contentEncoder.isCompleted()) {
resetOutput();
}
}
}
if (this.contentEncoder == null && !this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
}
if (this.status != CLOSED) {
this.session.clearEvent(EventMask.WRITE);
handler.requestReady(this);
}
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} finally {
// Finally set buffered output flag
this.hasBufferedOutput = this.outbuf.hasData();
}
}
public void submitRequest(final HttpRequest request) throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertNotClosed();
if (this.request != null) {
throw new HttpException("Request already submitted");
}
this.requestWriter.write(request);
this.hasBufferedOutput = this.outbuf.hasData();
if (request instanceof HttpEntityEnclosingRequest
&& ((HttpEntityEnclosingRequest) request).getEntity() != null) {
prepareEncoder(request);
this.request = request;
}
this.connMetrics.incrementRequestCount();
this.session.setEvent(EventMask.WRITE);
}
public boolean isRequestSubmitted() {
return this.request != null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.util.Iterator;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.message.LineFormatter;
import org.apache.http.message.BasicLineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Abstract {@link NHttpMessageWriter} that serves as a base for all message
* writer implementations.
*
* @since 4.0
*/
public abstract class AbstractMessageWriter<T extends HttpMessage> implements NHttpMessageWriter<T> {
protected final SessionOutputBuffer sessionBuffer;
protected final CharArrayBuffer lineBuf;
protected final LineFormatter lineFormatter;
/**
* Creates an instance of this class.
*
* @param buffer the session output buffer.
* @param formatter the line formatter.
* @param params HTTP parameters.
*/
public AbstractMessageWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.sessionBuffer = buffer;
this.lineBuf = new CharArrayBuffer(64);
this.lineFormatter = (formatter != null) ?
formatter : BasicLineFormatter.DEFAULT;
}
public void reset() {
}
/**
* Writes out the first line of {@link HttpMessage}.
*
* @param message HTTP message.
* @throws HttpException in case of HTTP protocol violation
*/
protected abstract void writeHeadLine(T message) throws IOException;
public void write(final T message) throws IOException, HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
writeHeadLine(message);
for (Iterator<?> it = message.headerIterator(); it.hasNext(); ) {
Header header = (Header) it.next();
this.sessionBuffer.writeLine
(lineFormatter.formatHeader(this.lineBuf, header));
}
this.lineBuf.clear();
this.sessionBuffer.writeLine(this.lineBuf);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpRequest}s.
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpRequestWriter}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpRequestWriter extends AbstractMessageWriter {
public HttpRequestWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpMessage message)
throws IOException {
final CharArrayBuffer buffer = lineFormatter.formatRequestLine
(this.lineBuf, ((HttpRequest) message).getRequestLine());
this.sessionBuffer.writeLine(buffer);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.StatusLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpResponse}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpResponseParser}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpResponseParser extends AbstractMessageParser {
private final HttpResponseFactory responseFactory;
public HttpResponseParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpResponseFactory responseFactory,
final HttpParams params) {
super(buffer, parser, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
@Override
protected HttpMessage createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
StatusLine statusline = lineParser.parseStatusLine(buffer, cursor);
return this.responseFactory.newHttpResponse(statusline, null);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.MalformedChunkCodingException;
import org.apache.http.TruncatedChunkException;
import org.apache.http.message.BufferedHeader;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.ParseException;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
/**
* Implements chunked transfer coding. The content is received in small chunks.
* Entities transferred using this encoder can be of unlimited length.
*
* @since 4.0
*/
public class ChunkDecoder extends AbstractContentDecoder {
private static final int READ_CONTENT = 0;
private static final int READ_FOOTERS = 1;
private static final int COMPLETED = 2;
private int state;
private boolean endOfChunk;
private boolean endOfStream;
private CharArrayBuffer lineBuf;
private int chunkSize;
private int pos;
private final List<CharArrayBuffer> trailerBufs;
private Header[] footers;
public ChunkDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
this.state = READ_CONTENT;
this.chunkSize = -1;
this.pos = 0;
this.endOfChunk = false;
this.endOfStream = false;
this.trailerBufs = new ArrayList<CharArrayBuffer>();
}
private void readChunkHead() throws IOException {
if (this.endOfChunk) {
if (this.buffer.length() < 2) {
return;
}
int cr = this.buffer.read();
int lf = this.buffer.read();
if (cr != HTTP.CR || lf != HTTP.LF) {
throw new MalformedChunkCodingException("CRLF expected at end of chunk");
}
this.endOfChunk = false;
}
if (this.lineBuf == null) {
this.lineBuf = new CharArrayBuffer(32);
} else {
this.lineBuf.clear();
}
if (this.buffer.readLine(this.lineBuf, this.endOfStream)) {
int separator = this.lineBuf.indexOf(';');
if (separator < 0) {
separator = this.lineBuf.length();
}
try {
String s = this.lineBuf.substringTrimmed(0, separator);
this.chunkSize = Integer.parseInt(s, 16);
} catch (NumberFormatException e) {
throw new MalformedChunkCodingException("Bad chunk header");
}
this.pos = 0;
}
}
private void parseHeader() {
CharArrayBuffer current = this.lineBuf;
int count = this.trailerBufs.size();
if ((this.lineBuf.charAt(0) == ' ' || this.lineBuf.charAt(0) == '\t') && count > 0) {
// Handle folded header line
CharArrayBuffer previous = this.trailerBufs.get(count - 1);
int i = 0;
while (i < current.length()) {
char ch = current.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
previous.append(' ');
previous.append(current, i, current.length() - i);
} else {
this.trailerBufs.add(current);
this.lineBuf = null;
}
}
private void processFooters() throws IOException {
int count = this.trailerBufs.size();
if (count > 0) {
this.footers = new Header[this.trailerBufs.size()];
for (int i = 0; i < this.trailerBufs.size(); i++) {
CharArrayBuffer buffer = this.trailerBufs.get(i);
try {
this.footers[i] = new BufferedHeader(buffer);
} catch (ParseException ex) {
throw new IOException(ex.getMessage());
}
}
}
this.trailerBufs.clear();
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.state == COMPLETED) {
return -1;
}
int totalRead = 0;
while (this.state != COMPLETED) {
if (!this.buffer.hasData() || this.chunkSize == -1) {
int bytesRead = this.buffer.fill(this.channel);
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
if (bytesRead == -1) {
this.endOfStream = true;
}
}
switch (this.state) {
case READ_CONTENT:
if (this.chunkSize == -1) {
readChunkHead();
if (this.chunkSize == -1) {
// Unable to read a chunk head
if (this.endOfStream) {
this.state = COMPLETED;
this.completed = true;
}
return totalRead;
}
if (this.chunkSize == 0) {
// Last chunk. Read footers
this.chunkSize = -1;
this.state = READ_FOOTERS;
break;
}
}
int maxLen = this.chunkSize - this.pos;
int len = this.buffer.read(dst, maxLen);
if (len > 0) {
this.pos += len;
totalRead += len;
} else {
if (!this.buffer.hasData() && this.endOfStream) {
this.state = COMPLETED;
this.completed = true;
throw new TruncatedChunkException("Truncated chunk "
+ "( expected size: " + this.chunkSize
+ "; actual size: " + this.pos + ")");
}
}
if (this.pos == this.chunkSize) {
// At the end of the chunk
this.chunkSize = -1;
this.pos = 0;
this.endOfChunk = true;
break;
}
return totalRead;
case READ_FOOTERS:
if (this.lineBuf == null) {
this.lineBuf = new CharArrayBuffer(32);
} else {
this.lineBuf.clear();
}
if (!this.buffer.readLine(this.lineBuf, this.endOfStream)) {
// Unable to read a footer
if (this.endOfStream) {
this.state = COMPLETED;
this.completed = true;
}
return totalRead;
}
if (this.lineBuf.length() > 0) {
parseHeader();
} else {
this.state = COMPLETED;
this.completed = true;
processFooters();
}
break;
}
}
return totalRead;
}
public Header[] getFooters() {
if (this.footers != null) {
return this.footers.clone();
} else {
return new Header[] {};
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[chunk-coded; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpResponse}s.
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpResponseWriter}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpResponseWriter extends AbstractMessageWriter {
public HttpResponseWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpMessage message)
throws IOException {
final CharArrayBuffer buffer = lineFormatter.formatStatusLine
(this.lineBuf, ((HttpResponse) message).getStatusLine());
this.sessionBuffer.writeLine(buffer);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.ConnectionClosedException;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentDecoder;
import org.apache.http.nio.reactor.SessionInputBuffer;
/**
* Content decoder that cuts off after a defined number of bytes. This class
* is used to receive content of HTTP messages where the end of the content
* entity is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* This decoder is optimized to transfer data directly from the underlying
* I/O session's channel to a {@link FileChannel}, whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class LengthDelimitedDecoder extends AbstractContentDecoder
implements FileContentDecoder {
private final long contentLength;
private long len;
public LengthDelimitedDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics,
long contentLength) {
super(channel, buffer, metrics);
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.contentLength = contentLength;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
int bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(chunk, this.buffer.length());
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (dst.remaining() > chunk) {
int oldLimit = dst.limit();
int newLimit = oldLimit - (dst.remaining() - chunk);
dst.limit(newLimit);
bytesRead = this.channel.read(dst);
dst.limit(oldLimit);
} else {
bytesRead = this.channel.read(dst);
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
if (this.len < this.contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ this.contentLength + "; received: " + this.len);
}
}
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
if (this.completed && bytesRead == 0) {
return -1;
} else {
return bytesRead;
}
}
public long transfer(
final FileChannel dst,
long position,
long count) throws IOException {
if (dst == null) {
return 0;
}
if (this.completed) {
return -1;
}
int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
long bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(chunk, this.buffer.length());
dst.position(position);
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (count > chunk) {
count = chunk;
}
if (this.channel.isOpen()) {
if(dst.size() < position)
throw new IOException("FileChannel.size() [" + dst.size() +
"] < position [" + position +
"]. Please grow the file before writing.");
bytesRead = dst.transferFrom(this.channel, position, count);
} else {
bytesRead = -1;
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
if (this.len < this.contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ this.contentLength + "; received: " + this.len);
}
}
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesRead;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[content length: ");
buffer.append(this.contentLength);
buffer.append("; pos: ");
buffer.append(this.len);
buffer.append("; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
/**
* Abstract {@link ContentDecoder} that serves as a base for all content
* decoder implementations.
*
* @since 4.0
*/
public abstract class AbstractContentDecoder implements ContentDecoder {
protected final ReadableByteChannel channel;
protected final SessionInputBuffer buffer;
protected final HttpTransportMetricsImpl metrics;
protected boolean completed;
/**
* Creates an instance of this class.
*
* @param channel the source channel.
* @param buffer the session input buffer that can be used to store
* session data for intermediate processing.
* @param metrics Transport metrics of the underlying HTTP transport.
*/
public AbstractContentDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super();
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (metrics == null) {
throw new IllegalArgumentException("Transport metrics may not be null");
}
this.buffer = buffer;
this.channel = channel;
this.metrics = metrics;
}
public boolean isCompleted() {
return this.completed;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpRequest}s.
*
* @since 4.1
*/
public class DefaultHttpRequestWriter extends AbstractMessageWriter<HttpRequest> {
public DefaultHttpRequestWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpRequest message) throws IOException {
CharArrayBuffer buffer = lineFormatter.formatRequestLine(
this.lineBuf, message.getRequestLine());
this.sessionBuffer.writeLine(buffer);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.RequestLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpRequest}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class DefaultHttpRequestParser extends AbstractMessageParser<HttpRequest> {
private final HttpRequestFactory requestFactory;
public DefaultHttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
}
@Override
protected HttpRequest createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
RequestLine requestLine = lineParser.parseRequestLine(buffer, cursor);
return this.requestFactory.newHttpRequest(requestLine);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.io.BufferInfo;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.util.CharArrayBuffer;
/**
* Implements chunked transfer coding. The content is sent in small chunks.
* Entities transferred using this decoder can be of unlimited length.
*
* @since 4.0
*/
public class ChunkEncoder extends AbstractContentEncoder {
private final CharArrayBuffer lineBuffer;
private final BufferInfo bufferinfo;
public ChunkEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
this.lineBuffer = new CharArrayBuffer(16);
if (buffer instanceof BufferInfo) {
this.bufferinfo = (BufferInfo) buffer;
} else {
this.bufferinfo = null;
}
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int chunk = src.remaining();
if (chunk == 0) {
return 0;
}
long bytesWritten = this.buffer.flush(this.channel);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
int avail;
if (this.bufferinfo != null) {
avail = this.bufferinfo.available();
} else {
avail = 4096;
}
// subtract the length of the longest chunk header
// 12345678\r\n
// <chunk-data>\r\n
avail -= 12;
if (avail <= 0) {
return 0;
} else if (avail < chunk) {
// write no more than 'avail' bytes
chunk = avail;
this.lineBuffer.clear();
this.lineBuffer.append(Integer.toHexString(chunk));
this.buffer.writeLine(this.lineBuffer);
int oldlimit = src.limit();
src.limit(src.position() + chunk);
this.buffer.write(src);
src.limit(oldlimit);
} else {
// write all
this.lineBuffer.clear();
this.lineBuffer.append(Integer.toHexString(chunk));
this.buffer.writeLine(this.lineBuffer);
this.buffer.write(src);
}
this.lineBuffer.clear();
this.buffer.writeLine(this.lineBuffer);
return chunk;
}
@Override
public void complete() throws IOException {
assertNotCompleted();
this.lineBuffer.clear();
this.lineBuffer.append("0");
this.buffer.writeLine(this.lineBuffer);
this.lineBuffer.clear();
this.buffer.writeLine(this.lineBuffer);
this.completed = true; // == super.complete()
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[chunk-coded; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.RequestLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpRequest}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpRequestParser}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpRequestParser extends AbstractMessageParser {
private final HttpRequestFactory requestFactory;
public HttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
}
@Override
protected HttpMessage createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
RequestLine requestLine = lineParser.parseRequestLine(buffer, cursor);
return this.requestFactory.newHttpRequest(requestLine);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.StatusLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpResponse}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class DefaultHttpResponseParser extends AbstractMessageParser<HttpResponse> {
private final HttpResponseFactory responseFactory;
public DefaultHttpResponseParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpResponseFactory responseFactory,
final HttpParams params) {
super(buffer, parser, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
@Override
protected HttpResponse createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
StatusLine statusline = lineParser.parseStatusLine(buffer, cursor);
return this.responseFactory.newHttpResponse(statusline, null);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentDecoder;
import org.apache.http.nio.reactor.SessionInputBuffer;
/**
* Content decoder that reads data without any transformation. The end of the
* content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* This decoder is optimized to transfer data directly from the underlying
* I/O session's channel to a {@link FileChannel}, whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class IdentityDecoder extends AbstractContentDecoder
implements FileContentDecoder {
public IdentityDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
/**
* Sets the completed status of this decoder. Normally this is not necessary
* (the decoder will automatically complete when the underlying channel
* returns EOF). It is useful to mark the decoder as completed if you have
* some other means to know all the necessary data has been read and want to
* reuse the underlying connection for more messages.
*/
public void setCompleted(boolean completed) {
this.completed = completed;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int bytesRead;
if (this.buffer.hasData()) {
bytesRead = this.buffer.read(dst);
} else {
bytesRead = this.channel.read(dst);
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
public long transfer(
final FileChannel dst,
long position,
long count) throws IOException {
if (dst == null) {
return 0;
}
if (this.completed) {
return 0;
}
long bytesRead;
if (this.buffer.hasData()) {
dst.position(position);
bytesRead = this.buffer.read(dst);
} else {
if (this.channel.isOpen()) {
if(dst.size() < position)
throw new IOException("FileChannel.size() [" + dst.size() +
"] < position [" + position +
"]. Please grow the file before writing.");
bytesRead = dst.transferFrom(this.channel, position, count);
if (bytesRead == 0) {
bytesRead = buffer.fill(this.channel);
}
} else {
bytesRead = -1;
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[identity; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpResponse}s.
*
* @since 4.1
*/
public class DefaultHttpResponseWriter extends AbstractMessageWriter<HttpResponse> {
public DefaultHttpResponseWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpResponse message) throws IOException {
CharArrayBuffer buffer = lineFormatter.formatStatusLine(
this.lineBuf, message.getStatusLine());
this.sessionBuffer.writeLine(buffer);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
/**
* Content encoder that cuts off after a defined number of bytes. This class
* is used to send content of HTTP messages where the end of the content entity
* is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* This decoder is optimized to transfer data directly from
* a {@link FileChannel} to the underlying I/O session's channel whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class LengthDelimitedEncoder extends AbstractContentEncoder
implements FileContentEncoder {
private final long contentLength;
private long len;
public LengthDelimitedEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics,
long contentLength) {
super(channel, buffer, metrics);
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.contentLength = contentLength;
this.len = 0;
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int lenRemaining = (int) (this.contentLength - this.len);
int bytesWritten;
if (src.remaining() > lenRemaining) {
int oldLimit = src.limit();
int newLimit = oldLimit - (src.remaining() - lenRemaining);
src.limit(newLimit);
bytesWritten = this.channel.write(src);
src.limit(oldLimit);
} else {
bytesWritten = this.channel.write(src);
}
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
this.len += bytesWritten;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesWritten;
}
public long transfer(
final FileChannel src,
long position,
long count) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int lenRemaining = (int) (this.contentLength - this.len);
long bytesWritten;
if (count > lenRemaining) {
count = lenRemaining;
}
bytesWritten = src.transferTo(position, count, this.channel);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
this.len += bytesWritten;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesWritten;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[content length: ");
buffer.append(this.contentLength);
buffer.append("; pos: ");
buffer.append(this.len);
buffer.append("; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
/**
* Abstract {@link ContentEncoder} that serves as a base for all content
* encoder implementations.
*
* @since 4.0
*/
public abstract class AbstractContentEncoder implements ContentEncoder {
protected final WritableByteChannel channel;
protected final SessionOutputBuffer buffer;
protected final HttpTransportMetricsImpl metrics;
protected boolean completed;
/**
* Creates an instance of this class.
*
* @param channel the destination channel.
* @param buffer the session output buffer that can be used to store
* session data for intermediate processing.
* @param metrics Transport metrics of the underlying HTTP transport.
*/
public AbstractContentEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super();
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (metrics == null) {
throw new IllegalArgumentException("Transport metrics may not be null");
}
this.buffer = buffer;
this.channel = channel;
this.metrics = metrics;
}
public boolean isCompleted() {
return this.completed;
}
public void complete() throws IOException {
this.completed = true;
}
protected void assertNotCompleted() {
if (this.completed) {
throw new IllegalStateException("Encoding process already completed");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
/**
* Content encoder that writes data without any transformation. The end of
* the content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* This decoder is optimized to transfer data directly from
* a {@link FileChannel} to the underlying I/O session's channel whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class IdentityEncoder extends AbstractContentEncoder
implements FileContentEncoder {
public IdentityEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int bytesWritten = this.channel.write(src);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
return bytesWritten;
}
public long transfer(
final FileChannel src,
long position,
long count) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
long bytesWritten = src.transferTo(position, count, this.channel);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
return bytesWritten;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[identity; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.ParseException;
import org.apache.http.ProtocolException;
import org.apache.http.message.LineParser;
import org.apache.http.message.BasicLineParser;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Abstract {@link NHttpMessageParser} that serves as a base for all message
* parser implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractMessageParser<T extends HttpMessage> implements NHttpMessageParser<T> {
private final SessionInputBuffer sessionBuffer;
private static final int READ_HEAD_LINE = 0;
private static final int READ_HEADERS = 1;
private static final int COMPLETED = 2;
private int state;
private boolean endOfStream;
private T message;
private CharArrayBuffer lineBuf;
private final List<CharArrayBuffer> headerBufs;
private int maxLineLen = -1;
private int maxHeaderCount = -1;
protected final LineParser lineParser;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param params HTTP parameters.
*/
public AbstractMessageParser(final SessionInputBuffer buffer, final LineParser parser, final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.sessionBuffer = buffer;
this.state = READ_HEAD_LINE;
this.endOfStream = false;
this.headerBufs = new ArrayList<CharArrayBuffer>();
this.maxLineLen = params.getIntParameter(
CoreConnectionPNames.MAX_LINE_LENGTH, -1);
this.maxHeaderCount = params.getIntParameter(
CoreConnectionPNames.MAX_HEADER_COUNT, -1);
this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT;
}
public void reset() {
this.state = READ_HEAD_LINE;
this.endOfStream = false;
this.headerBufs.clear();
this.message = null;
}
public int fillBuffer(final ReadableByteChannel channel) throws IOException {
int bytesRead = this.sessionBuffer.fill(channel);
if (bytesRead == -1) {
this.endOfStream = true;
}
return bytesRead;
}
/**
* Creates {@link HttpMessage} instance based on the content of the input
* buffer containing the first line of the incoming HTTP message.
*
* @param buffer the line buffer.
* @return HTTP message.
* @throws HttpException in case of HTTP protocol violation
* @throws ParseException in case of a parse error.
*/
protected abstract T createMessage(CharArrayBuffer buffer)
throws HttpException, ParseException;
private void parseHeadLine() throws HttpException, ParseException {
this.message = createMessage(this.lineBuf);
}
private void parseHeader() throws IOException {
CharArrayBuffer current = this.lineBuf;
int count = this.headerBufs.size();
if ((this.lineBuf.charAt(0) == ' ' || this.lineBuf.charAt(0) == '\t') && count > 0) {
// Handle folded header line
CharArrayBuffer previous = this.headerBufs.get(count - 1);
int i = 0;
while (i < current.length()) {
char ch = current.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
if (this.maxLineLen > 0
&& previous.length() + 1 + current.length() - i > this.maxLineLen) {
throw new IOException("Maximum line length limit exceeded");
}
previous.append(' ');
previous.append(current, i, current.length() - i);
} else {
this.headerBufs.add(current);
this.lineBuf = null;
}
}
public T parse() throws IOException, HttpException {
while (this.state != COMPLETED) {
if (this.lineBuf == null) {
this.lineBuf = new CharArrayBuffer(64);
} else {
this.lineBuf.clear();
}
boolean lineComplete = this.sessionBuffer.readLine(this.lineBuf, this.endOfStream);
if (this.maxLineLen > 0 &&
(this.lineBuf.length() > this.maxLineLen ||
(!lineComplete && this.sessionBuffer.length() > this.maxLineLen))) {
throw new IOException("Maximum line length limit exceeded");
}
if (!lineComplete) {
break;
}
switch (this.state) {
case READ_HEAD_LINE:
try {
parseHeadLine();
} catch (ParseException px) {
throw new ProtocolException(px.getMessage(), px);
}
this.state = READ_HEADERS;
break;
case READ_HEADERS:
if (this.lineBuf.length() > 0) {
if (this.maxHeaderCount > 0 && headerBufs.size() >= this.maxHeaderCount) {
throw new IOException("Maximum header count exceeded");
}
parseHeader();
} else {
this.state = COMPLETED;
}
break;
}
if (this.endOfStream && !this.sessionBuffer.hasData()) {
this.state = COMPLETED;
}
}
if (this.state == COMPLETED) {
for (int i = 0; i < this.headerBufs.size(); i++) {
CharArrayBuffer buffer = this.headerBufs.get(i);
try {
this.message.addHeader(lineParser.parseHeader(buffer));
} catch (ParseException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
return this.message;
} else {
return null;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.HttpParams;
public class ElementalEchoServer {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
IOEventDispatch ioEventDispatch = new DefaultIoEventDispatch();
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
ioReactor.listen(new InetSocketAddress(8080));
try {
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class DefaultIoEventDispatch implements IOEventDispatch {
private final ByteBuffer buffer = ByteBuffer.allocate(1024);
public void connected(IOSession session) {
System.out.println("connected");
session.setEventMask(EventMask.READ);
session.setSocketTimeout(20000);
}
public void inputReady(final IOSession session) {
System.out.println("readable");
try {
this.buffer.compact();
int bytesRead = session.channel().read(this.buffer);
if (this.buffer.position() > 0) {
session.setEventMask(EventMask.READ_WRITE);
}
System.out.println("Bytes read: " + bytesRead);
if (bytesRead == -1) {
session.close();
}
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
}
public void outputReady(final IOSession session) {
System.out.println("writeable");
try {
this.buffer.flip();
int bytesWritten = session.channel().write(this.buffer);
if (!this.buffer.hasRemaining()) {
session.setEventMask(EventMask.READ);
}
System.out.println("Bytes written: " + bytesWritten);
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
}
public void timeout(final IOSession session) {
System.out.println("timeout");
session.close();
}
public void disconnected(final IOSession session) {
System.out.println("disconnected");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.Locale;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTPS/1.1 server based on the non-blocking
* I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP server.
*
*
*/
public class NHttpSSLServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
ClassLoader cl = NHttpSSLServer.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Jakarta-HttpComponents-NIO/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(args[0]));
handler.setHandlerResolver(reqistry);
// Provide an event logger
handler.setEventListener(new EventLogger());
IOEventDispatch ioEventDispatch = new SSLServerIOEventDispatch(
handler,
sslcontext,
params);
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
try {
ioReactor.listen(new InetSocketAddress(8080));
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Elemental example for executing HTTP requests using the non-blocking I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*/
public class NHttpClient {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
// We are going to use this object to synchronize between the
// I/O event and main threads
CountDownLatch requestCount = new CountDownLatch(3);
BufferingHttpClientHandler handler = new BufferingHttpClientHandler(
httpproc,
new MyHttpRequestExecutionHandler(requestCount),
new DefaultConnectionReuseStrategy(),
params);
handler.setEventListener(new EventLogger());
final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);
Thread t = new Thread(new Runnable() {
public void run() {
try {
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
});
t.start();
SessionRequest[] reqs = new SessionRequest[3];
reqs[0] = ioReactor.connect(
new InetSocketAddress("www.yahoo.com", 80),
null,
new HttpHost("www.yahoo.com"),
new MySessionRequestCallback(requestCount));
reqs[1] = ioReactor.connect(
new InetSocketAddress("www.google.com", 80),
null,
new HttpHost("www.google.ch"),
new MySessionRequestCallback(requestCount));
reqs[2] = ioReactor.connect(
new InetSocketAddress("www.apache.org", 80),
null,
new HttpHost("www.apache.org"),
new MySessionRequestCallback(requestCount));
// Block until all connections signal
// completion of the request execution
requestCount.await();
System.out.println("Shutting down I/O reactor");
ioReactor.shutdown();
System.out.println("Done");
}
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
private final static String REQUEST_SENT = "request-sent";
private final static String RESPONSE_RECEIVED = "response-received";
private final CountDownLatch requestCount;
public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void initalizeContext(final HttpContext context, final Object attachment) {
HttpHost targetHost = (HttpHost) attachment;
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
}
public void finalizeContext(final HttpContext context) {
Object flag = context.getAttribute(RESPONSE_RECEIVED);
if (flag == null) {
// Signal completion of the request execution
requestCount.countDown();
}
}
public HttpRequest submitRequest(final HttpContext context) {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Object flag = context.getAttribute(REQUEST_SENT);
if (flag == null) {
// Stick some object into the context
context.setAttribute(REQUEST_SENT, Boolean.TRUE);
System.out.println("--------------");
System.out.println("Sending request to " + targetHost);
System.out.println("--------------");
return new BasicHttpRequest("GET", "/");
} else {
// No new request to submit
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
HttpEntity entity = response.getEntity();
try {
String content = EntityUtils.toString(entity);
System.out.println("--------------");
System.out.println(response.getStatusLine());
System.out.println("--------------");
System.out.println("Document length: " + content.length());
System.out.println("--------------");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
// Signal completion of the request execution
requestCount.countDown();
}
}
static class MySessionRequestCallback implements SessionRequestCallback {
private final CountDownLatch requestCount;
public MySessionRequestCallback(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void cancelled(final SessionRequest request) {
System.out.println("Connect request cancelled: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void completed(final SessionRequest request) {
}
public void failed(final SessionRequest request) {
System.out.println("Connect request failed: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void timeout(final SessionRequest request) {
System.out.println("Connect request timed out: " + request.getRemoteAddress());
this.requestCount.countDown();
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Elemental example for executing HTTPS requests using the non-blocking I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*/
public class NHttpSSLClient {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "Jakarta-HttpComponents-NIO/1.1");
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
// Initialize default SSL context
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, null, null);
// We are going to use this object to synchronize between the
// I/O event and main threads
CountDownLatch requestCount = new CountDownLatch(3);
BufferingHttpClientHandler handler = new BufferingHttpClientHandler(
httpproc,
new MyHttpRequestExecutionHandler(requestCount),
new DefaultConnectionReuseStrategy(),
params);
handler.setEventListener(new EventLogger());
final IOEventDispatch ioEventDispatch = new SSLClientIOEventDispatch(
handler,
sslcontext,
params);
Thread t = new Thread(new Runnable() {
public void run() {
try {
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
});
t.start();
SessionRequest[] reqs = new SessionRequest[3];
reqs[0] = ioReactor.connect(
new InetSocketAddress("www.netscape.com", 443),
null,
new HttpHost("www.netscape.com", 443),
new MySessionRequestCallback(requestCount));
reqs[1] = ioReactor.connect(
new InetSocketAddress("www.verisign.com", 443),
null,
new HttpHost("www.verisign.com", 443),
new MySessionRequestCallback(requestCount));
reqs[2] = ioReactor.connect(
new InetSocketAddress("www.yahoo.com", 443),
null,
new HttpHost("www.yahoo.com", 443),
new MySessionRequestCallback(requestCount));
// Block until all connections signal
// completion of the request execution
requestCount.await();
System.out.println("Shutting down I/O reactor");
ioReactor.shutdown();
System.out.println("Done");
}
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
private final static String REQUEST_SENT = "request-sent";
private final static String RESPONSE_RECEIVED = "response-received";
private final CountDownLatch requestCount;
public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void initalizeContext(final HttpContext context, final Object attachment) {
HttpHost targetHost = (HttpHost) attachment;
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
}
public void finalizeContext(final HttpContext context) {
Object flag = context.getAttribute(RESPONSE_RECEIVED);
if (flag == null) {
// Signal completion of the request execution
this.requestCount.countDown();
}
}
public HttpRequest submitRequest(final HttpContext context) {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Object token = context.getAttribute(REQUEST_SENT);
if (token == null) {
// Stick some object into the context
context.setAttribute(REQUEST_SENT, Boolean.TRUE);
System.out.println("--------------");
System.out.println("Sending request to " + targetHost);
System.out.println("--------------");
return new BasicHttpRequest("GET", "/");
} else {
// No new request to submit
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
HttpEntity entity = response.getEntity();
try {
String content = EntityUtils.toString(entity);
System.out.println("--------------");
System.out.println(response.getStatusLine());
System.out.println("--------------");
System.out.println("Document length: " + content.length());
System.out.println("--------------");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
// Signal completion of the request execution
this.requestCount.countDown();
}
}
static class MySessionRequestCallback implements SessionRequestCallback {
private final CountDownLatch requestCount;
public MySessionRequestCallback(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void cancelled(final SessionRequest request) {
System.out.println("Connect request cancelled: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void completed(final SessionRequest request) {
}
public void failed(final SessionRequest request) {
System.out.println("Connect request failed: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void timeout(final SessionRequest request) {
System.out.println("Connect request timed out: " + request.getRemoteAddress());
this.requestCount.countDown();
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentDecoderChannel;
import org.apache.http.nio.FileContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate;
import org.apache.http.nio.entity.ContentListener;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.http.nio.protocol.NHttpRequestHandlerResolver;
import org.apache.http.nio.protocol.SimpleNHttpRequestHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server based on the non-blocking
* I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
*
*
*/
public class NHttpFileServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
boolean useFileChannels = true;
if (args.length >= 2) {
String s = args[1];
if (s.equalsIgnoreCase("disableFileChannels")) {
useFileChannels = false;
}
}
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
final HttpFileHandler filehandler = new HttpFileHandler(args[0], useFileChannels);
NHttpRequestHandlerResolver resolver = new NHttpRequestHandlerResolver() {
public NHttpRequestHandler lookup(String requestURI) {
return filehandler;
}
};
handler.setHandlerResolver(resolver);
// Provide an event logger
handler.setEventListener(new EventLogger());
IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
try {
ioReactor.listen(new InetSocketAddress(8080));
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler extends SimpleNHttpRequestHandler {
private final String docRoot;
private final boolean useFileChannels;
public HttpFileHandler(final String docRoot, boolean useFileChannels) {
this.docRoot = docRoot;
this.useFileChannels = useFileChannels;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) throws HttpException, IOException {
return new ConsumingNHttpEntityTemplate(
request.getEntity(),
new FileWriteListener(useFileChannels));
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
NStringEntity entity = new NStringEntity(
"<html><body><h1>File" + file.getPath() +
" not found</h1></body></html>",
"UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
NStringEntity entity = new NStringEntity(
"<html><body><h1>Access denied</h1></body></html>",
"UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
} else {
response.setStatusCode(HttpStatus.SC_OK);
NFileEntity entity = new NFileEntity(file, "text/html", useFileChannels);
response.setEntity(entity);
}
}
}
static class FileWriteListener implements ContentListener {
private final File file;
private final FileOutputStream outputFile;
private final FileChannel fileChannel;
private final boolean useFileChannels;
private long idx = 0;
public FileWriteListener(boolean useFileChannels) throws IOException {
this.file = File.createTempFile("tmp", ".tmp", null);
this.outputFile = new FileOutputStream(file, true);
this.fileChannel = outputFile.getChannel();
this.useFileChannels = useFileChannels;
}
public void contentAvailable(ContentDecoder decoder, IOControl ioctrl)
throws IOException {
long transferred;
if(useFileChannels && decoder instanceof FileContentDecoder) {
transferred = ((FileContentDecoder) decoder).transfer(
fileChannel, idx, Long.MAX_VALUE);
} else {
transferred = fileChannel.transferFrom(
new ContentDecoderChannel(decoder), idx, Integer.MAX_VALUE);
}
if(transferred > 0)
idx += transferred;
}
public void finished() {
try {
outputFile.close();
} catch(IOException ignored) {}
try {
fileChannel.close();
} catch(IOException ignored) {}
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 server based on the non-blocking
* I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP server.
*
*
*/
public class NHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(args[0]));
handler.setHandlerResolver(reqistry);
// Provide an event logger
handler.setEventListener(new EventLogger());
IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
try {
ioReactor.listen(new InetSocketAddress(8080));
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
NStringEntity entity = new NStringEntity(
"<html><body><h1>File" + file.getPath() +
" not found</h1></body></html>", "UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
NStringEntity entity = new NStringEntity(
"<html><body><h1>Access denied</h1></body></html>",
"UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
NFileEntity body = new NFileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
/**
* Rudimentary HTTP/1.1 reverse proxy based on the non-blocking I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP reverse proxy.
*
*
*/
public class NHttpReverseProxy {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Usage: NHttpReverseProxy <hostname> [port]");
System.exit(1);
}
String hostname = args[0];
int port = 80;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
// Target host
HttpHost targetHost = new HttpHost(hostname, port);
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1")
.setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");
final ConnectingIOReactor connectingIOReactor = new DefaultConnectingIOReactor(
1, params);
final ListeningIOReactor listeningIOReactor = new DefaultListeningIOReactor(
1, params);
// Set up HTTP protocol processor for incoming connections
HttpProcessor inhttpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
// Set up HTTP protocol processor for outgoing connections
HttpProcessor outhttpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
NHttpClientHandler connectingHandler = new ConnectingHandler(
inhttpproc,
new DefaultConnectionReuseStrategy(),
params);
NHttpServiceHandler listeningHandler = new ListeningHandler(
targetHost,
connectingIOReactor,
outhttpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
final IOEventDispatch connectingEventDispatch = new DefaultClientIOEventDispatch(
connectingHandler, params);
final IOEventDispatch listeningEventDispatch = new DefaultServerIOEventDispatch(
listeningHandler, params);
Thread t = new Thread(new Runnable() {
public void run() {
try {
connectingIOReactor.execute(connectingEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
}
});
t.start();
try {
listeningIOReactor.listen(new InetSocketAddress(8888));
listeningIOReactor.execute(listeningEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
}
static class ListeningHandler implements NHttpServiceHandler {
private final HttpHost targetHost;
private final ConnectingIOReactor connectingIOReactor;
private final HttpProcessor httpProcessor;
private final HttpResponseFactory responseFactory;
private final ConnectionReuseStrategy connStrategy;
private final HttpParams params;
public ListeningHandler(
final HttpHost targetHost,
final ConnectingIOReactor connectingIOReactor,
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
super();
this.targetHost = targetHost;
this.connectingIOReactor = connectingIOReactor;
this.httpProcessor = httpProcessor;
this.connStrategy = connStrategy;
this.responseFactory = responseFactory;
this.params = params;
}
public void connected(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] conn open");
ProxyTask proxyTask = new ProxyTask();
synchronized (proxyTask) {
// Initialize connection state
proxyTask.setTarget(this.targetHost);
proxyTask.setClientIOControl(conn);
proxyTask.setClientState(ConnState.CONNECTED);
HttpContext context = conn.getContext();
context.setAttribute(ProxyTask.ATTRIB, proxyTask);
InetSocketAddress address = new InetSocketAddress(
this.targetHost.getHostName(),
this.targetHost.getPort());
this.connectingIOReactor.connect(
address,
null,
proxyTask,
null);
}
}
public void requestReceived(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] request received");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState != ConnState.IDLE
&& connState != ConnState.CONNECTED) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
try {
HttpRequest request = conn.getHttpRequest();
System.out.println(conn + " [client->proxy] >> " + request.getRequestLine());
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
// Update connection state
proxyTask.setRequest(request);
proxyTask.setClientState(ConnState.REQUEST_RECEIVED);
// See if the client expects a 100-Continue
if (request instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest) request).expectContinue()) {
HttpResponse ack = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_CONTINUE,
context);
conn.submitResponse(ack);
}
} else {
// No request content expected. Suspend client input
conn.suspendInput();
}
// If there is already a connection to the origin server
// make sure origin output is active
if (proxyTask.getOriginIOControl() != null) {
proxyTask.getOriginIOControl().requestOutput();
}
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
System.out.println(conn + " [client->proxy] input ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState != ConnState.REQUEST_RECEIVED
&& connState != ConnState.REQUEST_BODY_STREAM) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
try {
ByteBuffer dst = proxyTask.getInBuffer();
int bytesRead = decoder.read(dst);
System.out.println(conn + " [client->proxy] " + bytesRead + " bytes read");
System.out.println(conn + " [client->proxy] " + decoder);
if (!dst.hasRemaining()) {
// Input buffer is full. Suspend client input
// until the origin handler frees up some space in the buffer
conn.suspendInput();
}
// If there is some content in the input buffer make sure origin
// output is active
if (dst.position() > 0) {
if (proxyTask.getOriginIOControl() != null) {
proxyTask.getOriginIOControl().requestOutput();
}
}
if (decoder.isCompleted()) {
System.out.println(conn + " [client->proxy] request body received");
// Update connection state
proxyTask.setClientState(ConnState.REQUEST_BODY_DONE);
// Suspend client input
conn.suspendInput();
} else {
proxyTask.setClientState(ConnState.REQUEST_BODY_STREAM);
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void responseReady(final NHttpServerConnection conn) {
System.out.println(conn + " [client<-proxy] response ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState == ConnState.IDLE) {
// Response not available
return;
}
if (connState != ConnState.REQUEST_RECEIVED
&& connState != ConnState.REQUEST_BODY_DONE) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
try {
HttpRequest request = proxyTask.getRequest();
HttpResponse response = proxyTask.getResponse();
if (response == null) {
throw new IllegalStateException("HTTP request is null");
}
// Remove hop-by-hop headers
response.removeHeaders(HTTP.CONTENT_LEN);
response.removeHeaders(HTTP.TRANSFER_ENCODING);
response.removeHeaders(HTTP.CONN_DIRECTIVE);
response.removeHeaders("Keep-Alive");
response.removeHeaders("Proxy-Authenticate");
response.removeHeaders("Proxy-Authorization");
response.removeHeaders("TE");
response.removeHeaders("Trailers");
response.removeHeaders("Upgrade");
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
// Close client connection if the connection to the target
// is no longer active / open
if (proxyTask.getOriginState().compareTo(ConnState.CLOSING) >= 0) {
response.addHeader(HTTP.CONN_DIRECTIVE, "Close");
}
// Pre-process HTTP request
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(response, context);
conn.submitResponse(response);
proxyTask.setClientState(ConnState.RESPONSE_SENT);
System.out.println(conn + " [client<-proxy] << " + response.getStatusLine());
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [client<-proxy] close connection");
proxyTask.setClientState(ConnState.CLOSING);
conn.close();
} else {
// Reset connection state
proxyTask.reset();
conn.requestInput();
// Ready to deal with a new request
}
}
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
}
private boolean canResponseHaveBody(
final HttpRequest request, final HttpResponse response) {
if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
System.out.println(conn + " [client<-proxy] output ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState != ConnState.RESPONSE_SENT
&& connState != ConnState.RESPONSE_BODY_STREAM) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
HttpResponse response = proxyTask.getResponse();
if (response == null) {
throw new IllegalStateException("HTTP request is null");
}
try {
ByteBuffer src = proxyTask.getOutBuffer();
src.flip();
int bytesWritten = encoder.write(src);
System.out.println(conn + " [client<-proxy] " + bytesWritten + " bytes written");
System.out.println(conn + " [client<-proxy] " + encoder);
src.compact();
if (src.position() == 0) {
if (proxyTask.getOriginState() == ConnState.RESPONSE_BODY_DONE) {
encoder.complete();
} else {
// Input output is empty. Wait until the origin handler
// fills up the buffer
conn.suspendOutput();
}
}
// Update connection state
if (encoder.isCompleted()) {
System.out.println(conn + " [proxy] response body sent");
proxyTask.setClientState(ConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [client<-proxy] close connection");
proxyTask.setClientState(ConnState.CLOSING);
conn.close();
} else {
// Reset connection state
proxyTask.reset();
conn.requestInput();
// Ready to deal with a new request
}
} else {
proxyTask.setClientState(ConnState.RESPONSE_BODY_STREAM);
// Make sure origin input is active
proxyTask.getOriginIOControl().requestInput();
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void closed(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] conn closed");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
if (proxyTask != null) {
synchronized (proxyTask) {
proxyTask.setClientState(ConnState.CLOSED);
}
}
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
System.out.println(conn + " [client->proxy] HTTP error: " + httpex.getMessage());
if (conn.isResponseSubmitted()) {
shutdownConnection(conn);
return;
}
HttpContext context = conn.getContext();
try {
HttpResponse response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0, HttpStatus.SC_BAD_REQUEST, context);
response.setParams(
new DefaultedHttpParams(this.params, response.getParams()));
response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
// Pre-process HTTP request
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQUEST, null);
this.httpProcessor.process(response, context);
conn.submitResponse(response);
conn.close();
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn);
System.out.println(conn + " [client->proxy] I/O error: " + ex.getMessage());
}
public void timeout(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] timeout");
closeConnection(conn);
}
private void shutdownConnection(final NHttpConnection conn) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
private void closeConnection(final NHttpConnection conn) {
try {
conn.close();
} catch (IOException ignore) {
}
}
}
static class ConnectingHandler implements NHttpClientHandler {
private final HttpProcessor httpProcessor;
private final ConnectionReuseStrategy connStrategy;
private final HttpParams params;
public ConnectingHandler(
final HttpProcessor httpProcessor,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
super();
this.httpProcessor = httpProcessor;
this.connStrategy = connStrategy;
this.params = params;
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
System.out.println(conn + " [proxy->origin] conn open");
// The shared state object is expected to be passed as an attachment
ProxyTask proxyTask = (ProxyTask) attachment;
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.IDLE) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
// Set origin IO control handle
proxyTask.setOriginIOControl(conn);
// Store the state object in the context
HttpContext context = conn.getContext();
context.setAttribute(ProxyTask.ATTRIB, proxyTask);
// Update connection state
proxyTask.setOriginState(ConnState.CONNECTED);
if (proxyTask.getRequest() != null) {
conn.requestOutput();
}
}
}
public void requestReady(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy->origin] request ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState == ConnState.REQUEST_SENT
|| connState == ConnState.REQUEST_BODY_DONE) {
// Request sent but no response available yet
return;
}
if (connState != ConnState.IDLE
&& connState != ConnState.CONNECTED) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
HttpRequest request = proxyTask.getRequest();
if (request == null) {
throw new IllegalStateException("HTTP request is null");
}
// Remove hop-by-hop headers
request.removeHeaders(HTTP.CONTENT_LEN);
request.removeHeaders(HTTP.TRANSFER_ENCODING);
request.removeHeaders(HTTP.CONN_DIRECTIVE);
request.removeHeaders("Keep-Alive");
request.removeHeaders("Proxy-Authenticate");
request.removeHeaders("Proxy-Authorization");
request.removeHeaders("TE");
request.removeHeaders("Trailers");
request.removeHeaders("Upgrade");
// Remove host header
request.removeHeaders(HTTP.TARGET_HOST);
HttpHost targetHost = proxyTask.getTarget();
try {
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
// Pre-process HTTP request
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
this.httpProcessor.process(request, context);
// and send it to the origin server
conn.submitRequest(request);
// Update connection state
proxyTask.setOriginState(ConnState.REQUEST_SENT);
System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString());
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
System.out.println(conn + " [proxy->origin] output ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.REQUEST_SENT
&& connState != ConnState.REQUEST_BODY_STREAM) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
try {
ByteBuffer src = proxyTask.getInBuffer();
src.flip();
int bytesWritten = encoder.write(src);
System.out.println(conn + " [proxy->origin] " + bytesWritten + " bytes written");
System.out.println(conn + " [proxy->origin] " + encoder);
src.compact();
if (src.position() == 0) {
if (proxyTask.getClientState() == ConnState.REQUEST_BODY_DONE) {
encoder.complete();
} else {
// Input buffer is empty. Wait until the client fills up
// the buffer
conn.suspendOutput();
}
}
// Update connection state
if (encoder.isCompleted()) {
System.out.println(conn + " [proxy->origin] request body sent");
proxyTask.setOriginState(ConnState.REQUEST_BODY_DONE);
} else {
proxyTask.setOriginState(ConnState.REQUEST_BODY_STREAM);
// Make sure client input is active
proxyTask.getClientIOControl().requestInput();
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void responseReceived(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy<-origin] response received");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.REQUEST_SENT
&& connState != ConnState.REQUEST_BODY_DONE) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
HttpResponse response = conn.getHttpResponse();
HttpRequest request = proxyTask.getRequest();
System.out.println(conn + " [proxy<-origin] << " + response.getStatusLine());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// Ignore 1xx response
return;
}
try {
// Update connection state
proxyTask.setResponse(response);
proxyTask.setOriginState(ConnState.RESPONSE_RECEIVED);
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [proxy<-origin] close connection");
proxyTask.setOriginState(ConnState.CLOSING);
conn.close();
}
}
// Make sure client output is active
proxyTask.getClientIOControl().requestOutput();
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
private boolean canResponseHaveBody(
final HttpRequest request, final HttpResponse response) {
if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
System.out.println(conn + " [proxy<-origin] input ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.RESPONSE_RECEIVED
&& connState != ConnState.RESPONSE_BODY_STREAM) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
HttpResponse response = proxyTask.getResponse();
try {
ByteBuffer dst = proxyTask.getOutBuffer();
int bytesRead = decoder.read(dst);
System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read");
System.out.println(conn + " [proxy<-origin] " + decoder);
if (!dst.hasRemaining()) {
// Output buffer is full. Suspend origin input until
// the client handler frees up some space in the buffer
conn.suspendInput();
}
// If there is some content in the buffer make sure client output
// is active
if (dst.position() > 0) {
proxyTask.getClientIOControl().requestOutput();
}
if (decoder.isCompleted()) {
System.out.println(conn + " [proxy<-origin] response body received");
proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [proxy<-origin] close connection");
proxyTask.setOriginState(ConnState.CLOSING);
conn.close();
}
} else {
proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM);
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void closed(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy->origin] conn closed");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
if (proxyTask != null) {
synchronized (proxyTask) {
proxyTask.setOriginState(ConnState.CLOSED);
}
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
shutdownConnection(conn);
System.out.println(conn + " [proxy->origin] HTTP error: " + ex.getMessage());
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn);
System.out.println(conn + " [proxy->origin] I/O error: " + ex.getMessage());
}
public void timeout(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy->origin] timeout");
closeConnection(conn);
}
private void shutdownConnection(final HttpConnection conn) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
private void closeConnection(final HttpConnection conn) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
}
enum ConnState {
IDLE,
CONNECTED,
REQUEST_RECEIVED,
REQUEST_SENT,
REQUEST_BODY_STREAM,
REQUEST_BODY_DONE,
RESPONSE_RECEIVED,
RESPONSE_SENT,
RESPONSE_BODY_STREAM,
RESPONSE_BODY_DONE,
CLOSING,
CLOSED
}
static class ProxyTask {
public static final String ATTRIB = "nhttp.proxy-task";
private final ByteBuffer inBuffer;
private final ByteBuffer outBuffer;
private HttpHost target;
private IOControl originIOControl;
private IOControl clientIOControl;
private ConnState originState;
private ConnState clientState;
private HttpRequest request;
private HttpResponse response;
public ProxyTask() {
super();
this.originState = ConnState.IDLE;
this.clientState = ConnState.IDLE;
this.inBuffer = ByteBuffer.allocateDirect(10240);
this.outBuffer = ByteBuffer.allocateDirect(10240);
}
public ByteBuffer getInBuffer() {
return this.inBuffer;
}
public ByteBuffer getOutBuffer() {
return this.outBuffer;
}
public HttpHost getTarget() {
return this.target;
}
public void setTarget(final HttpHost target) {
this.target = target;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public IOControl getClientIOControl() {
return this.clientIOControl;
}
public void setClientIOControl(final IOControl clientIOControl) {
this.clientIOControl = clientIOControl;
}
public IOControl getOriginIOControl() {
return this.originIOControl;
}
public void setOriginIOControl(final IOControl originIOControl) {
this.originIOControl = originIOControl;
}
public ConnState getOriginState() {
return this.originState;
}
public void setOriginState(final ConnState state) {
this.originState = state;
}
public ConnState getClientState() {
return this.clientState;
}
public void setClientState(final ConnState state) {
this.clientState = state;
}
public void reset() {
this.inBuffer.clear();
this.outBuffer.clear();
this.originState = ConnState.IDLE;
this.clientState = ConnState.IDLE;
this.request = null;
this.response = null;
}
public void shutdown() {
if (this.clientIOControl != null) {
try {
this.clientIOControl.shutdown();
} catch (IOException ignore) {
}
}
if (this.originIOControl != null) {
try {
this.originIOControl.shutdown();
} catch (IOException ignore) {
}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Example of a very simple asynchronous connection manager that maintains a pool of persistent
* connections to one target host.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*/
public class NHttpClientConnManagement {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
// Set up protocol handler
BufferingHttpClientHandler protocolHandler = new BufferingHttpClientHandler(
httpproc,
new MyHttpRequestExecutionHandler(),
new DefaultConnectionReuseStrategy(),
params);
protocolHandler.setEventListener(new EventLogger());
// Limit the total maximum of concurrent connections to 5
int maxTotalConnections = 5;
// Use the connection manager to maintain a pool of connections to localhost:8080
final AsyncConnectionManager connMgr = new AsyncConnectionManager(
new HttpHost("localhost", 8080),
maxTotalConnections,
protocolHandler,
params);
// Start the I/O reactor in a separate thread
Thread t = new Thread(new Runnable() {
public void run() {
try {
connMgr.execute();
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("I/O reactor terminated");
}
});
t.start();
// Submit 50 requests using maximum 5 concurrent connections
Queue<RequestHandle> queue = new LinkedList<RequestHandle>();
for (int i = 0; i < 50; i++) {
AsyncConnectionRequest connRequest = connMgr.requestConnection();
connRequest.waitFor();
NHttpClientConnection conn = connRequest.getConnection();
if (conn == null) {
System.err.println("Failed to obtain connection");
break;
}
HttpContext context = conn.getContext();
BasicHttpRequest httpget = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
RequestHandle handle = new RequestHandle(connMgr, conn);
context.setAttribute("request", httpget);
context.setAttribute("request-handle", handle);
queue.add(handle);
conn.requestOutput();
}
// Wait until all requests have been completed
while (!queue.isEmpty()) {
RequestHandle handle = queue.remove();
handle.waitFor();
}
// Give the I/O reactor 10 sec to shut down
connMgr.shutdown(10000);
System.out.println("Done");
}
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
public MyHttpRequestExecutionHandler() {
super();
}
public void initalizeContext(final HttpContext context, final Object attachment) {
}
public void finalizeContext(final HttpContext context) {
RequestHandle handle = (RequestHandle) context.removeAttribute("request-handle");
if (handle != null) {
handle.cancel();
}
}
public HttpRequest submitRequest(final HttpContext context) {
HttpRequest request = (HttpRequest) context.removeAttribute("request");
return request;
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
HttpEntity entity = response.getEntity();
try {
String content = EntityUtils.toString(entity);
System.out.println("--------------");
System.out.println(response.getStatusLine());
System.out.println("--------------");
System.out.println("Document length: " + content.length());
System.out.println("--------------");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
RequestHandle handle = (RequestHandle) context.removeAttribute("request-handle");
if (handle != null) {
handle.completed();
}
}
}
static class AsyncConnectionRequest {
private volatile boolean completed;
private volatile NHttpClientConnection conn;
public AsyncConnectionRequest() {
super();
}
public boolean isCompleted() {
return this.completed;
}
public void setConnection(NHttpClientConnection conn) {
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.conn = conn;
notifyAll();
}
}
public NHttpClientConnection getConnection() {
return this.conn;
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
notifyAll();
}
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
}
static class AsyncConnectionManager {
private final HttpHost target;
private final int maxConnections;
private final NHttpClientHandler handler;
private final HttpParams params;
private final ConnectingIOReactor ioreactor;
private final Object lock;
private final Set<NHttpClientConnection> allConns;
private final Queue<NHttpClientConnection> availableConns;
private final Queue<AsyncConnectionRequest> pendingRequests;
private volatile boolean shutdown;
public AsyncConnectionManager(
HttpHost target,
int maxConnections,
NHttpClientHandler handler,
HttpParams params) throws IOReactorException {
super();
this.target = target;
this.maxConnections = maxConnections;
this.handler = handler;
this.params = params;
this.lock = new Object();
this.allConns = new HashSet<NHttpClientConnection>();
this.availableConns = new LinkedList<NHttpClientConnection>();
this.pendingRequests = new LinkedList<AsyncConnectionRequest>();
this.ioreactor = new DefaultConnectingIOReactor(2, params);
}
public void execute() throws IOException {
IOEventDispatch dispatch = new DefaultClientIOEventDispatch(
new ManagedClientHandler(this.handler, this), this.params);
this.ioreactor.execute(dispatch);
}
public void shutdown(long waitMs) throws IOException {
synchronized (this.lock) {
if (!this.shutdown) {
this.shutdown = true;
while (!this.pendingRequests.isEmpty()) {
AsyncConnectionRequest request = this.pendingRequests.remove();
request.cancel();
}
this.availableConns.clear();
this.allConns.clear();
}
}
this.ioreactor.shutdown(waitMs);
}
void addConnection(NHttpClientConnection conn) {
if (conn == null) {
return;
}
if (this.shutdown) {
return;
}
synchronized (this.lock) {
this.allConns.add(conn);
}
}
void removeConnection(NHttpClientConnection conn) {
if (conn == null) {
return;
}
if (this.shutdown) {
return;
}
synchronized (this.lock) {
if (this.allConns.remove(conn)) {
this.availableConns.remove(conn);
}
processRequests();
}
}
public AsyncConnectionRequest requestConnection() {
if (this.shutdown) {
throw new IllegalStateException("Connection manager has been shut down");
}
AsyncConnectionRequest request = new AsyncConnectionRequest();
synchronized (this.lock) {
while (!this.availableConns.isEmpty()) {
NHttpClientConnection conn = this.availableConns.remove();
if (conn.isOpen()) {
System.out.println("Re-using persistent connection");
request.setConnection(conn);
break;
} else {
this.allConns.remove(conn);
}
}
if (!request.isCompleted()) {
this.pendingRequests.add(request);
processRequests();
}
}
return request;
}
public void releaseConnection(NHttpClientConnection conn) {
if (conn == null) {
return;
}
if (this.shutdown) {
return;
}
synchronized (this.lock) {
if (this.allConns.contains(conn)) {
if (conn.isOpen()) {
conn.setSocketTimeout(0);
AsyncConnectionRequest request = this.pendingRequests.poll();
if (request != null) {
System.out.println("Re-using persistent connection");
request.setConnection(conn);
} else {
this.availableConns.add(conn);
}
} else {
this.allConns.remove(conn);
processRequests();
}
}
}
}
private void processRequests() {
while (this.allConns.size() < this.maxConnections) {
AsyncConnectionRequest request = this.pendingRequests.poll();
if (request == null) {
break;
}
InetSocketAddress address = new InetSocketAddress(
this.target.getHostName(),
this.target.getPort());
ConnRequestCallback callback = new ConnRequestCallback(request);
System.out.println("Opening new connection");
this.ioreactor.connect(address, null, request, callback);
}
}
}
static class ManagedClientHandler implements NHttpClientHandler {
private final NHttpClientHandler handler;
private final AsyncConnectionManager connMgr;
public ManagedClientHandler(NHttpClientHandler handler, AsyncConnectionManager connMgr) {
super();
this.handler = handler;
this.connMgr = connMgr;
}
public void connected(NHttpClientConnection conn, Object attachment) {
AsyncConnectionRequest request = (AsyncConnectionRequest) attachment;
this.handler.connected(conn, attachment);
this.connMgr.addConnection(conn);
request.setConnection(conn);
}
public void closed(NHttpClientConnection conn) {
this.connMgr.removeConnection(conn);
this.handler.closed(conn);
}
public void requestReady(NHttpClientConnection conn) {
this.handler.requestReady(conn);
}
public void outputReady(NHttpClientConnection conn, ContentEncoder encoder) {
this.handler.outputReady(conn, encoder);
}
public void responseReceived(NHttpClientConnection conn) {
this.handler.responseReceived(conn);
}
public void inputReady(NHttpClientConnection conn, ContentDecoder decoder) {
this.handler.inputReady(conn, decoder);
}
public void exception(NHttpClientConnection conn, HttpException ex) {
this.handler.exception(conn, ex);
}
public void exception(NHttpClientConnection conn, IOException ex) {
this.handler.exception(conn, ex);
}
public void timeout(NHttpClientConnection conn) {
this.handler.timeout(conn);
}
}
static class RequestHandle {
private final AsyncConnectionManager connMgr;
private final NHttpClientConnection conn;
private volatile boolean completed;
public RequestHandle(AsyncConnectionManager connMgr, NHttpClientConnection conn) {
super();
this.connMgr = connMgr;
this.conn = conn;
}
public boolean isCompleted() {
return this.completed;
}
public void completed() {
if (this.completed) {
return;
}
this.completed = true;
this.connMgr.releaseConnection(this.conn);
synchronized (this) {
notifyAll();
}
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
notifyAll();
}
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
}
static class ConnRequestCallback implements SessionRequestCallback {
private final AsyncConnectionRequest request;
ConnRequestCallback(AsyncConnectionRequest request) {
super();
this.request = request;
}
public void completed(SessionRequest request) {
System.out.println(request.getRemoteAddress() + " - request successful");
}
public void cancelled(SessionRequest request) {
System.out.println(request.getRemoteAddress() + " - request cancelled");
this.request.cancel();
}
public void failed(SessionRequest request) {
System.err.println(request.getRemoteAddress() + " - request failed");
IOException ex = request.getException();
if (ex != null) {
ex.printStackTrace();
}
this.request.cancel();
}
public void timeout(SessionRequest request) {
System.out.println(request.getRemoteAddress() + " - request timed out");
this.request.cancel();
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.util.Queue;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
abstract class RequestExecutionHandler
implements NHttpRequestExecutionHandler, HttpRequestExecutionHandler {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
protected abstract HttpRequest generateRequest(Job testjob);
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<Job> queue = (Queue<Job>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
Job testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
return generateRequest(testjob);
} else {
return null;
}
}
public ConsumingNHttpEntity responseEntity(
final HttpResponse response,
final HttpContext context) throws IOException {
return new BufferingNHttpEntity(response.getEntity(),
new HeapByteBufferAllocator());
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
content = EntityUtils.toString(entity);
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
final class RequestHandler extends SimpleNHttpRequestHandler implements HttpRequestHandler {
private final boolean chunking;
RequestHandler() {
this(false);
}
RequestHandler(boolean chunking) {
super();
this.chunking = chunking;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) {
return new BufferingNHttpEntity(
request.getEntity(),
new HeapByteBufferAllocator());
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String content = null;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
content = EntityUtils.toString(entity);
} else {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
content = "Request entity not avaialble";
}
} else {
String s = request.getRequestLine().getUri();
int idx = s.indexOf('x');
if (idx == -1) {
throw new HttpException("Unexpected request-URI format");
}
String pattern = s.substring(0, idx);
int count = Integer.parseInt(s.substring(idx + 1, s.length()));
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
buffer.append(pattern);
}
content = buffer.toString();
}
NStringEntity entity = new NStringEntity(content, "US-ASCII");
entity.setChunked(this.chunking);
response.setEntity(entity);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.util.Random;
public class Job {
private static final Random RND = new Random();
private static final String TEST_CHARS = "0123456789ABCDEF";
private final int count;
private final String pattern;
private volatile boolean completed;
private volatile int statusCode;
private volatile String result;
private volatile String failureMessage;
private volatile Exception ex;
public Job(int maxCount) {
super();
this.count = RND.nextInt(maxCount - 1) + 1;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 5; i++) {
char rndchar = TEST_CHARS.charAt(RND.nextInt(TEST_CHARS.length() - 1));
buffer.append(rndchar);
}
this.pattern = buffer.toString();
}
public Job() {
this(1000);
}
public Job(final String pattern, int count) {
super();
this.count = count;
this.pattern = pattern;
}
public int getCount() {
return this.count;
}
public String getPattern() {
return this.pattern;
}
public String getExpected() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < this.count; i++) {
buffer.append(this.pattern);
}
return buffer.toString();
}
public int getStatusCode() {
return this.statusCode;
}
public String getResult() {
return this.result;
}
public boolean isSuccessful() {
return this.result != null;
}
public String getFailureMessage() {
return this.failureMessage;
}
public Exception getException() {
return this.ex;
}
public boolean isCompleted() {
return this.completed;
}
public synchronized void setResult(int statusCode, final String result) {
if (this.completed) {
return;
}
this.completed = true;
this.statusCode = statusCode;
this.result = result;
notifyAll();
}
public synchronized void fail(final String message, final Exception ex) {
if (this.completed) {
return;
}
this.completed = true;
this.result = null;
this.failureMessage = message;
this.ex = ex;
notifyAll();
}
public void fail(final String message) {
fail(message, null);
}
public synchronized void waitFor() throws InterruptedException {
while (!this.completed) {
wait();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
public class OoopsieRuntimeException extends RuntimeException {
private static final long serialVersionUID = 662807254163212266L;
public OoopsieRuntimeException() {
super("Ooopsie!!!");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.http.mockup.HttpSSLClient;
import org.apache.http.mockup.HttpSSLServer;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
/**
* Base class for all HttpCore NIO tests
*/
public class HttpCoreNIOSSLTestBase extends TestCase {
public HttpCoreNIOSSLTestBase(String testName) {
super(testName);
}
protected HttpSSLServer server;
protected HttpSSLClient client;
@Override
protected void setUp() throws Exception {
HttpParams serverParams = new SyncBasicHttpParams();
serverParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.server = new HttpSSLServer(serverParams);
this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler());
HttpParams clientParams = new SyncBasicHttpParams();
clientParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.client = new HttpSSLClient(clientParams);
this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler());
}
@Override
protected void tearDown() {
try {
this.client.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
try {
this.server.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.EventListener;
public class SimpleEventListener implements EventListener {
public SimpleEventListener() {
super();
}
public void connectionOpen(final NHttpConnection conn) {
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out");
}
public void connectionClosed(final NHttpConnection conn) {
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
ex.printStackTrace(System.out);
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
ex.printStackTrace(System.out);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.params.HttpParams;
public class HttpSSLClient {
private final SSLContext sslcontext;
private final DefaultConnectingIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
public HttpSSLClient(final HttpParams params) throws Exception {
super();
this.params = params;
this.sslcontext = createSSLContext();
this.ioReactor = new DefaultConnectingIOReactor(2, this.params);
}
private TrustManagerFactory createTrustManagerFactory() throws NoSuchAlgorithmException {
String algo = TrustManagerFactory.getDefaultAlgorithm();
try {
return TrustManagerFactory.getInstance(algo);
} catch (NoSuchAlgorithmException ex) {
return TrustManagerFactory.getInstance("SunX509");
}
}
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
TrustManagerFactory tmfactory = createTrustManagerFactory();
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, trustmanagers, null);
return sslcontext;
}
public HttpParams getParams() {
return this.params;
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpClientHandler clientHandler,
final SSLContext sslcontext,
final HttpParams params) {
return new SSLClientIOEventDispatch(clientHandler, sslcontext, params);
}
private void execute(final NHttpClientHandler clientHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
clientHandler,
this.sslcontext,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) {
return this.ioReactor.connect(address, null, attachment, null);
}
public void start(final NHttpClientHandler clientHandler) {
this.thread = new IOReactorThread(clientHandler);
this.thread.start();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
if (this.thread != null) {
this.thread.join(500);
}
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpClientHandler clientHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpClientHandler clientHandler) {
super();
this.clientHandler = clientHandler;
}
@Override
public void run() {
try {
execute(this.clientHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.params.HttpParams;
/**
* Trivial test server based on HttpCore NIO
*
*/
public class HttpServerNio {
private final DefaultListeningIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
private ListenerEndpoint endpoint;
public HttpServerNio(final HttpParams params) throws IOException {
super();
this.ioReactor = new DefaultListeningIOReactor(2, params);
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpServiceHandler serviceHandler, final HttpParams params) {
return new DefaultServerIOEventDispatch(serviceHandler, params);
}
private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
serviceHandler,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public ListenerEndpoint getListenerEndpoint() {
return this.endpoint;
}
public void setEndpoint(ListenerEndpoint endpoint) {
this.endpoint = endpoint;
}
public void start(final NHttpServiceHandler serviceHandler) {
this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
this.thread = new IOReactorThread(serviceHandler);
this.thread.start();
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
join(500);
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpServiceHandler serviceHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
try {
execute(this.serviceHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.params.HttpParams;
public class HttpClientNio {
private final DefaultConnectingIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
public HttpClientNio(final HttpParams params) throws IOException {
super();
this.ioReactor = new DefaultConnectingIOReactor(2, params);
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpClientHandler clientHandler, final HttpParams params) {
return new DefaultClientIOEventDispatch(clientHandler, params);
}
private void execute(final NHttpClientHandler clientHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
clientHandler,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) {
return this.ioReactor.connect(address, null, attachment, null);
}
public void start(final NHttpClientHandler clientHandler) {
this.thread = new IOReactorThread(clientHandler);
this.thread.start();
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
join(500);
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpClientHandler clientHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpClientHandler clientHandler) {
super();
this.clientHandler = clientHandler;
}
@Override
public void run() {
try {
execute(this.clientHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.params.HttpParams;
/**
* Trivial test server based on HttpCore NIO SSL
*
*/
public class HttpSSLServer {
private final SSLContext sslcontext;
private final DefaultListeningIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
private ListenerEndpoint endpoint;
public HttpSSLServer(final HttpParams params) throws Exception {
super();
this.params = params;
this.sslcontext = createSSLContext();
this.ioReactor = new DefaultListeningIOReactor(2, this.params);
}
private KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException {
String algo = KeyManagerFactory.getDefaultAlgorithm();
try {
return KeyManagerFactory.getInstance(algo);
} catch (NoSuchAlgorithmException ex) {
return KeyManagerFactory.getInstance("SunX509");
}
}
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = createKeyManagerFactory();
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
return sslcontext;
}
public HttpParams getParams() {
return this.params;
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpServiceHandler serviceHandler,
final SSLContext sslcontext,
final HttpParams params) {
return new SSLServerIOEventDispatch(serviceHandler, sslcontext, params);
}
private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
serviceHandler,
this.sslcontext,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public ListenerEndpoint getListenerEndpoint() {
return this.endpoint;
}
public void start(final NHttpServiceHandler serviceHandler) {
this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
this.thread = new IOReactorThread(serviceHandler);
this.thread.start();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
if (this.thread != null) {
this.thread.join(500);
}
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpServiceHandler serviceHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
try {
execute(this.serviceHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.nio.codecs.AbstractContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
public class MockupEncoder extends AbstractContentEncoder {
// TODO? remove this field and the complete() and isCompleted() methods
private boolean completed;
public MockupEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
@Override
public boolean isCompleted() {
return this.completed;
}
@Override
public void complete() throws IOException {
this.completed = true;
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
if (this.completed) {
throw new IllegalStateException("Decoding process already completed");
}
return this.channel.write(src);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.http.nio.protocol.NHttpRequestHandlerResolver;
public class SimpleNHttpRequestHandlerResolver implements NHttpRequestHandlerResolver {
private final NHttpRequestHandler handler;
public SimpleNHttpRequestHandlerResolver(final NHttpRequestHandler handler) {
this.handler = handler;
}
public NHttpRequestHandler lookup(final String requestURI) {
return this.handler;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.util.EncodingUtils;
public class ReadableByteChannelMockup implements ReadableByteChannel {
private final String[] chunks;
private final String charset;
private int chunkCount = 0;
private ByteBuffer currentChunk;
private boolean closed = false;
public ReadableByteChannelMockup(final String[] chunks, final String charset) {
super();
this.chunks = chunks;
this.charset = charset;
}
private void prepareChunk() {
if (this.currentChunk == null || !this.currentChunk.hasRemaining()) {
if (this.chunkCount < this.chunks.length) {
String s = this.chunks[this.chunkCount];
this.chunkCount++;
this.currentChunk = ByteBuffer.wrap(EncodingUtils.getBytes(s, this.charset));
} else {
this.closed = true;
}
}
}
public int read(final ByteBuffer dst) throws IOException {
prepareChunk();
if (this.closed) {
return -1;
}
int i = 0;
while (dst.hasRemaining() && this.currentChunk.hasRemaining()) {
dst.put(this.currentChunk.get());
i++;
}
return i;
}
public void close() throws IOException {
this.closed = true;
}
public boolean isOpen() {
return !this.closed;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.nio.ContentDecoder;
public class MockupDecoder implements ContentDecoder {
private final ReadableByteChannel channel;
private boolean completed;
public MockupDecoder(final ReadableByteChannel channel) {
super();
this.channel = channel;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int bytesRead = this.channel.read(dst);
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
public boolean isCompleted() {
return this.completed;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.mockup;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
public class SimpleHttpRequestHandlerResolver implements HttpRequestHandlerResolver {
private final HttpRequestHandler handler;
public SimpleHttpRequestHandlerResolver(final HttpRequestHandler handler) {
super();
this.handler = handler;
}
public HttpRequestHandler lookup(final String requestURI) {
return this.handler;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.io.IOException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
class SimpleIOReactorExceptionHandler implements IOReactorExceptionHandler {
public boolean handle(final RuntimeException ex) {
if (!(ex instanceof OoopsieRuntimeException)) {
ex.printStackTrace(System.out);
}
return false;
}
public boolean handle(final IOException ex) {
ex.printStackTrace(System.out);
return false;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.http.mockup.HttpClientNio;
import org.apache.http.mockup.HttpServerNio;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
/**
* Base class for all HttpCore NIO tests
*
*/
public class HttpCoreNIOTestBase extends TestCase {
public HttpCoreNIOTestBase(String testName) {
super(testName);
}
protected HttpServerNio server;
protected HttpClientNio client;
@Override
protected void setUp() throws Exception {
HttpParams serverParams = new SyncBasicHttpParams();
serverParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.server = new HttpServerNio(serverParams);
this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler());
HttpParams clientParams = new SyncBasicHttpParams();
clientParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.client = new HttpClientNio(clientParams);
this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler());
}
@Override
protected void tearDown() {
try {
this.client.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
try {
this.server.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.sip;
import org.apache.http.Header;
/**
* Represents an SIP (or HTTP) header field with an optional compact name.
* RFC 3261 (SIP/2.0), section 7.3.3 specifies that some header field
* names have an abbreviated form which is equivalent to the full name.
* All compact header names defined for SIP are registered at
* <a href="http://www.iana.org/assignments/sip-parameters">
* http://www.iana.org/assignments/sip-parameters
* </a>.
* <br/>
* While all compact names defined so far are single-character names,
* RFC 3261 does not mandate that. This interface therefore allows for
* strings as the compact name.
*
*
*/
public interface CompactHeader extends Header {
/**
* Obtains the name of this header in compact form, if there is one.
*
* @return the compact name of this header, or
* <code>null</code> if there is none
*/
String getCompactName()
;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.