diff options
Diffstat (limited to 'lib/java/src/main/java/org/apache')
139 files changed, 3791 insertions, 4369 deletions
diff --git a/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java b/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java index 483c8d054..c7c4be303 100644 --- a/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java +++ b/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java @@ -24,32 +24,39 @@ import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.server.AbstractNonblockingServer; public abstract class AsyncProcessFunction<I, T extends TBase, R> { - final String methodName; + final String methodName; - public AsyncProcessFunction(String methodName) { - this.methodName = methodName; - } + public AsyncProcessFunction(String methodName) { + this.methodName = methodName; + } - protected abstract boolean isOneway(); + protected abstract boolean isOneway(); - public abstract void start(I iface, T args, AsyncMethodCallback<R> resultHandler) throws TException; + public abstract void start(I iface, T args, AsyncMethodCallback<R> resultHandler) + throws TException; - public abstract T getEmptyArgsInstance(); + public abstract T getEmptyArgsInstance(); - public abstract AsyncMethodCallback<R> getResultHandler(final AbstractNonblockingServer.AsyncFrameBuffer fb, int seqid); + public abstract AsyncMethodCallback<R> getResultHandler( + final AbstractNonblockingServer.AsyncFrameBuffer fb, int seqid); - public String getMethodName() { - return methodName; - } + public String getMethodName() { + return methodName; + } - public void sendResponse(final AbstractNonblockingServer.AsyncFrameBuffer fb, final TSerializable result, final byte type, final int seqid) throws TException { - TProtocol oprot = fb.getOutputProtocol(); + public void sendResponse( + final AbstractNonblockingServer.AsyncFrameBuffer fb, + final TSerializable result, + final byte type, + final int seqid) + throws TException { + TProtocol oprot = fb.getOutputProtocol(); - oprot.writeMessageBegin(new TMessage(getMethodName(), type, seqid)); - result.write(oprot); - oprot.writeMessageEnd(); - oprot.getTransport().flush(); + oprot.writeMessageBegin(new TMessage(getMethodName(), type, seqid)); + result.write(oprot); + oprot.writeMessageEnd(); + oprot.getTransport().flush(); - fb.responseReady(); - } + fb.responseReady(); + } } diff --git a/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java b/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java index d8cb1082b..d4bc7acc7 100644 --- a/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java +++ b/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java @@ -19,34 +19,27 @@ package org.apache.thrift; -/** - * Utility methods for use when encoding/decoding raw data as byte arrays. - */ +/** Utility methods for use when encoding/decoding raw data as byte arrays. */ public class EncodingUtils { /** - * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> - * starting at position 0 within that buffer. + * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> starting at position 0 + * within that buffer. * - * @param integer - * The integer to encode. - * @param buf - * The buffer to write to. + * @param integer The integer to encode. + * @param buf The buffer to write to. */ public static final void encodeBigEndian(final int integer, final byte[] buf) { encodeBigEndian(integer, buf, 0); } /** - * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> - * starting at position <code>offset</code>. + * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> starting at position + * <code>offset</code>. * - * @param integer - * The integer to encode. - * @param buf - * The buffer to write to. - * @param offset - * The offset within <code>buf</code> to start the encoding. + * @param integer The integer to encode. + * @param buf The buffer to write to. + * @param offset The offset within <code>buf</code> to start the encoding. */ public static final void encodeBigEndian(final int integer, final byte[] buf, int offset) { buf[offset] = (byte) (0xff & (integer >> 24)); @@ -56,11 +49,10 @@ public class EncodingUtils { } /** - * Decode a series of 4 bytes from <code>buf</code>, starting at position 0, - * and interpret them as an integer. + * Decode a series of 4 bytes from <code>buf</code>, starting at position 0, and interpret them as + * an integer. * - * @param buf - * The buffer to read from. + * @param buf The buffer to read from. * @return An integer, as read from the buffer. */ public static final int decodeBigEndian(final byte[] buf) { @@ -68,36 +60,33 @@ public class EncodingUtils { } /** - * Decode a series of 4 bytes from <code>buf</code>, start at - * <code>offset</code>, and interpret them as an integer. + * Decode a series of 4 bytes from <code>buf</code>, start at <code>offset</code>, and interpret + * them as an integer. * - * @param buf - * The buffer to read from. - * @param offset - * The offset with <code>buf</code> to start the decoding. + * @param buf The buffer to read from. + * @param offset The offset with <code>buf</code> to start the decoding. * @return An integer, as read from the buffer. */ public static final int decodeBigEndian(final byte[] buf, int offset) { - return ((buf[offset] & 0xff) << 24) | ((buf[offset + 1] & 0xff) << 16) - | ((buf[offset + 2] & 0xff) << 8) | ((buf[offset + 3] & 0xff)); + return ((buf[offset] & 0xff) << 24) + | ((buf[offset + 1] & 0xff) << 16) + | ((buf[offset + 2] & 0xff) << 8) + | ((buf[offset + 3] & 0xff)); } /** - * Bitfield utilities. - * Returns true if the bit at position is set in v. + * Bitfield utilities. Returns true if the bit at position is set in v. * - * @param v - * the value whose bit is to be checked. - * @param position - * the 0 based bit number indicating the bit to check. + * @param v the value whose bit is to be checked. + * @param position the 0 based bit number indicating the bit to check. * @return true if the bit at position is set in v. */ public static final boolean testBit(byte v, int position) { - return testBit((int)v, position); + return testBit((int) v, position); } public static final boolean testBit(short v, int position) { - return testBit((int)v, position); + return testBit((int) v, position); } public static final boolean testBit(int v, int position) { @@ -111,18 +100,16 @@ public class EncodingUtils { /** * Returns v, with the bit at position set to zero. * - * @param v - * the value whose bit is to be cleared. - * @param position - * the 0 based bit number indicating the bit to clear. + * @param v the value whose bit is to be cleared. + * @param position the 0 based bit number indicating the bit to clear. * @return v, with the bit at position set to zero. */ public static final byte clearBit(byte v, int position) { - return (byte)clearBit((int)v, position); + return (byte) clearBit((int) v, position); } public static final short clearBit(short v, int position) { - return (short)clearBit((int)v, position); + return (short) clearBit((int) v, position); } public static final int clearBit(int v, int position) { @@ -136,33 +123,26 @@ public class EncodingUtils { /** * Returns v, with the bit at position set to 1 or 0 depending on value. * - * @param v - * the value whose bit is to be set. - * @param position - * the 0 based bit number indicating the bit to set. - * @param value - * if true, the given bit is set to 1; otherwise it is set to 0. + * @param v the value whose bit is to be set. + * @param position the 0 based bit number indicating the bit to set. + * @param value if true, the given bit is set to 1; otherwise it is set to 0. * @return v, with the bit at position set to 0 (if value is false) or 1 (if value is true). */ public static final byte setBit(byte v, int position, boolean value) { - return (byte)setBit((int)v, position, value); + return (byte) setBit((int) v, position, value); } public static final short setBit(short v, int position, boolean value) { - return (short)setBit((int)v, position, value); + return (short) setBit((int) v, position, value); } public static final int setBit(int v, int position, boolean value) { - if(value) - return v | (1 << position); - else - return clearBit(v, position); + if (value) return v | (1 << position); + else return clearBit(v, position); } public static final long setBit(long v, int position, boolean value) { - if(value) - return v | (1L << position); - else - return clearBit(v, position); + if (value) return v | (1L << position); + else return clearBit(v, position); } } diff --git a/lib/java/src/main/java/org/apache/thrift/Option.java b/lib/java/src/main/java/org/apache/thrift/Option.java index 6b036df96..601bcc16a 100644 --- a/lib/java/src/main/java/org/apache/thrift/Option.java +++ b/lib/java/src/main/java/org/apache/thrift/Option.java @@ -21,120 +21,123 @@ package org.apache.thrift; import java.util.Optional; -/** - * Implementation of the Option type pattern - */ +/** Implementation of the Option type pattern */ public abstract class Option<T> { - @SuppressWarnings("rawtypes") - private static final Option NONE = new None(); - - /** - * Whether the Option is defined or not - * @return - * true if the Option is defined (of type Some) - * false if the Option is not defined (of type None) - */ - public abstract boolean isDefined(); - - /** - * Get the value of the Option (if it is defined) - * @return the value - * @throws IllegalStateException if called on a None - */ - public abstract T get(); - - /** - * Get the contained value (if defined) or else return a default value - * @param other what to return if the value is not defined (a None) - * @return either the value, or other if the value is not defined - */ - public T or(T other) { - if (isDefined()) { - return get(); - } else { - return other; - } + @SuppressWarnings("rawtypes") + private static final Option NONE = new None(); + + /** + * Whether the Option is defined or not + * + * @return true if the Option is defined (of type Some) false if the Option is not defined (of + * type None) + */ + public abstract boolean isDefined(); + + /** + * Get the value of the Option (if it is defined) + * + * @return the value + * @throws IllegalStateException if called on a None + */ + public abstract T get(); + + /** + * Get the contained value (if defined) or else return a default value + * + * @param other what to return if the value is not defined (a None) + * @return either the value, or other if the value is not defined + */ + public T or(T other) { + if (isDefined()) { + return get(); + } else { + return other; + } + } + + /** + * Turn this Option into Java 8 Optional type + * + * @return Java 8+ Optional Type + */ + public Optional<T> toOptional() { + if (isDefined()) { + return Optional.of(get()); + } else { + return Optional.empty(); } + } - /** - * Turn this Option into Java 8 Optional type - * @return Java 8+ Optional Type - */ - public Optional<T> toOptional() { - if (isDefined()) { - return Optional.of(get()); - } else { - return Optional.empty(); - } + /** The None type, representing an absent value (instead of "null") */ + public static class None<T> extends Option<T> { + public boolean isDefined() { + return false; } - /** - * The None type, representing an absent value (instead of "null") - */ - public static class None<T> extends Option<T> { - public boolean isDefined() { - return false; - } - - public T get() { - throw new IllegalStateException("Cannot call get() on None"); - } - - public String toString() { - return "None"; - } + public T get() { + throw new IllegalStateException("Cannot call get() on None"); } - /** - * The Some type, representing an existence of some value - * @param <T> The type of value - */ - public static class Some<T> extends Option<T> { - private final T value; - public Some(T value) { - this.value = value; - } - - public boolean isDefined() { - return true; - } - - public T get() { - return value; - } - - public String toString() { - return "Some(" + value + ")"; - } + public String toString() { + return "None"; + } + } + + /** + * The Some type, representing an existence of some value + * + * @param <T> The type of value + */ + public static class Some<T> extends Option<T> { + private final T value; + + public Some(T value) { + this.value = value; } - /** - * Wraps value in an Option type, depending on whether or not value is null - * @param value the value to wrap in Option - * @param <T> the type of value - * @return Some(value) if value is not null, None if value is null - */ - public static <T> Option<T> fromNullable(T value) { - if (value != null) { - return some(value); - } else { - return none(); - } + public boolean isDefined() { + return true; } - /** - * Wrap value in a Some type (NB! value must not be null!) - * @param value the value to wrap. - * @param <T> the type of value - * @return a new Some(value) - */ - public static <T> Some<T> some(T value) { - return new Some<T>(value); + public T get() { + return value; } - @SuppressWarnings("unchecked") - public static <T> None<T> none() { - return (None<T>) NONE; + public String toString() { + return "Some(" + value + ")"; + } + } + + /** + * Wraps value in an Option type, depending on whether or not value is null + * + * @param value the value to wrap in Option + * @param <T> the type of value + * @return Some(value) if value is not null, None if value is null + */ + public static <T> Option<T> fromNullable(T value) { + if (value != null) { + return some(value); + } else { + return none(); } + } + + /** + * Wrap value in a Some type (NB! value must not be null!) + * + * @param value the value to wrap. + * @param <T> the type of value + * @return a new Some(value) + */ + public static <T> Some<T> some(T value) { + return new Some<T>(value); + } + + @SuppressWarnings("unchecked") + public static <T> None<T> none() { + return (None<T>) NONE; + } } diff --git a/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java b/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java index e6213dfa1..7399342a2 100644 --- a/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java +++ b/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java @@ -17,13 +17,15 @@ public abstract class ProcessFunction<I, T extends TBase> { this.methodName = methodName; } - public final void process(int seqid, TProtocol iprot, TProtocol oprot, I iface) throws TException { + public final void process(int seqid, TProtocol iprot, TProtocol oprot, I iface) + throws TException { T args = getEmptyArgsInstance(); try { args.read(iprot); } catch (TProtocolException e) { iprot.readMessageEnd(); - TApplicationException x = new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); + TApplicationException x = + new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); x.write(oprot); oprot.writeMessageEnd(); @@ -45,15 +47,17 @@ public abstract class ProcessFunction<I, T extends TBase> { msgType = TMessageType.EXCEPTION; } catch (Exception ex) { LOGGER.error("Internal error processing " + getMethodName(), ex); - if(rethrowUnhandledExceptions()) throw new RuntimeException(ex.getMessage(), ex); - if(!isOneway()) { - result = new TApplicationException(TApplicationException.INTERNAL_ERROR, - "Internal error processing " + getMethodName()); + if (rethrowUnhandledExceptions()) throw new RuntimeException(ex.getMessage(), ex); + if (!isOneway()) { + result = + new TApplicationException( + TApplicationException.INTERNAL_ERROR, + "Internal error processing " + getMethodName()); msgType = TMessageType.EXCEPTION; } } - if(!isOneway()) { + if (!isOneway()) { oprot.writeMessageBegin(new TMessage(getMethodName(), msgType, seqid)); result.write(oprot); oprot.writeMessageEnd(); @@ -63,8 +67,9 @@ public abstract class ProcessFunction<I, T extends TBase> { private void handleException(int seqid, TProtocol oprot) throws TException { if (!isOneway()) { - TApplicationException x = new TApplicationException(TApplicationException.INTERNAL_ERROR, - "Internal error processing " + getMethodName()); + TApplicationException x = + new TApplicationException( + TApplicationException.INTERNAL_ERROR, "Internal error processing " + getMethodName()); oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); x.write(oprot); oprot.writeMessageEnd(); @@ -72,7 +77,7 @@ public abstract class ProcessFunction<I, T extends TBase> { } } - protected boolean rethrowUnhandledExceptions(){ + protected boolean rethrowUnhandledExceptions() { return false; } diff --git a/lib/java/src/main/java/org/apache/thrift/TApplicationException.java b/lib/java/src/main/java/org/apache/thrift/TApplicationException.java index 59cff6930..daf107223 100644 --- a/lib/java/src/main/java/org/apache/thrift/TApplicationException.java +++ b/lib/java/src/main/java/org/apache/thrift/TApplicationException.java @@ -25,15 +25,12 @@ import org.apache.thrift.protocol.TProtocolUtil; import org.apache.thrift.protocol.TStruct; import org.apache.thrift.protocol.TType; -/** - * Application level exception - * - */ +/** Application level exception */ public class TApplicationException extends TException implements TSerializable { private static final TStruct TAPPLICATION_EXCEPTION_STRUCT = new TStruct("TApplicationException"); - private static final TField MESSAGE_FIELD = new TField("message", TType.STRING, (short)1); - private static final TField TYPE_FIELD = new TField("type", TType.I32, (short)2); + private static final TField MESSAGE_FIELD = new TField("message", TType.STRING, (short) 1); + private static final TField TYPE_FIELD = new TField("type", TType.I32, (short) 2); private static final long serialVersionUID = 1L; @@ -78,14 +75,12 @@ public class TApplicationException extends TException implements TSerializable { public String getMessage() { if (message_ == null) { return super.getMessage(); - } - else { + } else { return message_; } } - public void read(TProtocol iprot) throws TException - { + public void read(TProtocol iprot) throws TException { TField field; iprot.readStructBegin(); @@ -130,15 +125,13 @@ public class TApplicationException extends TException implements TSerializable { * @return an instance of TApplicationException read from iprot. * @throws TException if there is an error reading from iprot. */ - public static TApplicationException readFrom(TProtocol iprot) throws TException - { + public static TApplicationException readFrom(TProtocol iprot) throws TException { TApplicationException result = new TApplicationException(); result.read(iprot); return result; } - public void write(TProtocol oprot) throws TException - { + public void write(TProtocol oprot) throws TException { oprot.writeStructBegin(TAPPLICATION_EXCEPTION_STRUCT); if (getMessage() != null) { oprot.writeFieldBegin(MESSAGE_FIELD); diff --git a/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java b/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java index d435b08c5..4dc9160bf 100644 --- a/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java @@ -23,9 +23,8 @@ import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer; public interface TAsyncProcessor { /** * Process a single frame. - - * <b>Note:</b> Implementations must call fb.responseReady() once processing - * is complete + * + * <p><b>Note:</b> Implementations must call fb.responseReady() once processing is complete * * @param fb the frame buffer to process. * @throws TException if the frame cannot be processed diff --git a/lib/java/src/main/java/org/apache/thrift/TBase.java b/lib/java/src/main/java/org/apache/thrift/TBase.java index be8ef9ba9..9c8bdbab1 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBase.java +++ b/lib/java/src/main/java/org/apache/thrift/TBase.java @@ -21,13 +21,9 @@ package org.apache.thrift; import java.io.Serializable; -import org.apache.thrift.protocol.TProtocol; - -/** - * Generic base interface for generated Thrift objects. - * - */ -public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Comparable<T>, TSerializable, Serializable { +/** Generic base interface for generated Thrift objects. */ +public interface TBase<T extends TBase<T, F>, F extends TFieldIdEnum> + extends Comparable<T>, TSerializable, Serializable { /** * Get the F instance that corresponds to fieldId. @@ -46,8 +42,8 @@ public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Com public boolean isSet(F field); /** - * Get a field's value by field variable. Primitive types will be wrapped in - * the appropriate "boxed" types. + * Get a field's value by field variable. Primitive types will be wrapped in the appropriate + * "boxed" types. * * @param field the field whose value is requested. * @return the value of the requested field. @@ -55,8 +51,8 @@ public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Com public Object getFieldValue(F field); /** - * Set a field's value by field variable. Primitive types must be "boxed" in - * the appropriate object wrapper type. + * Set a field's value by field variable. Primitive types must be "boxed" in the appropriate + * object wrapper type. * * @param field the field whose value is to be set. * @param value the value to be assigned to field. @@ -71,8 +67,8 @@ public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Com public T deepCopy(); /** - * Return to the state of having just been initialized, as though you had just - * called the default constructor. + * Return to the state of having just been initialized, as though you had just called the default + * constructor. */ public void clear(); } diff --git a/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java b/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java index f13f068ef..266f0c0ce 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java @@ -18,97 +18,96 @@ */ package org.apache.thrift; -import org.apache.thrift.protocol.*; +import java.util.Collections; +import java.util.Map; import org.apache.thrift.async.AsyncMethodCallback; - +import org.apache.thrift.protocol.*; import org.apache.thrift.server.AbstractNonblockingServer.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collections; -import java.util.Map; - public class TBaseAsyncProcessor<I> implements TAsyncProcessor, TProcessor { - protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); - - final I iface; - final Map<String,AsyncProcessFunction<I, ? extends TBase,?>> processMap; - - public TBaseAsyncProcessor(I iface, Map<String, AsyncProcessFunction<I, ? extends TBase,?>> processMap) { - this.iface = iface; - this.processMap = processMap; + protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); + + final I iface; + final Map<String, AsyncProcessFunction<I, ? extends TBase, ?>> processMap; + + public TBaseAsyncProcessor( + I iface, Map<String, AsyncProcessFunction<I, ? extends TBase, ?>> processMap) { + this.iface = iface; + this.processMap = processMap; + } + + public Map<String, AsyncProcessFunction<I, ? extends TBase, ?>> getProcessMapView() { + return Collections.unmodifiableMap(processMap); + } + + public void process(final AsyncFrameBuffer fb) throws TException { + + final TProtocol in = fb.getInputProtocol(); + final TProtocol out = fb.getOutputProtocol(); + + // Find processing function + final TMessage msg = in.readMessageBegin(); + AsyncProcessFunction fn = processMap.get(msg.name); + if (fn == null) { + TProtocolUtil.skip(in, TType.STRUCT); + in.readMessageEnd(); + + TApplicationException x = + new TApplicationException( + TApplicationException.UNKNOWN_METHOD, "Invalid method name: '" + msg.name + "'"); + LOGGER.debug("Invalid method name", x); + + // this means it is a two-way request, so we can send a reply + if (msg.type == TMessageType.CALL) { + out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); + x.write(out); + out.writeMessageEnd(); + out.getTransport().flush(); + } + fb.responseReady(); + return; } - public Map<String,AsyncProcessFunction<I, ? extends TBase,?>> getProcessMapView() { - return Collections.unmodifiableMap(processMap); + // Get Args + TBase args = fn.getEmptyArgsInstance(); + + try { + args.read(in); + } catch (TProtocolException e) { + in.readMessageEnd(); + + TApplicationException x = + new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); + LOGGER.debug("Could not retrieve function arguments", x); + + if (!fn.isOneway()) { + out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); + x.write(out); + out.writeMessageEnd(); + out.getTransport().flush(); + } + fb.responseReady(); + return; } + in.readMessageEnd(); - public void process(final AsyncFrameBuffer fb) throws TException { - - final TProtocol in = fb.getInputProtocol(); - final TProtocol out = fb.getOutputProtocol(); - - //Find processing function - final TMessage msg = in.readMessageBegin(); - AsyncProcessFunction fn = processMap.get(msg.name); - if (fn == null) { - TProtocolUtil.skip(in, TType.STRUCT); - in.readMessageEnd(); - - TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, - "Invalid method name: '" + msg.name + "'"); - LOGGER.debug("Invalid method name", x); - - // this means it is a two-way request, so we can send a reply - if (msg.type == TMessageType.CALL) { - out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); - x.write(out); - out.writeMessageEnd(); - out.getTransport().flush(); - } - fb.responseReady(); - return; - } - - //Get Args - TBase args = fn.getEmptyArgsInstance(); - - try { - args.read(in); - } catch (TProtocolException e) { - in.readMessageEnd(); - - TApplicationException x = new TApplicationException(TApplicationException.PROTOCOL_ERROR, - e.getMessage()); - LOGGER.debug("Could not retrieve function arguments", x); - - if (!fn.isOneway()) { - out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); - x.write(out); - out.writeMessageEnd(); - out.getTransport().flush(); - } - fb.responseReady(); - return; - } - in.readMessageEnd(); - - if (fn.isOneway()) { - fb.responseReady(); - } - - //start off processing function - AsyncMethodCallback resultHandler = fn.getResultHandler(fb, msg.seqid); - try { - fn.start(iface, args, resultHandler); - } catch (Exception e) { - LOGGER.debug("Exception handling function", e); - resultHandler.onError(e); - } - return; + if (fn.isOneway()) { + fb.responseReady(); } - @Override - public void process(TProtocol in, TProtocol out) throws TException { + // start off processing function + AsyncMethodCallback resultHandler = fn.getResultHandler(fb, msg.seqid); + try { + fn.start(iface, args, resultHandler); + } catch (Exception e) { + LOGGER.debug("Exception handling function", e); + resultHandler.onError(e); } + return; + } + + @Override + public void process(TProtocol in, TProtocol out) throws TException {} } diff --git a/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java b/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java index 6f6c6ebf5..be7a9f3c9 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java +++ b/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java @@ -1,24 +1,29 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; import java.io.Serializable; import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; @@ -26,28 +31,24 @@ import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; public final class TBaseHelper { - private TBaseHelper(){} + private TBaseHelper() {} private static final Comparator comparator = new NestedStructureComparator(); public static int compareTo(Object o1, Object o2) { if (o1 instanceof Comparable) { - return compareTo((Comparable)o1, (Comparable)o2); + return compareTo((Comparable) o1, (Comparable) o2); } else if (o1 instanceof List) { - return compareTo((List)o1, (List)o2); + return compareTo((List) o1, (List) o2); } else if (o1 instanceof Set) { - return compareTo((Set)o1, (Set)o2); + return compareTo((Set) o1, (Set) o2); } else if (o1 instanceof Map) { - return compareTo((Map)o1, (Map)o2); + return compareTo((Map) o1, (Map) o2); } else if (o1 instanceof byte[]) { - return compareTo((byte[])o1, (byte[])o2); + return compareTo((byte[]) o1, (byte[]) o2); } else { throw new IllegalArgumentException("Cannot compare objects of type " + o1.getClass()); } @@ -62,7 +63,7 @@ public final class TBaseHelper { } public static int compareTo(short a, short b) { - return Short.compare(a,b); + return Short.compare(a, b); } public static int compareTo(int a, int b) { @@ -165,9 +166,7 @@ public final class TBaseHelper { return 0; } - /** - * Comparator to compare items inside a structure (e.g. a list, set, or map). - */ + /** Comparator to compare items inside a structure (e.g. a list, set, or map). */ private static class NestedStructureComparator implements Comparator, Serializable { public int compare(Object oA, Object oB) { if (oA == null && oB == null) { @@ -177,15 +176,15 @@ public final class TBaseHelper { } else if (oB == null) { return 1; } else if (oA instanceof List) { - return compareTo((List)oA, (List)oB); + return compareTo((List) oA, (List) oB); } else if (oA instanceof Set) { - return compareTo((Set)oA, (Set)oB); + return compareTo((Set) oA, (Set) oB); } else if (oA instanceof Map) { - return compareTo((Map)oA, (Map)oB); + return compareTo((Map) oA, (Map) oB); } else if (oA instanceof byte[]) { - return compareTo((byte[])oA, (byte[])oB); + return compareTo((byte[]) oA, (byte[]) oB); } else { - return compareTo((Comparable)oA, (Comparable)oB); + return compareTo((Comparable) oA, (Comparable) oB); } } } @@ -244,14 +243,15 @@ public final class TBaseHelper { public static boolean wrapsFullArray(ByteBuffer byteBuffer) { return byteBuffer.hasArray() - && byteBuffer.position() == 0 - && byteBuffer.arrayOffset() == 0 - && byteBuffer.remaining() == byteBuffer.capacity(); + && byteBuffer.position() == 0 + && byteBuffer.arrayOffset() == 0 + && byteBuffer.remaining() == byteBuffer.capacity(); } public static int byteBufferToByteArray(ByteBuffer byteBuffer, byte[] target, int offset) { int remaining = byteBuffer.remaining(); - System.arraycopy(byteBuffer.array(), + System.arraycopy( + byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), target, offset, @@ -275,7 +275,8 @@ public final class TBaseHelper { } ByteBuffer copy = ByteBuffer.wrap(new byte[orig.remaining()]); if (orig.hasArray()) { - System.arraycopy(orig.array(), orig.arrayOffset() + orig.position(), copy.array(), 0, orig.remaining()); + System.arraycopy( + orig.array(), orig.arrayOffset() + orig.position(), copy.array(), 0, orig.remaining()); } else { orig.slice().get(copy.array()); } diff --git a/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java b/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java index 55a0f15d3..05cd7b8cc 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java @@ -2,7 +2,6 @@ package org.apache.thrift; import java.util.Collections; import java.util.Map; - import org.apache.thrift.protocol.TMessage; import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; @@ -11,14 +10,15 @@ import org.apache.thrift.protocol.TType; public abstract class TBaseProcessor<I> implements TProcessor { private final I iface; - private final Map<String,ProcessFunction<I, ? extends TBase>> processMap; + private final Map<String, ProcessFunction<I, ? extends TBase>> processMap; - protected TBaseProcessor(I iface, Map<String, ProcessFunction<I, ? extends TBase>> processFunctionMap) { + protected TBaseProcessor( + I iface, Map<String, ProcessFunction<I, ? extends TBase>> processFunctionMap) { this.iface = iface; this.processMap = processFunctionMap; } - public Map<String,ProcessFunction<I, ? extends TBase>> getProcessMapView() { + public Map<String, ProcessFunction<I, ? extends TBase>> getProcessMapView() { return Collections.unmodifiableMap(processMap); } @@ -29,7 +29,9 @@ public abstract class TBaseProcessor<I> implements TProcessor { if (fn == null) { TProtocolUtil.skip(in, TType.STRUCT); in.readMessageEnd(); - TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, "Invalid method name: '"+msg.name+"'"); + TApplicationException x = + new TApplicationException( + TApplicationException.UNKNOWN_METHOD, "Invalid method name: '" + msg.name + "'"); out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(out); out.writeMessageEnd(); diff --git a/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java b/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java index 3a2d56c88..69bb5ba80 100644 --- a/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java +++ b/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java @@ -22,11 +22,7 @@ package org.apache.thrift; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; -/** - * Class that allows access to the underlying buf without doing deep - * copies on it. - * - */ +/** Class that allows access to the underlying buf without doing deep copies on it. */ public class TByteArrayOutputStream extends ByteArrayOutputStream { private final int initialSize; diff --git a/lib/java/src/main/java/org/apache/thrift/TConfiguration.java b/lib/java/src/main/java/org/apache/thrift/TConfiguration.java index b98274aad..0391d5b23 100644 --- a/lib/java/src/main/java/org/apache/thrift/TConfiguration.java +++ b/lib/java/src/main/java/org/apache/thrift/TConfiguration.java @@ -18,84 +18,85 @@ */ package org.apache.thrift; - public class TConfiguration { - public static final int DEFAULT_MAX_MESSAGE_SIZE = 100 * 1024 * 1024; - public static final int DEFAULT_MAX_FRAME_SIZE = 16384000; // this value is used consistently across all Thrift libraries - public static final int DEFAULT_RECURSION_DEPTH = 64; + public static final int DEFAULT_MAX_MESSAGE_SIZE = 100 * 1024 * 1024; + public static final int DEFAULT_MAX_FRAME_SIZE = + 16384000; // this value is used consistently across all Thrift libraries + public static final int DEFAULT_RECURSION_DEPTH = 64; - private int maxMessageSize; - private int maxFrameSize; - private int recursionLimit; + private int maxMessageSize; + private int maxFrameSize; + private int recursionLimit; - public TConfiguration() { - this(DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_FRAME_SIZE, DEFAULT_RECURSION_DEPTH); - } - public TConfiguration(int maxMessageSize, int maxFrameSize, int recursionLimit) { - this.maxFrameSize = maxFrameSize; - this.maxMessageSize = maxMessageSize; - this.recursionLimit = recursionLimit; - } + public TConfiguration() { + this(DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_FRAME_SIZE, DEFAULT_RECURSION_DEPTH); + } - public int getMaxMessageSize() { - return maxMessageSize; - } + public TConfiguration(int maxMessageSize, int maxFrameSize, int recursionLimit) { + this.maxFrameSize = maxFrameSize; + this.maxMessageSize = maxMessageSize; + this.recursionLimit = recursionLimit; + } - public int getMaxFrameSize() { - return maxFrameSize; - } + public int getMaxMessageSize() { + return maxMessageSize; + } - public int getRecursionLimit() { - return recursionLimit; - } + public int getMaxFrameSize() { + return maxFrameSize; + } - public void setMaxMessageSize(int maxMessageSize) { - this.maxMessageSize = maxMessageSize; - } + public int getRecursionLimit() { + return recursionLimit; + } - public void setMaxFrameSize(int maxFrameSize) { - this.maxFrameSize = maxFrameSize; + public void setMaxMessageSize(int maxMessageSize) { + this.maxMessageSize = maxMessageSize; + } + + public void setMaxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + } + + public void setRecursionLimit(int recursionLimit) { + this.recursionLimit = recursionLimit; + } + + public static final TConfiguration DEFAULT = new Builder().build(); + + public static TConfiguration.Builder custom() { + return new Builder(); + } + + public static class Builder { + private int maxMessageSize; + private int maxFrameSize; + private int recursionLimit; + + Builder() { + super(); + this.maxFrameSize = DEFAULT_MAX_FRAME_SIZE; + this.maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE; + this.recursionLimit = DEFAULT_RECURSION_DEPTH; } - public void setRecursionLimit(int recursionLimit) { - this.recursionLimit = recursionLimit; + public Builder setMaxMessageSize(int maxMessageSize) { + this.maxMessageSize = maxMessageSize; + return this; } - public static final TConfiguration DEFAULT = new Builder().build(); + public Builder setMaxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + return this; + } - public static TConfiguration.Builder custom() { - return new Builder(); + public Builder setRecursionLimit(int recursionLimit) { + this.recursionLimit = recursionLimit; + return this; } - public static class Builder { - private int maxMessageSize ; - private int maxFrameSize; - private int recursionLimit ; - - Builder() { - super(); - this.maxFrameSize = DEFAULT_MAX_FRAME_SIZE; - this.maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE; - this.recursionLimit = DEFAULT_RECURSION_DEPTH; - } - - public Builder setMaxMessageSize(int maxMessageSize) { - this.maxMessageSize = maxMessageSize; - return this; - } - - public Builder setMaxFrameSize(int maxFrameSize) { - this.maxFrameSize = maxFrameSize; - return this; - } - - public Builder setRecursionLimit(int recursionLimit) { - this.recursionLimit = recursionLimit; - return this; - } - - public TConfiguration build() { - return new TConfiguration(maxMessageSize, maxFrameSize, recursionLimit); - } + public TConfiguration build() { + return new TConfiguration(maxMessageSize, maxFrameSize, recursionLimit); } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/TDeserializer.java b/lib/java/src/main/java/org/apache/thrift/TDeserializer.java index dd63996db..1cdc54870 100644 --- a/lib/java/src/main/java/org/apache/thrift/TDeserializer.java +++ b/lib/java/src/main/java/org/apache/thrift/TDeserializer.java @@ -19,6 +19,9 @@ package org.apache.thrift; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.util.Collection; import org.apache.thrift.meta_data.EnumMetaData; import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.partial.TFieldData; @@ -38,15 +41,7 @@ import org.apache.thrift.protocol.TType; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TTransportException; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.Collection; - -/** - * Generic utility for easily deserializing objects from a byte array or Java - * String. - * - */ +/** Generic utility for easily deserializing objects from a byte array or Java String. */ public class TDeserializer { private final TProtocol protocol_; private final TMemoryInputTransport trans_; @@ -67,8 +62,8 @@ public class TDeserializer { } /** - * Create a new TDeserializer. It will use the TProtocol specified by the - * factory that is passed in. + * Create a new TDeserializer. It will use the TProtocol specified by the factory that is passed + * in. * * @param protocolFactory Factory to create a protocol * @throws TTransportException if there an error initializing the underlying transport. @@ -79,8 +74,8 @@ public class TDeserializer { } /** - * Construct a new TDeserializer that supports partial deserialization - * that outputs instances of type controlled by the given {@code processor}. + * Construct a new TDeserializer that supports partial deserialization that outputs instances of + * type controlled by the given {@code processor}. * * @param thriftClass a TBase derived class. * @param fieldNames list of fields to deserialize. @@ -91,7 +86,8 @@ public class TDeserializer { Class<? extends TBase> thriftClass, Collection<String> fieldNames, ThriftFieldValueProcessor processor, - TProtocolFactory protocolFactory) throws TTransportException { + TProtocolFactory protocolFactory) + throws TTransportException { this(protocolFactory); Validate.checkNotNull(thriftClass, "thriftClass"); @@ -103,8 +99,8 @@ public class TDeserializer { } /** - * Construct a new TDeserializer that supports partial deserialization - * that outputs {@code TBase} instances. + * Construct a new TDeserializer that supports partial deserialization that outputs {@code TBase} + * instances. * * @param thriftClass a TBase derived class. * @param fieldNames list of fields to deserialize. @@ -113,7 +109,8 @@ public class TDeserializer { public TDeserializer( Class<? extends TBase> thriftClass, Collection<String> fieldNames, - TProtocolFactory protocolFactory) throws TTransportException { + TProtocolFactory protocolFactory) + throws TTransportException { this(thriftClass, fieldNames, new ThriftStructProcessor(), protocolFactory); } @@ -134,7 +131,7 @@ public class TDeserializer { * @throws TException if an error is encountered during deserialization. */ public void deserialize(TBase base, byte[] bytes) throws TException { - deserialize(base, bytes, 0, bytes.length); + deserialize(base, bytes, 0, bytes.length); } /** @@ -161,8 +158,7 @@ public class TDeserializer { } /** - * Deserialize the Thrift object from a Java string, using a specified - * character set for decoding. + * Deserialize the Thrift object from a Java string, using a specified character set for decoding. * * @param base The object to read into * @param data The string to read from @@ -180,15 +176,18 @@ public class TDeserializer { } /** - * Deserialize only a single Thrift object (addressed by recursively using field id) - * from a byte record. + * Deserialize only a single Thrift object (addressed by recursively using field id) from a byte + * record. + * * @param tb The object to read into * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path tb * @param fieldIdPathRest The rest FieldId's that define a path tb * @throws TException if an error is encountered during deserialization. */ - public void partialDeserialize(TBase tb, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public void partialDeserialize( + TBase tb, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { try { if (locateField(bytes, fieldIdPathFirst, fieldIdPathRest) != null) { // if this line is reached, iprot will be positioned at the start of tb. @@ -203,123 +202,143 @@ public class TDeserializer { } /** - * Deserialize only a boolean field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a boolean field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a boolean field * @param fieldIdPathRest The rest FieldId's that define a path to a boolean field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Boolean partialDeserializeBool(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Boolean partialDeserializeBool( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Boolean) partialDeserializeField(TType.BOOL, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a byte field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a byte field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a byte field * @param fieldIdPathRest The rest FieldId's that define a path to a byte field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Byte partialDeserializeByte(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Byte partialDeserializeByte( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Byte) partialDeserializeField(TType.BYTE, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a double field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a double field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a double field * @param fieldIdPathRest The rest FieldId's that define a path to a double field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Double partialDeserializeDouble(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Double partialDeserializeDouble( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Double) partialDeserializeField(TType.DOUBLE, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only an i16 field (addressed by recursively using field id) - * from a byte record. + * Deserialize only an i16 field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to an i16 field * @param fieldIdPathRest The rest FieldId's that define a path to an i16 field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Short partialDeserializeI16(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Short partialDeserializeI16( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Short) partialDeserializeField(TType.I16, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only an i32 field (addressed by recursively using field id) - * from a byte record. + * Deserialize only an i32 field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to an i32 field * @param fieldIdPathRest The rest FieldId's that define a path to an i32 field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Integer partialDeserializeI32(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Integer partialDeserializeI32( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Integer) partialDeserializeField(TType.I32, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only an i64 field (addressed by recursively using field id) - * from a byte record. + * Deserialize only an i64 field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to an i64 field * @param fieldIdPathRest The rest FieldId's that define a path to an i64 field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Long partialDeserializeI64(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Long partialDeserializeI64( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Long) partialDeserializeField(TType.I64, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a string field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a string field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a string field * @param fieldIdPathRest The rest FieldId's that define a path to a string field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public String partialDeserializeString(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public String partialDeserializeString( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (String) partialDeserializeField(TType.STRING, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a binary field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a binary field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a binary field * @param fieldIdPathRest The rest FieldId's that define a path to a binary field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public ByteBuffer partialDeserializeByteArray(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public ByteBuffer partialDeserializeByteArray( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { // TType does not have binary, so we use the arbitrary num 100 - return (ByteBuffer) partialDeserializeField((byte)100, bytes, fieldIdPathFirst, fieldIdPathRest); + return (ByteBuffer) + partialDeserializeField((byte) 100, bytes, fieldIdPathFirst, fieldIdPathRest); } /** * Deserialize only the id of the field set in a TUnion (addressed by recursively using field id) * from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a TUnion * @param fieldIdPathRest The rest FieldId's that define a path to a TUnion * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Short partialDeserializeSetFieldIdInUnion(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Short partialDeserializeSetFieldIdInUnion( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { try { TField field = locateField(bytes, fieldIdPathFirst, fieldIdPathRest); - if (field != null){ + if (field != null) { protocol_.readStructBegin(); // The Union return protocol_.readFieldBegin().id; // The field set in the union } @@ -332,7 +351,9 @@ public class TDeserializer { } } - private Object partialDeserializeField(byte ttype, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + private Object partialDeserializeField( + byte ttype, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { try { TField field = locateField(bytes, fieldIdPathFirst, fieldIdPathRest); if (field != null) { @@ -340,22 +361,22 @@ public class TDeserializer { // if this point is reached, iprot will be positioned at the start of // the field switch (ttype) { - case TType.BOOL: - return protocol_.readBool(); - case TType.BYTE: - return protocol_.readByte(); - case TType.DOUBLE: - return protocol_.readDouble(); - case TType.I16: - return protocol_.readI16(); - case TType.I32: - return protocol_.readI32(); - case TType.I64: - return protocol_.readI64(); - case TType.STRING: - return protocol_.readString(); - default: - return null; + case TType.BOOL: + return protocol_.readBool(); + case TType.BYTE: + return protocol_.readByte(); + case TType.DOUBLE: + return protocol_.readDouble(); + case TType.I16: + return protocol_.readI16(); + case TType.I32: + return protocol_.readI32(); + case TType.I64: + return protocol_.readI64(); + case TType.STRING: + return protocol_.readString(); + default: + return null; } } // hack to differentiate between string and binary @@ -372,7 +393,9 @@ public class TDeserializer { } } - private TField locateField(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + private TField locateField( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { trans_.reset(bytes); TFieldIdEnum[] fieldIdPath = new TFieldIdEnum[fieldIdPathRest.length + 1]; @@ -412,8 +435,7 @@ public class TDeserializer { } /** - * Deserialize the Thrift object from a Java string, using the default JVM - * charset encoding. + * Deserialize the Thrift object from a Java string, using the default JVM charset encoding. * * @param base The object to read into * @param data The string to read from @@ -569,9 +591,7 @@ public class TDeserializer { } private void deserializeStructField( - Object instance, - TFieldIdEnum fieldId, - ThriftMetadata.ThriftObject data) throws TException { + Object instance, TFieldIdEnum fieldId, ThriftMetadata.ThriftObject data) throws TException { byte fieldType = data.data.valueMetaData.type; Object value; @@ -695,8 +715,7 @@ public class TDeserializer { private void ensurePartialDeserializationMode() throws IllegalStateException { if (!this.isPartialDeserializationMode()) { throw new IllegalStateException( - "Members metadata and processor must be correctly initialized in order to use this method" - ); + "Members metadata and processor must be correctly initialized in order to use this method"); } } @@ -705,8 +724,7 @@ public class TDeserializer { if (!(this.processor_ instanceof ThriftStructProcessor)) { throw new IllegalStateException( - "processor must be an instance of ThriftStructProcessor to use this method" - ); + "processor must be an instance of ThriftStructProcessor to use this method"); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java b/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java index fbc778751..84aa82e8d 100644 --- a/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java +++ b/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java @@ -19,27 +19,20 @@ package org.apache.thrift; -import java.lang.NoSuchMethodException; -import java.lang.IllegalAccessException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -/** - * Utility class with static methods for interacting with TEnum - */ +/** Utility class with static methods for interacting with TEnum */ public class TEnumHelper { /** - * Given a TEnum class and integer value, this method will return - * the associated constant from the given TEnum class. - * This method MUST be modified should the name of the 'findByValue' method + * Given a TEnum class and integer value, this method will return the associated constant from the + * given TEnum class. This method MUST be modified should the name of the 'findByValue' method * change. * * @param enumClass TEnum from which to return a matching constant. * @param value Value for which to return the constant. - * - * @return The constant in 'enumClass' whose value is 'value' or null if - * something went wrong. + * @return The constant in 'enumClass' whose value is 'value' or null if something went wrong. */ public static TEnum getByValue(Class<? extends TEnum> enumClass, int value) { try { diff --git a/lib/java/src/main/java/org/apache/thrift/TException.java b/lib/java/src/main/java/org/apache/thrift/TException.java index f84f4812e..b2273d919 100644 --- a/lib/java/src/main/java/org/apache/thrift/TException.java +++ b/lib/java/src/main/java/org/apache/thrift/TException.java @@ -19,10 +19,7 @@ package org.apache.thrift; -/** - * Generic exception class for Thrift. - * - */ +/** Generic exception class for Thrift. */ public class TException extends Exception { private static final long serialVersionUID = 1L; diff --git a/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java b/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java index 20b845e61..f270630b0 100644 --- a/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java +++ b/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java @@ -18,9 +18,7 @@ */ package org.apache.thrift; -/** - * Interface for all generated struct Fields objects. - */ +/** Interface for all generated struct Fields objects. */ public interface TFieldIdEnum { /** * Gets the Thrift field id for the named field. diff --git a/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java b/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java index 74bac4eff..065cdfcc5 100644 --- a/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java +++ b/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java @@ -19,12 +19,9 @@ package org.apache.thrift; -/** - * Requirement type constants. - * - */ +/** Requirement type constants. */ public final class TFieldRequirementType { - public static final byte REQUIRED = 1; + public static final byte REQUIRED = 1; public static final byte OPTIONAL = 2; public static final byte DEFAULT = 3; } diff --git a/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java b/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java index d797a606f..28ae13880 100644 --- a/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java @@ -19,19 +19,20 @@ package org.apache.thrift; -import org.apache.thrift.protocol.*; - -import java.util.Map; import java.util.HashMap; +import java.util.Map; +import org.apache.thrift.protocol.*; /** - * <code>TMultiplexedProcessor</code> is a <code>TProcessor</code> allowing - * a single <code>TServer</code> to provide multiple services. + * <code>TMultiplexedProcessor</code> is a <code>TProcessor</code> allowing a single <code>TServer + * </code> to provide multiple services. + * + * <p>To do so, you instantiate the processor and then register additional processors with it, as + * shown in the following example: * - * <p>To do so, you instantiate the processor and then register additional - * processors with it, as shown in the following example:</p> + * <blockquote> * - * <blockquote><code> + * <code> * TMultiplexedProcessor processor = new TMultiplexedProcessor(); * * processor.registerProcessor( @@ -46,113 +47,121 @@ import java.util.HashMap; * TSimpleServer server = new TSimpleServer(processor, t); * * server.serve(); - * </code></blockquote> + * </code> + * + * </blockquote> */ public class TMultiplexedProcessor implements TProcessor { - private final Map<String,TProcessor> SERVICE_PROCESSOR_MAP - = new HashMap<String,TProcessor>(); - private TProcessor defaultProcessor; + private final Map<String, TProcessor> SERVICE_PROCESSOR_MAP = new HashMap<String, TProcessor>(); + private TProcessor defaultProcessor; - /** - * 'Register' a service with this <code>TMultiplexedProcessor</code>. This - * allows us to broker requests to individual services by using the service - * name to select them at request time. - * - * @param serviceName Name of a service, has to be identical to the name - * declared in the Thrift IDL, e.g. "WeatherReport". - * @param processor Implementation of a service, usually referred to - * as "handlers", e.g. WeatherReportHandler implementing WeatherReport.Iface. - */ - public void registerProcessor(String serviceName, TProcessor processor) { - SERVICE_PROCESSOR_MAP.put(serviceName, processor); - } + /** + * 'Register' a service with this <code>TMultiplexedProcessor</code>. This allows us to broker + * requests to individual services by using the service name to select them at request time. + * + * @param serviceName Name of a service, has to be identical to the name declared in the Thrift + * IDL, e.g. "WeatherReport". + * @param processor Implementation of a service, usually referred to as "handlers", e.g. + * WeatherReportHandler implementing WeatherReport.Iface. + */ + public void registerProcessor(String serviceName, TProcessor processor) { + SERVICE_PROCESSOR_MAP.put(serviceName, processor); + } - /** - * Register a service to be called to process queries without service name - * @param processor the service to be called. - */ - public void registerDefault(TProcessor processor) { - defaultProcessor = processor; + /** + * Register a service to be called to process queries without service name + * + * @param processor the service to be called. + */ + public void registerDefault(TProcessor processor) { + defaultProcessor = processor; + } + + /** + * This implementation of <code>process</code> performs the following steps: + * + * <ol> + * <li>Read the beginning of the message. + * <li>Extract the service name from the message. + * <li>Using the service name to locate the appropriate processor. + * <li>Dispatch to the processor, with a decorated instance of TProtocol that allows + * readMessageBegin() to return the original TMessage. + * </ol> + * + * @throws TProtocolException If the message type is not CALL or ONEWAY, if the service name was + * not found in the message, or if the service name was not found in the service map. You + * called {@link #registerProcessor(String, TProcessor) registerProcessor} during + * initialization, right? :) + */ + public void process(TProtocol iprot, TProtocol oprot) throws TException { + /* + Use the actual underlying protocol (e.g. TBinaryProtocol) to read the + message header. This pulls the message "off the wire", which we'll + deal with at the end of this method. + */ + TMessage message = iprot.readMessageBegin(); + + if (message.type != TMessageType.CALL && message.type != TMessageType.ONEWAY) { + throw new TProtocolException( + TProtocolException.NOT_IMPLEMENTED, "This should not have happened!?"); } - /** - * This implementation of <code>process</code> performs the following steps: - * - * <ol> - * <li>Read the beginning of the message.</li> - * <li>Extract the service name from the message.</li> - * <li>Using the service name to locate the appropriate processor.</li> - * <li>Dispatch to the processor, with a decorated instance of TProtocol - * that allows readMessageBegin() to return the original TMessage.</li> - * </ol> - * - * @throws TProtocolException If the message type is not CALL or ONEWAY, if - * the service name was not found in the message, or if the service - * name was not found in the service map. You called {@link #registerProcessor(String, TProcessor) registerProcessor} - * during initialization, right? :) - */ - public void process(TProtocol iprot, TProtocol oprot) throws TException { - /* - Use the actual underlying protocol (e.g. TBinaryProtocol) to read the - message header. This pulls the message "off the wire", which we'll - deal with at the end of this method. - */ - TMessage message = iprot.readMessageBegin(); + // Extract the service name + int index = message.name.indexOf(TMultiplexedProtocol.SEPARATOR); + if (index < 0) { + if (defaultProcessor != null) { + // Dispatch processing to the stored processor + defaultProcessor.process(new StoredMessageProtocol(iprot, message), oprot); + return; + } + throw new TProtocolException( + TProtocolException.NOT_IMPLEMENTED, + "Service name not found in message name: " + + message.name + + ". Did you " + + "forget to use a TMultiplexProtocol in your client?"); + } - if (message.type != TMessageType.CALL && message.type != TMessageType.ONEWAY) { - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "This should not have happened!?"); - } + // Create a new TMessage, something that can be consumed by any TProtocol + String serviceName = message.name.substring(0, index); + TProcessor actualProcessor = SERVICE_PROCESSOR_MAP.get(serviceName); + if (actualProcessor == null) { + throw new TProtocolException( + TProtocolException.NOT_IMPLEMENTED, + "Service name not found: " + + serviceName + + ". Did you forget " + + "to call registerProcessor()?"); + } - // Extract the service name - int index = message.name.indexOf(TMultiplexedProtocol.SEPARATOR); - if (index < 0) { - if (defaultProcessor != null) { - // Dispatch processing to the stored processor - defaultProcessor.process(new StoredMessageProtocol(iprot, message), oprot); - return; - } - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Service name not found in message name: " + message.name + ". Did you " + - "forget to use a TMultiplexProtocol in your client?"); - } + // Create a new TMessage, removing the service name + TMessage standardMessage = + new TMessage( + message.name.substring(serviceName.length() + TMultiplexedProtocol.SEPARATOR.length()), + message.type, + message.seqid); - // Create a new TMessage, something that can be consumed by any TProtocol - String serviceName = message.name.substring(0, index); - TProcessor actualProcessor = SERVICE_PROCESSOR_MAP.get(serviceName); - if (actualProcessor == null) { - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Service name not found: " + serviceName + ". Did you forget " + - "to call registerProcessor()?"); - } + // Dispatch processing to the stored processor + actualProcessor.process(new StoredMessageProtocol(iprot, standardMessage), oprot); + } - // Create a new TMessage, removing the service name - TMessage standardMessage = new TMessage( - message.name.substring(serviceName.length()+TMultiplexedProtocol.SEPARATOR.length()), - message.type, - message.seqid - ); + /** + * Our goal was to work with any protocol. In order to do that, we needed to allow them to call + * readMessageBegin() and get a TMessage in exactly the standard format, without the service name + * prepended to TMessage.name. + */ + private static class StoredMessageProtocol extends TProtocolDecorator { + TMessage messageBegin; - // Dispatch processing to the stored processor - actualProcessor.process(new StoredMessageProtocol(iprot, standardMessage), oprot); + public StoredMessageProtocol(TProtocol protocol, TMessage messageBegin) { + super(protocol); + this.messageBegin = messageBegin; } - /** - * Our goal was to work with any protocol. In order to do that, we needed - * to allow them to call readMessageBegin() and get a TMessage in exactly - * the standard format, without the service name prepended to TMessage.name. - */ - private static class StoredMessageProtocol extends TProtocolDecorator { - TMessage messageBegin; - public StoredMessageProtocol(TProtocol protocol, TMessage messageBegin) { - super(protocol); - this.messageBegin = messageBegin; - } - @Override - public TMessage readMessageBegin() throws TException { - return messageBegin; - } + @Override + public TMessage readMessageBegin() throws TException { + return messageBegin; } - + } } diff --git a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java index 13e8031b6..034cc8599 100644 --- a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java +++ b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java @@ -1,25 +1,23 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -35,49 +33,39 @@ import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * This class uses a single thread to set up non-blocking sockets to a set - * of remote servers (hostname and port pairs), and sends a same request to - * all these servers. It then fetches responses from servers. + * This class uses a single thread to set up non-blocking sockets to a set of remote servers + * (hostname and port pairs), and sends a same request to all these servers. It then fetches + * responses from servers. * - * Parameters: - * int maxRecvBufBytesPerServer - an upper limit for receive buffer size - * per server (in byte). If a response from a server exceeds this limit, the - * client will not allocate memory or read response data for it. + * <p>Parameters: int maxRecvBufBytesPerServer - an upper limit for receive buffer size per server + * (in byte). If a response from a server exceeds this limit, the client will not allocate memory or + * read response data for it. * - * int fetchTimeoutSeconds - time limit for fetching responses from all - * servers (in second). After the timeout, the fetch job is stopped and - * available responses are returned. + * <p>int fetchTimeoutSeconds - time limit for fetching responses from all servers (in second). + * After the timeout, the fetch job is stopped and available responses are returned. * - * ByteBuffer requestBuf - request message that is sent to all servers. + * <p>ByteBuffer requestBuf - request message that is sent to all servers. * - * Output: - * Responses are stored in an array of ByteBuffers. Index of elements in - * this array corresponds to index of servers in the server list. Content in - * a ByteBuffer may be in one of the following forms: - * 1. First 4 bytes form an integer indicating length of following data, - * then followed by the data. - * 2. First 4 bytes form an integer indicating length of following data, - * then followed by nothing - this happens when the response data size - * exceeds maxRecvBufBytesPerServer, and the client will not read any - * response data. - * 3. No data in the ByteBuffer - this happens when the server does not - * return any response within fetchTimeoutSeconds. + * <p>Output: Responses are stored in an array of ByteBuffers. Index of elements in this array + * corresponds to index of servers in the server list. Content in a ByteBuffer may be in one of the + * following forms: 1. First 4 bytes form an integer indicating length of following data, then + * followed by the data. 2. First 4 bytes form an integer indicating length of following data, then + * followed by nothing - this happens when the response data size exceeds maxRecvBufBytesPerServer, + * and the client will not read any response data. 3. No data in the ByteBuffer - this happens when + * the server does not return any response within fetchTimeoutSeconds. * - * In some special cases (no servers are given, fetchTimeoutSeconds less - * than or equal to 0, requestBuf is null), the return is null. - * - * Note: - * It assumes all remote servers are TNonblockingServers and use - * TFramedTransport. + * <p>In some special cases (no servers are given, fetchTimeoutSeconds less than or equal to 0, + * requestBuf is null), the return is null. * + * <p>Note: It assumes all remote servers are TNonblockingServers and use TFramedTransport. */ public class TNonblockingMultiFetchClient { - private static final Logger LOGGER = LoggerFactory.getLogger( - TNonblockingMultiFetchClient.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingMultiFetchClient.class); // if the size of the response msg exceeds this limit (in byte), we will // not read the msg @@ -97,9 +85,11 @@ public class TNonblockingMultiFetchClient { private TNonblockingMultiFetchStats stats; private ByteBuffer[] recvBuf; - public TNonblockingMultiFetchClient(int maxRecvBufBytesPerServer, - int fetchTimeoutSeconds, ByteBuffer requestBuf, - List<InetSocketAddress> servers) { + public TNonblockingMultiFetchClient( + int maxRecvBufBytesPerServer, + int fetchTimeoutSeconds, + ByteBuffer requestBuf, + List<InetSocketAddress> servers) { this.maxRecvBufBytesPerServer = maxRecvBufBytesPerServer; this.fetchTimeoutSeconds = fetchTimeoutSeconds; this.requestBuf = requestBuf; @@ -154,8 +144,7 @@ public class TNonblockingMultiFetchClient { recvBuf = null; stats.clear(); - if (servers == null || servers.size() == 0 || - requestBuf == null || fetchTimeoutSeconds <= 0) { + if (servers == null || servers.size() == 0 || requestBuf == null || fetchTimeoutSeconds <= 0) { return recvBuf; } @@ -185,9 +174,8 @@ public class TNonblockingMultiFetchClient { } /** - * Private class that does real fetch job. - * Users are not allowed to directly use this class, as its run() - * function may run forever. + * Private class that does real fetch job. Users are not allowed to directly use this class, as + * its run() function may run forever. */ private class MultiFetch implements Runnable { private Selector selector; @@ -195,11 +183,11 @@ public class TNonblockingMultiFetchClient { /** * main entry function for fetching. * - * Server responses are stored in TNonblocingMultiFetchClient.recvBuf, - * and fetch statistics is in TNonblockingMultiFetchClient.stats. + * <p>Server responses are stored in TNonblocingMultiFetchClient.recvBuf, and fetch statistics + * is in TNonblockingMultiFetchClient.stats. * - * Sanity check for parameters has been done in - * TNonblockingMultiFetchClient before calling this function. + * <p>Sanity check for parameters has been done in TNonblockingMultiFetchClient before calling + * this function. */ public void run() { long t1 = System.currentTimeMillis(); @@ -208,7 +196,7 @@ public class TNonblockingMultiFetchClient { stats.setNumTotalServers(numTotalServers); // buffer for receiving response from servers - recvBuf = new ByteBuffer[numTotalServers]; + recvBuf = new ByteBuffer[numTotalServers]; // buffer for sending request ByteBuffer[] sendBuf = new ByteBuffer[numTotalServers]; long[] numBytesRead = new long[numTotalServers]; @@ -246,23 +234,26 @@ public class TNonblockingMultiFetchClient { // free resource if (s != null) { - try {s.close();} catch (Exception ex) {} + try { + s.close(); + } catch (Exception ex) { + } } if (key != null) { - key.cancel(); + key.cancel(); } } } // wait for events - while (stats.getNumReadCompletedServers() + - stats.getNumConnectErrorServers() < stats.getNumTotalServers()) { + while (stats.getNumReadCompletedServers() + stats.getNumConnectErrorServers() + < stats.getNumTotalServers()) { // if the thread is interrupted (e.g., task is cancelled) if (Thread.currentThread().isInterrupted()) { return; } - try{ + try { selector.select(); } catch (Exception e) { LOGGER.error("Selector selects error", e); @@ -275,13 +266,13 @@ public class TNonblockingMultiFetchClient { it.remove(); // get previously attached index - int index = (Integer)selKey.attachment(); + int index = (Integer) selKey.attachment(); if (selKey.isValid() && selKey.isConnectable()) { // if this socket throws an exception (e.g., connection refused), // print error msg and skip it. try { - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); sChannel.finishConnect(); } catch (Exception e) { stats.incNumConnectErrorServers(); @@ -294,7 +285,7 @@ public class TNonblockingMultiFetchClient { // if this socket throws an exception, print error msg and // skip it. try { - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); sChannel.write(sendBuf[index]); } catch (Exception e) { LOGGER.error("Socket {} writes to server {} error", index, servers.get(index), e); @@ -306,34 +297,38 @@ public class TNonblockingMultiFetchClient { // if this socket throws an exception, print error msg and // skip it. try { - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); int bytesRead = sChannel.read(recvBuf[index]); if (bytesRead > 0) { numBytesRead[index] += bytesRead; - if (!hasReadFrameSize[index] && - recvBuf[index].remaining()==0) { + if (!hasReadFrameSize[index] && recvBuf[index].remaining() == 0) { // if the frame size has been read completely, then prepare // to read the actual frame. frameSize[index] = recvBuf[index].getInt(0); if (frameSize[index] <= 0) { stats.incNumInvalidFrameSize(); - LOGGER.error("Read an invalid frame size {} from {}. Does the server use TFramedTransport?", - frameSize[index], servers.get(index)); + LOGGER.error( + "Read an invalid frame size {} from {}. Does the server use TFramedTransport?", + frameSize[index], + servers.get(index)); sChannel.close(); continue; } if (frameSize[index] + 4 > stats.getMaxResponseBytes()) { - stats.setMaxResponseBytes(frameSize[index]+4); + stats.setMaxResponseBytes(frameSize[index] + 4); } if (frameSize[index] + 4 > maxRecvBufBytesPerServer) { stats.incNumOverflowedRecvBuf(); - LOGGER.error("Read frame size {} from {}, total buffer size would exceed limit {}", - frameSize[index], servers.get(index), maxRecvBufBytesPerServer); + LOGGER.error( + "Read frame size {} from {}, total buffer size would exceed limit {}", + frameSize[index], + servers.get(index), + maxRecvBufBytesPerServer); sChannel.close(); continue; } @@ -346,34 +341,30 @@ public class TNonblockingMultiFetchClient { hasReadFrameSize[index] = true; } - if (hasReadFrameSize[index] && - numBytesRead[index] >= frameSize[index]+4) { + if (hasReadFrameSize[index] && numBytesRead[index] >= frameSize[index] + 4) { // has read all data sChannel.close(); stats.incNumReadCompletedServers(); long t2 = System.currentTimeMillis(); - stats.setReadTime(t2-t1); + stats.setReadTime(t2 - t1); } } } catch (Exception e) { - LOGGER.error("Socket {} reads from server {} error", - index, servers.get(index), e); + LOGGER.error("Socket {} reads from server {} error", index, servers.get(index), e); } } } } } - /** - * dispose any resource allocated - */ + /** dispose any resource allocated */ public void close() { try { if (selector.isOpen()) { Iterator<SelectionKey> it = selector.keys().iterator(); while (it.hasNext()) { SelectionKey selKey = it.next(); - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); sChannel.close(); } diff --git a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java index 90b86208b..bc0243738 100644 --- a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java +++ b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java @@ -1,36 +1,35 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; -/** - * This class keeps track of statistics for TNonblockinMultiFetchClient. - */ +/** This class keeps track of statistics for TNonblockinMultiFetchClient. */ public class TNonblockingMultiFetchStats { - private int numTotalServers; - private int numReadCompletedServers; - private int numConnectErrorServers; - private int totalRecvBufBytes; - private int maxResponseBytes; - private int numOverflowedRecvBuf; - private int numInvalidFrameSize; + private int numTotalServers; + private int numReadCompletedServers; + private int numConnectErrorServers; + private int totalRecvBufBytes; + private int maxResponseBytes; + private int numOverflowedRecvBuf; + private int numInvalidFrameSize; // time from the beginning of fetch() function to the reading finish // time of the last socket (in milli-second) - private long readTime; + private long readTime; public TNonblockingMultiFetchStats() { clear(); @@ -48,33 +47,86 @@ public class TNonblockingMultiFetchStats { } public String toString() { - String stats = String.format("numTotalServers=%d, " + - "numReadCompletedServers=%d, numConnectErrorServers=%d, " + - "numUnresponsiveServers=%d, totalRecvBufBytes=%fM, " + - "maxResponseBytes=%d, numOverflowedRecvBuf=%d, " + - "numInvalidFrameSize=%d, readTime=%dms", - numTotalServers, numReadCompletedServers, numConnectErrorServers, - (numTotalServers-numReadCompletedServers-numConnectErrorServers), - totalRecvBufBytes/1024.0/1024, maxResponseBytes, numOverflowedRecvBuf, - numInvalidFrameSize, readTime); + String stats = + String.format( + "numTotalServers=%d, " + + "numReadCompletedServers=%d, numConnectErrorServers=%d, " + + "numUnresponsiveServers=%d, totalRecvBufBytes=%fM, " + + "maxResponseBytes=%d, numOverflowedRecvBuf=%d, " + + "numInvalidFrameSize=%d, readTime=%dms", + numTotalServers, + numReadCompletedServers, + numConnectErrorServers, + (numTotalServers - numReadCompletedServers - numConnectErrorServers), + totalRecvBufBytes / 1024.0 / 1024, + maxResponseBytes, + numOverflowedRecvBuf, + numInvalidFrameSize, + readTime); return stats; } - public void setNumTotalServers(int val) { numTotalServers = val; } - public void setMaxResponseBytes(int val) { maxResponseBytes = val; } - public void setReadTime(long val) { readTime = val; } - public void incNumReadCompletedServers() { numReadCompletedServers++; } - public void incNumConnectErrorServers() { numConnectErrorServers++; } - public void incNumOverflowedRecvBuf() { numOverflowedRecvBuf++; } - public void incTotalRecvBufBytes(int val) { totalRecvBufBytes += val; } - public void incNumInvalidFrameSize() { numInvalidFrameSize++; } - - public int getMaxResponseBytes() { return maxResponseBytes; } - public int getNumReadCompletedServers() { return numReadCompletedServers; } - public int getNumConnectErrorServers() { return numConnectErrorServers; } - public int getNumTotalServers() { return numTotalServers; } - public int getNumOverflowedRecvBuf() { return numOverflowedRecvBuf;} - public int getTotalRecvBufBytes() { return totalRecvBufBytes;} - public int getNumInvalidFrameSize() { return numInvalidFrameSize; } - public long getReadTime() { return readTime; } + public void setNumTotalServers(int val) { + numTotalServers = val; + } + + public void setMaxResponseBytes(int val) { + maxResponseBytes = val; + } + + public void setReadTime(long val) { + readTime = val; + } + + public void incNumReadCompletedServers() { + numReadCompletedServers++; + } + + public void incNumConnectErrorServers() { + numConnectErrorServers++; + } + + public void incNumOverflowedRecvBuf() { + numOverflowedRecvBuf++; + } + + public void incTotalRecvBufBytes(int val) { + totalRecvBufBytes += val; + } + + public void incNumInvalidFrameSize() { + numInvalidFrameSize++; + } + + public int getMaxResponseBytes() { + return maxResponseBytes; + } + + public int getNumReadCompletedServers() { + return numReadCompletedServers; + } + + public int getNumConnectErrorServers() { + return numConnectErrorServers; + } + + public int getNumTotalServers() { + return numTotalServers; + } + + public int getNumOverflowedRecvBuf() { + return numOverflowedRecvBuf; + } + + public int getTotalRecvBufBytes() { + return totalRecvBufBytes; + } + + public int getNumInvalidFrameSize() { + return numInvalidFrameSize; + } + + public long getReadTime() { + return readTime; + } } diff --git a/lib/java/src/main/java/org/apache/thrift/TProcessor.java b/lib/java/src/main/java/org/apache/thrift/TProcessor.java index 15ba9c0fe..3a0e6fd2b 100644 --- a/lib/java/src/main/java/org/apache/thrift/TProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TProcessor.java @@ -22,8 +22,8 @@ package org.apache.thrift; import org.apache.thrift.protocol.TProtocol; /** - * A processor is a generic object which operates upon an input stream and - * writes to some output stream. + * A processor is a generic object which operates upon an input stream and writes to some output + * stream. */ public interface TProcessor { public void process(TProtocol in, TProtocol out) throws TException; diff --git a/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java b/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java index 81933a211..fab4005ae 100644 --- a/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java @@ -21,10 +21,7 @@ package org.apache.thrift; import org.apache.thrift.transport.TTransport; -/** - * The default processor factory just returns a singleton - * instance. - */ +/** The default processor factory just returns a singleton instance. */ public class TProcessorFactory { private final TProcessor processor_; @@ -38,6 +35,6 @@ public class TProcessorFactory { } public boolean isAsyncProcessor() { - return processor_ instanceof TAsyncProcessor; + return processor_ instanceof TAsyncProcessor; } } diff --git a/lib/java/src/main/java/org/apache/thrift/TSerializable.java b/lib/java/src/main/java/org/apache/thrift/TSerializable.java index 317814b45..125280418 100644 --- a/lib/java/src/main/java/org/apache/thrift/TSerializable.java +++ b/lib/java/src/main/java/org/apache/thrift/TSerializable.java @@ -21,10 +21,7 @@ package org.apache.thrift; import org.apache.thrift.protocol.TProtocol; -/** - * Generic base interface for generated Thrift objects. - * - */ +/** Generic base interface for generated Thrift objects. */ public interface TSerializable { /** @@ -42,5 +39,4 @@ public interface TSerializable { * @throws TException if there is an error writing to oprot */ public void write(TProtocol oprot) throws TException; - } diff --git a/lib/java/src/main/java/org/apache/thrift/TSerializer.java b/lib/java/src/main/java/org/apache/thrift/TSerializer.java index 710cd2124..6c0c7c2f8 100644 --- a/lib/java/src/main/java/org/apache/thrift/TSerializer.java +++ b/lib/java/src/main/java/org/apache/thrift/TSerializer.java @@ -20,33 +20,22 @@ package org.apache.thrift; import java.io.ByteArrayOutputStream; - import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransportException; -/** - * Generic utility for easily serializing objects into a byte array or Java - * String. - * - */ +/** Generic utility for easily serializing objects into a byte array or Java String. */ public class TSerializer { - /** - * This is the byte array that data is actually serialized into - */ + /** This is the byte array that data is actually serialized into */ private final ByteArrayOutputStream baos_ = new ByteArrayOutputStream(); - /** - * This transport wraps that byte array - */ + /** This transport wraps that byte array */ private final TIOStreamTransport transport_; - /** - * Internal protocol used for serializing objects. - */ + /** Internal protocol used for serializing objects. */ private TProtocol protocol_; /** @@ -59,8 +48,7 @@ public class TSerializer { } /** - * Create a new TSerializer. It will use the TProtocol specified by the - * factory that is passed in. + * Create a new TSerializer. It will use the TProtocol specified by the factory that is passed in. * * @param protocolFactory Factory to create a protocol * @throws TTransportException if there an error initializing the underlying transport. @@ -71,9 +59,8 @@ public class TSerializer { } /** - * Serialize the Thrift object into a byte array. The process is simple, - * just clear the byte array output, write the object into it, and grab the - * raw bytes. + * Serialize the Thrift object into a byte array. The process is simple, just clear the byte array + * output, write the object into it, and grab the raw bytes. * * @param base The object to serialize * @return Serialized object in byte[] format @@ -86,8 +73,7 @@ public class TSerializer { } /** - * Serialize the Thrift object into a Java string, using the default JVM - * charset encoding. + * Serialize the Thrift object into a Java string, using the default JVM charset encoding. * * @param base The object to serialize * @return Serialized object as a String diff --git a/lib/java/src/main/java/org/apache/thrift/TServiceClient.java b/lib/java/src/main/java/org/apache/thrift/TServiceClient.java index 00a36ee7f..6c3759658 100644 --- a/lib/java/src/main/java/org/apache/thrift/TServiceClient.java +++ b/lib/java/src/main/java/org/apache/thrift/TServiceClient.java @@ -24,8 +24,8 @@ import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; /** - * A TServiceClient is used to communicate with a TService implementation - * across protocols and transports. + * A TServiceClient is used to communicate with a TService implementation across protocols and + * transports. */ public abstract class TServiceClient { public TServiceClient(TProtocol prot) { @@ -44,6 +44,7 @@ public abstract class TServiceClient { /** * Get the TProtocol being used as the input (read) protocol. + * * @return the TProtocol being used as the input (read) protocol. */ public TProtocol getInputProtocol() { @@ -52,28 +53,29 @@ public abstract class TServiceClient { /** * Get the TProtocol being used as the output (write) protocol. + * * @return the TProtocol being used as the output (write) protocol. */ public TProtocol getOutputProtocol() { return this.oprot_; } - protected void sendBase(String methodName, TBase<?,?> args) throws TException { + protected void sendBase(String methodName, TBase<?, ?> args) throws TException { sendBase(methodName, args, TMessageType.CALL); } - protected void sendBaseOneway(String methodName, TBase<?,?> args) throws TException { + protected void sendBaseOneway(String methodName, TBase<?, ?> args) throws TException { sendBase(methodName, args, TMessageType.ONEWAY); } - private void sendBase(String methodName, TBase<?,?> args, byte type) throws TException { + private void sendBase(String methodName, TBase<?, ?> args, byte type) throws TException { oprot_.writeMessageBegin(new TMessage(methodName, type, ++seqid_)); args.write(oprot_); oprot_.writeMessageEnd(); oprot_.getTransport().flush(); } - protected void receiveBase(TBase<?,?> result, String methodName) throws TException { + protected void receiveBase(TBase<?, ?> result, String methodName) throws TException { TMessage msg = iprot_.readMessageBegin(); if (msg.type == TMessageType.EXCEPTION) { TApplicationException x = new TApplicationException(); @@ -82,8 +84,11 @@ public abstract class TServiceClient { throw x; } if (msg.seqid != seqid_) { - throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID, - String.format("%s failed: out of sequence response: expected %d but got %d", methodName, seqid_, msg.seqid)); + throw new TApplicationException( + TApplicationException.BAD_SEQUENCE_ID, + String.format( + "%s failed: out of sequence response: expected %d but got %d", + methodName, seqid_, msg.seqid)); } result.read(iprot_); iprot_.readMessageEnd(); diff --git a/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java b/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java index 7f08ba674..16363329a 100644 --- a/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java @@ -22,21 +22,24 @@ package org.apache.thrift; import org.apache.thrift.protocol.TProtocol; /** - * A TServiceClientFactory provides a general way to get a TServiceClient - * connected to a remote TService via a protocol. + * A TServiceClientFactory provides a general way to get a TServiceClient connected to a remote + * TService via a protocol. + * * @param <T> the type of TServiceClient to get. */ public interface TServiceClientFactory<T extends TServiceClient> { /** * Get a brand-new T using <i>prot</i> as both the input and output protocol. + * * @param prot The protocol to use for getting T. * @return A brand-new T using <i>prot</i> as both the input and output protocol. */ public T getClient(TProtocol prot); /** - * Get a brand new T using the specified input and output protocols. The - * input and output protocols may be the same instance. + * Get a brand new T using the specified input and output protocols. The input and output + * protocols may be the same instance. + * * @param iprot The input protocol to use for getting T. * @param oprot The output protocol to use for getting T. * @return a brand new T using the specified input and output protocols diff --git a/lib/java/src/main/java/org/apache/thrift/TUnion.java b/lib/java/src/main/java/org/apache/thrift/TUnion.java index 0ad6881a9..65c92dc56 100644 --- a/lib/java/src/main/java/org/apache/thrift/TUnion.java +++ b/lib/java/src/main/java/org/apache/thrift/TUnion.java @@ -1,19 +1,20 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; @@ -24,7 +25,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.thrift.protocol.TField; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolException; @@ -34,7 +34,8 @@ import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; -public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> implements TBase<T, F> { +public abstract class TUnion<T extends TUnion<T, F>, F extends TFieldIdEnum> + implements TBase<T, F> { protected Object value_; protected F setField_; @@ -44,7 +45,9 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl value_ = null; } - private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); + private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = + new HashMap<Class<? extends IScheme>, SchemeFactory>(); + static { schemes.put(StandardScheme.class, new TUnionStandardSchemeFactory()); schemes.put(TupleScheme.class, new TUnionTupleSchemeFactory()); @@ -64,15 +67,15 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl private static Object deepCopyObject(Object o) { if (o instanceof TBase) { - return ((TBase)o).deepCopy(); + return ((TBase) o).deepCopy(); } else if (o instanceof ByteBuffer) { - return TBaseHelper.copyBinary((ByteBuffer)o); + return TBaseHelper.copyBinary((ByteBuffer) o); } else if (o instanceof List) { - return deepCopyList((List)o); + return deepCopyList((List) o); } else if (o instanceof Set) { - return deepCopySet((Set)o); + return deepCopySet((Set) o); } else if (o instanceof Map) { - return deepCopyMap((Map)o); + return deepCopyMap((Map) o); } else { return o; } @@ -112,14 +115,18 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl public Object getFieldValue(F fieldId) { if (fieldId != setField_) { - throw new IllegalArgumentException("Cannot get the value of field " + fieldId + " because union's set field is " + setField_); + throw new IllegalArgumentException( + "Cannot get the value of field " + + fieldId + + " because union's set field is " + + setField_); } return getFieldValue(); } public Object getFieldValue(int fieldId) { - return getFieldValue(enumForId((short)fieldId)); + return getFieldValue(enumForId((short) fieldId)); } public boolean isSet() { @@ -131,7 +138,7 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl } public boolean isSet(int fieldId) { - return isSet(enumForId((short)fieldId)); + return isSet(enumForId((short) fieldId)); } public void read(TProtocol iprot) throws TException { @@ -145,7 +152,7 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl } public void setFieldValue(int fieldId, Object value) { - setFieldValue(enumForId((short)fieldId), value); + setFieldValue(enumForId((short) fieldId), value); } public void write(TProtocol oprot) throws TException { @@ -153,8 +160,8 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl } /** - * Implementation should be generated so that we can efficiently type check - * various values. + * Implementation should be generated so that we can efficiently type check various values. + * * @param setField the field to assign value to. * @param value the value to be assigned to setField. * @throws ClassCastException if the type of value is incompatible with the type of setField. @@ -162,18 +169,21 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl protected abstract void checkType(F setField, Object value) throws ClassCastException; /** - * Implementation should be generated to read the right stuff from the wire - * based on the field header. + * Implementation should be generated to read the right stuff from the wire based on the field + * header. * * @param iprot input protocol from which to read a value. * @param field the field whose value is to be read from iprot. * @return read Object based on the field header, as specified by the argument. * @throws TException on error during read. */ - protected abstract Object standardSchemeReadValue(TProtocol iprot, TField field) throws TException; + protected abstract Object standardSchemeReadValue(TProtocol iprot, TField field) + throws TException; + protected abstract void standardSchemeWriteValue(TProtocol oprot) throws TException; protected abstract Object tupleSchemeReadValue(TProtocol iprot, short fieldID) throws TException; + protected abstract void tupleSchemeWriteValue(TProtocol oprot) throws TException; protected abstract TStruct getStructDesc(); @@ -193,8 +203,8 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl Object v = getFieldValue(); sb.append(getFieldDesc(getSetField()).name); sb.append(":"); - if(v instanceof ByteBuffer) { - TBaseHelper.toString((ByteBuffer)v, sb); + if (v instanceof ByteBuffer) { + TBaseHelper.toString((ByteBuffer) v, sb); } else { sb.append(v.toString()); } diff --git a/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java b/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java index a34b01ebb..55d4608ed 100644 --- a/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java +++ b/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java @@ -19,15 +19,12 @@ package org.apache.thrift.annotation; -import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** - * Annotation indicating a field, method return, or method parameter may be {@code null}. - * We package our own annotation to avoid a mandatory third-party dependency. + * Annotation indicating a field, method return, or method parameter may be {@code null}. We package + * our own annotation to avoid a mandatory third-party dependency. */ @Retention(RetentionPolicy.CLASS) -public @interface Nullable { - -} +public @interface Nullable {} diff --git a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java index 4ebde0741..3939bc227 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java +++ b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java @@ -19,33 +19,29 @@ package org.apache.thrift.async; /** - * A handler interface asynchronous clients can implement to receive future - * notice of the results of an asynchronous method call. + * A handler interface asynchronous clients can implement to receive future notice of the results of + * an asynchronous method call. * * @param <T> The return type of the asynchronously invoked method. */ public interface AsyncMethodCallback<T> { /** - * This method will be called when the remote side has completed invoking - * your method call and the result is fully read. For {@code oneway} method - * calls, this method will be called as soon as we have completed writing out - * the request. + * This method will be called when the remote side has completed invoking your method call and the + * result is fully read. For {@code oneway} method calls, this method will be called as soon as we + * have completed writing out the request. * - * @param response The return value of the asynchronously invoked method; - * {@code null} for void methods which includes - * {@code oneway} methods. + * @param response The return value of the asynchronously invoked method; {@code null} for void + * methods which includes {@code oneway} methods. */ void onComplete(T response); /** - * This method will be called when there is either an unexpected client-side - * exception like an IOException or else when the remote method raises an - * exception, either declared in the IDL or due to an unexpected server-side - * error. + * This method will be called when there is either an unexpected client-side exception like an + * IOException or else when the remote method raises an exception, either declared in the IDL or + * due to an unexpected server-side error. * - * @param exception The exception encountered processing the the asynchronous - * method call, may be a local exception or an unmarshalled - * remote exception. + * @param exception The exception encountered processing the the asynchronous method call, may be + * a local exception or an unmarshalled remote exception. */ void onError(Exception exception); } diff --git a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java index 0bee3a7cf..202af7bff 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java +++ b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java @@ -3,33 +3,33 @@ package org.apache.thrift.async; import java.util.concurrent.CompletableFuture; /** - * A simple adapter that bridges {@link AsyncMethodCallback} with {@link CompletableFuture}-returning style clients. - * Compiler generated code will invoke this adapter to implement {@code FutureClient}s. + * A simple adapter that bridges {@link AsyncMethodCallback} with {@link + * CompletableFuture}-returning style clients. Compiler generated code will invoke this adapter to + * implement {@code FutureClient}s. * * @param <T> return type (can be {@link Void}). */ public final class AsyncMethodFutureAdapter<T> implements AsyncMethodCallback<T> { - private AsyncMethodFutureAdapter() { - } + private AsyncMethodFutureAdapter() {} - public static <T> AsyncMethodFutureAdapter<T> create() { - return new AsyncMethodFutureAdapter<>(); - } + public static <T> AsyncMethodFutureAdapter<T> create() { + return new AsyncMethodFutureAdapter<>(); + } - private final CompletableFuture<T> future = new CompletableFuture<>(); + private final CompletableFuture<T> future = new CompletableFuture<>(); - public CompletableFuture<T> getFuture() { - return future; - } + public CompletableFuture<T> getFuture() { + return future; + } - @Override - public void onComplete(T response) { - future.complete(response); - } + @Override + public void onComplete(T response) { + future.complete(response); + } - @Override - public void onError(Exception exception) { - future.completeExceptionally(exception); - } + @Override + public void onError(Exception exception) { + future.completeExceptionally(exception); + } } diff --git a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java index 8ba135642..06d6f6382 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java +++ b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java @@ -29,11 +29,18 @@ public abstract class TAsyncClient { private Exception ___error; private long ___timeout; - public TAsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager manager, TNonblockingTransport transport) { + public TAsyncClient( + TProtocolFactory protocolFactory, + TAsyncClientManager manager, + TNonblockingTransport transport) { this(protocolFactory, manager, transport, 0); } - public TAsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager manager, TNonblockingTransport transport, long timeout) { + public TAsyncClient( + TProtocolFactory protocolFactory, + TAsyncClientManager manager, + TNonblockingTransport transport, + long timeout) { this.___protocolFactory = protocolFactory; this.___manager = manager; this.___transport = transport; @@ -58,6 +65,7 @@ public abstract class TAsyncClient { /** * Is the client in an error state? + * * @return If client in an error state? */ public boolean hasError() { @@ -66,7 +74,9 @@ public abstract class TAsyncClient { /** * Get the client's error - returns null if no error - * @return Get the client's error. <p> returns null if no error + * + * @return Get the client's error. + * <p>returns null if no error */ public Exception getError() { return ___error; @@ -75,7 +85,8 @@ public abstract class TAsyncClient { protected void checkReady() { // Ensure we are not currently executing a method if (___currentMethod != null) { - throw new IllegalStateException("Client is currently executing another method: " + ___currentMethod.getClass().getName()); + throw new IllegalStateException( + "Client is currently executing another method: " + ___currentMethod.getClass().getName()); } // Ensure we're not in an error state @@ -84,9 +95,7 @@ public abstract class TAsyncClient { } } - /** - * Called by delegate method when finished - */ + /** Called by delegate method when finished */ protected void onComplete() { ___currentMethod = null; } diff --git a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java index c07ccd540..ba6a5fd2e 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java +++ b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java @@ -29,19 +29,17 @@ import java.util.Iterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeoutException; - import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Contains selector thread which transitions method call objects - */ +/** Contains selector thread which transitions method call objects */ public class TAsyncClientManager { private static final Logger LOGGER = LoggerFactory.getLogger(TAsyncClientManager.class.getName()); private final SelectThread selectThread; - private final ConcurrentLinkedQueue<TAsyncMethodCall> pendingCalls = new ConcurrentLinkedQueue<TAsyncMethodCall>(); + private final ConcurrentLinkedQueue<TAsyncMethodCall> pendingCalls = + new ConcurrentLinkedQueue<TAsyncMethodCall>(); public TAsyncClientManager() throws IOException { this.selectThread = new SelectThread(); @@ -68,7 +66,8 @@ public class TAsyncClientManager { private class SelectThread extends Thread { private final Selector selector; private volatile boolean running; - private final TreeSet<TAsyncMethodCall> timeoutWatchSet = new TreeSet<TAsyncMethodCall>(new TAsyncMethodCallTimeoutComparator()); + private final TreeSet<TAsyncMethodCall> timeoutWatchSet = + new TreeSet<TAsyncMethodCall>(new TAsyncMethodCallTimeoutComparator()); public SelectThread() throws IOException { this.selector = SelectorProvider.provider().openSelector(); @@ -96,7 +95,8 @@ public class TAsyncClientManager { // No timeouts, so select indefinitely selector.select(); } else { - // We have a timeout pending, so calculate the time until then and select appropriately + // We have a timeout pending, so calculate the time until then and select + // appropriately long nextTimeout = timeoutWatchSet.first().getTimeoutTimestamp(); long selectTime = nextTimeout - System.currentTimeMillis(); if (selectTime > 0) { @@ -139,7 +139,7 @@ public class TAsyncClientManager { // just skip continue; } - TAsyncMethodCall methodCall = (TAsyncMethodCall)key.attachment(); + TAsyncMethodCall methodCall = (TAsyncMethodCall) key.attachment(); methodCall.transition(key); // If done or error occurred, remove from timeout watch set @@ -160,7 +160,13 @@ public class TAsyncClientManager { TAsyncMethodCall methodCall = iterator.next(); if (currentTime >= methodCall.getTimeoutTimestamp()) { iterator.remove(); - methodCall.onError(new TimeoutException("Operation " + methodCall.getClass() + " timed out after " + (currentTime - methodCall.getStartTime()) + " ms.")); + methodCall.onError( + new TimeoutException( + "Operation " + + methodCall.getClass() + + " timed out after " + + (currentTime - methodCall.getStartTime()) + + " ms.")); } else { break; } @@ -189,12 +195,13 @@ public class TAsyncClientManager { } /** Comparator used in TreeSet */ - private static class TAsyncMethodCallTimeoutComparator implements Comparator<TAsyncMethodCall>, Serializable { + private static class TAsyncMethodCallTimeoutComparator + implements Comparator<TAsyncMethodCall>, Serializable { public int compare(TAsyncMethodCall left, TAsyncMethodCall right) { if (left.getTimeoutTimestamp() == right.getTimeoutTimestamp()) { - return (int)(left.getSequenceId() - right.getSequenceId()); + return (int) (left.getSequenceId() - right.getSequenceId()); } else { - return (int)(left.getTimeoutTimestamp() - right.getTimeoutTimestamp()); + return (int) (left.getTimeoutTimestamp() - right.getTimeoutTimestamp()); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java b/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java index a119f23e0..df586b4ec 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java +++ b/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java @@ -23,22 +23,22 @@ import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.concurrent.atomic.AtomicLong; - import org.apache.thrift.TException; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TMemoryBuffer; import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransportException; +import org.apache.thrift.transport.layered.TFramedTransport; /** * Encapsulates an async method call. - * <p> - * Need to generate: + * + * <p>Need to generate: + * * <ul> - * <li>protected abstract void write_args(TProtocol protocol)</li> - * <li>protected abstract T getResult() throws <Exception_1>, <Exception_2>, ...</li> + * <li>protected abstract void write_args(TProtocol protocol) + * <li>protected abstract T getResult() throws <Exception_1>, <Exception_2>, ... * </ul> * * @param <T> The return type of the encapsulated method call. @@ -58,9 +58,7 @@ public abstract class TAsyncMethodCall<T> { ERROR; } - /** - * Next step in the call, initialized by start() - */ + /** Next step in the call, initialized by start() */ private State state = null; protected final TNonblockingTransport transport; @@ -77,7 +75,12 @@ public abstract class TAsyncMethodCall<T> { private long startTime = System.currentTimeMillis(); - protected TAsyncMethodCall(TAsyncClient client, TProtocolFactory protocolFactory, TNonblockingTransport transport, AsyncMethodCallback<T> callback, boolean isOneway) { + protected TAsyncMethodCall( + TAsyncClient client, + TProtocolFactory protocolFactory, + TNonblockingTransport transport, + AsyncMethodCallback<T> callback, + boolean isOneway) { this.transport = transport; this.callback = callback; this.protocolFactory = protocolFactory; @@ -121,6 +124,7 @@ public abstract class TAsyncMethodCall<T> { /** * Initialize buffers. + * * @throws TException if buffer initialization fails */ protected void prepareMethodCall() throws TException { @@ -137,6 +141,7 @@ public abstract class TAsyncMethodCall<T> { /** * Register with selector and start first state, which could be either connecting or writing. + * * @throws IOException if register or starting fails */ void start(Selector sel) throws IOException { @@ -168,9 +173,10 @@ public abstract class TAsyncMethodCall<T> { } /** - * Transition to next state, doing whatever work is required. Since this - * method is only called by the selector thread, we can make changes to our - * select interests without worrying about concurrency. + * Transition to next state, doing whatever work is required. Since this method is only called by + * the selector thread, we can make changes to our select interests without worrying about + * concurrency. + * * @param key */ void transition(SelectionKey key) { @@ -201,8 +207,10 @@ public abstract class TAsyncMethodCall<T> { doReadingResponseBody(key); break; default: // RESPONSE_READ, ERROR, or bug - throw new IllegalStateException("Method call in state " + state - + " but selector called transition method. Seems like a bug..."); + throw new IllegalStateException( + "Method call in state " + + state + + " but selector called transition method. Seems like a bug..."); } } catch (Exception e) { key.cancel(); @@ -260,7 +268,7 @@ public abstract class TAsyncMethodCall<T> { cleanUpAndFireCallback(key); } else { state = State.READING_RESPONSE_SIZE; - sizeBuffer.rewind(); // Prepare to read incoming frame size + sizeBuffer.rewind(); // Prepare to read incoming frame size key.interestOps(SelectionKey.OP_READ); } } @@ -268,7 +276,8 @@ public abstract class TAsyncMethodCall<T> { private void doWritingRequestSize() throws TTransportException { if (transport.write(sizeBuffer) < 0) { - throw new TTransportException(TTransportException.END_OF_FILE, "Write call frame size failed"); + throw new TTransportException( + TTransportException.END_OF_FILE, "Write call frame size failed"); } if (sizeBuffer.remaining() == 0) { state = State.WRITING_REQUEST_BODY; @@ -277,7 +286,8 @@ public abstract class TAsyncMethodCall<T> { private void doConnecting(SelectionKey key) throws IOException { if (!key.isConnectable() || !transport.finishConnect()) { - throw new IOException("not connectable or finishConnect returned false after we got an OP_CONNECT"); + throw new IOException( + "not connectable or finishConnect returned false after we got an OP_CONNECT"); } registerForFirstWrite(key); } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java index be49cb949..b6fc11326 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java @@ -23,9 +23,9 @@ import org.apache.thrift.TEnum; public class EnumMetaData extends FieldValueMetaData { public final Class<? extends TEnum> enumClass; - - public EnumMetaData(byte type, Class<? extends TEnum> sClass){ + + public EnumMetaData(byte type, Class<? extends TEnum> sClass) { super(type); this.enumClass = sClass; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java index 5691f83e6..b78919385 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java @@ -19,42 +19,41 @@ package org.apache.thrift.meta_data; -import java.util.AbstractMap; -import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.apache.thrift.TBase; import org.apache.thrift.TFieldIdEnum; /** - * This class is used to store meta data about thrift fields. Every field in a - * a struct should have a corresponding instance of this class describing it. + * This class is used to store meta data about thrift fields. Every field in a a struct should have + * a corresponding instance of this class describing it. * - * The meta data is registered by ALL Thrift struct classes via a static {...} - * initializer block in the generated Thrift code. + * <p>The meta data is registered by ALL Thrift struct classes via a static {...} initializer block + * in the generated Thrift code. * - * Since different threads could be initializing different Thrift classes, calls - * to the public static methods of this class could be racy. + * <p>Since different threads could be initializing different Thrift classes, calls to the public + * static methods of this class could be racy. * - * All methods of this class should be made thread safe. + * <p>All methods of this class should be made thread safe. */ public class FieldMetaData implements java.io.Serializable { public final String fieldName; public final byte requirementType; public final FieldValueMetaData valueMetaData; private final Map<String, String> fieldAnnotations; - private static final Map<Class<? extends TBase>, Map<? extends TFieldIdEnum, FieldMetaData>> structMap = new ConcurrentHashMap<>(); + private static final Map<Class<? extends TBase>, Map<? extends TFieldIdEnum, FieldMetaData>> + structMap = new ConcurrentHashMap<>(); - public FieldMetaData(String name, byte req, FieldValueMetaData vMetaData){ + public FieldMetaData(String name, byte req, FieldValueMetaData vMetaData) { this(name, req, vMetaData, Collections.emptyMap()); } - public FieldMetaData(String fieldName, byte requirementType, FieldValueMetaData valueMetaData, Map<String, String> fieldAnnotations) { + public FieldMetaData( + String fieldName, + byte requirementType, + FieldValueMetaData valueMetaData, + Map<String, String> fieldAnnotations) { this.fieldName = fieldName; this.requirementType = requirementType; this.valueMetaData = valueMetaData; @@ -62,26 +61,26 @@ public class FieldMetaData implements java.io.Serializable { } /** - * @return an unmodifiable view of the annotations for this field, empty if no annotations present or code gen param - * is not turned on + * @return an unmodifiable view of the annotations for this field, empty if no annotations present + * or code gen param is not turned on */ public Map<String, String> getFieldAnnotations() { return Collections.unmodifiableMap(fieldAnnotations); } - public static void addStructMetaDataMap(Class<? extends TBase> sClass, Map<? extends TFieldIdEnum, FieldMetaData> map){ + public static void addStructMetaDataMap( + Class<? extends TBase> sClass, Map<? extends TFieldIdEnum, FieldMetaData> map) { structMap.put(sClass, map); } /** - * Returns a map with metadata (i.e. instances of FieldMetaData) that - * describe the fields of the given class. + * Returns a map with metadata (i.e. instances of FieldMetaData) that describe the fields of the + * given class. * - * @param sClass The TBase class for which the metadata map is requested. It is not - * guaranteed that sClass will have been statically initialized before - * this method is called. A racy call to - * {@link FieldMetaData#addStructMetaDataMap(Class, Map)} from a different - * thread during static initialization of the Thrift class is possible. + * @param sClass The TBase class for which the metadata map is requested. It is not guaranteed + * that sClass will have been statically initialized before this method is called. A racy call + * to {@link FieldMetaData#addStructMetaDataMap(Class, Map)} from a different thread during + * static initialization of the Thrift class is possible. */ public static Map<? extends TFieldIdEnum, FieldMetaData> getStructMetaDataMap( Class<? extends TBase> sClass) { @@ -89,13 +88,21 @@ public class FieldMetaData implements java.io.Serializable { // Similarly, do not trigger sClass.newInstance() while holding a lock on structMap, // it will lead to the same deadlock. // See: https://issues.apache.org/jira/browse/THRIFT-5430 for details. - if (!structMap.containsKey(sClass)){ // Load class if it hasn't been loaded - try{ + if (!structMap.containsKey(sClass)) { // Load class if it hasn't been loaded + try { sClass.newInstance(); - } catch (InstantiationException e){ - throw new RuntimeException("InstantiationException for TBase class: " + sClass.getName() + ", message: " + e.getMessage()); - } catch (IllegalAccessException e){ - throw new RuntimeException("IllegalAccessException for TBase class: " + sClass.getName() + ", message: " + e.getMessage()); + } catch (InstantiationException e) { + throw new RuntimeException( + "InstantiationException for TBase class: " + + sClass.getName() + + ", message: " + + e.getMessage()); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "IllegalAccessException for TBase class: " + + sClass.getName() + + ", message: " + + e.getMessage()); } } return structMap.get(sClass); diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java index 2180b089b..d022e11bb 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java @@ -22,11 +22,10 @@ package org.apache.thrift.meta_data; import org.apache.thrift.protocol.TType; /** - * FieldValueMetaData and collection of subclasses to store metadata about - * the value(s) of a field + * FieldValueMetaData and collection of subclasses to store metadata about the value(s) of a field */ public class FieldValueMetaData implements java.io.Serializable { - public final byte type; + public final byte type; private final boolean isTypedefType; private final String typedefName; @@ -59,7 +58,7 @@ public class FieldValueMetaData implements java.io.Serializable { } public boolean isStruct() { - return type == TType.STRUCT; + return type == TType.STRUCT; } public boolean isContainer() { diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java index 8e7073bf5..e87e97a73 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java @@ -21,9 +21,9 @@ package org.apache.thrift.meta_data; public class ListMetaData extends FieldValueMetaData { public final FieldValueMetaData elemMetaData; - - public ListMetaData(byte type, FieldValueMetaData eMetaData){ + + public ListMetaData(byte type, FieldValueMetaData eMetaData) { super(type); this.elemMetaData = eMetaData; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java index e7c408c78..692a372ec 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java @@ -22,10 +22,10 @@ package org.apache.thrift.meta_data; public class MapMetaData extends FieldValueMetaData { public final FieldValueMetaData keyMetaData; public final FieldValueMetaData valueMetaData; - - public MapMetaData(byte type, FieldValueMetaData kMetaData, FieldValueMetaData vMetaData){ + + public MapMetaData(byte type, FieldValueMetaData kMetaData, FieldValueMetaData vMetaData) { super(type); this.keyMetaData = kMetaData; this.valueMetaData = vMetaData; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java index cf4b96aab..3f2b1e20d 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java @@ -21,9 +21,9 @@ package org.apache.thrift.meta_data; public class SetMetaData extends FieldValueMetaData { public final FieldValueMetaData elemMetaData; - - public SetMetaData(byte type, FieldValueMetaData eMetaData){ + + public SetMetaData(byte type, FieldValueMetaData eMetaData) { super(type); this.elemMetaData = eMetaData; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java index b37d21dab..98d734179 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java @@ -23,9 +23,9 @@ import org.apache.thrift.TBase; public class StructMetaData extends FieldValueMetaData { public final Class<? extends TBase> structClass; - - public StructMetaData(byte type, Class<? extends TBase> sClass){ + + public StructMetaData(byte type, Class<? extends TBase> sClass) { super(type); this.structClass = sClass; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java b/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java index 22423f10c..a56d20286 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java @@ -19,22 +19,19 @@ package org.apache.thrift.partial; -import org.apache.thrift.partial.Validate; - -import org.apache.thrift.TEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import org.apache.thrift.TEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Provides a memoized way to lookup an enum by its value. * - * This class is used internally by {@code TDeserializer}. - * It is not intended to be used separately on its own. + * <p>This class is used internally by {@code TDeserializer}. It is not intended to be used + * separately on its own. */ public class EnumCache { private static Logger LOG = LoggerFactory.getLogger(EnumCache.class); @@ -46,8 +43,7 @@ public class EnumCache { } /** - * Gets an instance of the enum type {@code enumClass} - * corresponding to the given {@code value}. + * Gets an instance of the enum type {@code enumClass} corresponding to the given {@code value}. * * @param enumClass class of the enum to be returned. * @param value value returned by {@code getValue()}. diff --git a/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java b/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java index f636c80d9..e635dc643 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java @@ -19,26 +19,23 @@ package org.apache.thrift.partial; -import org.apache.thrift.TBase; -import org.apache.thrift.protocol.TType; - -import java.lang.StringBuilder; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.thrift.TBase; +import org.apache.thrift.protocol.TType; /** - * Enables comparison of two TBase instances such that the comparison - * is limited to the subset of fields defined by the supplied metadata. + * Enables comparison of two TBase instances such that the comparison is limited to the subset of + * fields defined by the supplied metadata. * - * This comparer is useful when comparing two instances where: - * -- one is generated by full deserialization. - * -- the other is generated by partial deserialization. + * <p>This comparer is useful when comparing two instances where: -- one is generated by full + * deserialization. -- the other is generated by partial deserialization. * - * The typical use case is to establish correctness of partial deserialization. + * <p>The typical use case is to establish correctness of partial deserialization. */ public class PartialThriftComparer<T extends TBase> { @@ -61,12 +58,12 @@ public class PartialThriftComparer<T extends TBase> { } /** - * Compares thrift objects {@code t1} and {@code t2} and - * returns true if they are equal false otherwise. The comparison is limited - * to the scope defined by {@code metadata}. - * <p> - * If the objects are not equal then it optionally records their differences - * if {@code sb} is supplied. + * Compares thrift objects {@code t1} and {@code t2} and returns true if they are equal false + * otherwise. The comparison is limited to the scope defined by {@code metadata}. + * + * <p>If the objects are not equal then it optionally records their differences if {@code sb} is + * supplied. + * * <p> * * @param t1 the first object. @@ -79,10 +76,7 @@ public class PartialThriftComparer<T extends TBase> { } private boolean areEqual( - ThriftMetadata.ThriftObject data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftObject data, Object o1, Object o2, StringBuilder sb) { byte fieldType = data.data.valueMetaData.type; switch (fieldType) { @@ -116,10 +110,7 @@ public class PartialThriftComparer<T extends TBase> { } private boolean areEqual( - ThriftMetadata.ThriftStruct data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftStruct data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; @@ -151,10 +142,7 @@ public class PartialThriftComparer<T extends TBase> { } private boolean areEqual( - ThriftMetadata.ThriftPrimitive data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftPrimitive data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { @@ -173,11 +161,7 @@ public class PartialThriftComparer<T extends TBase> { return false; } - private boolean areEqual( - ThriftMetadata.ThriftEnum data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftEnum data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { @@ -192,11 +176,7 @@ public class PartialThriftComparer<T extends TBase> { return false; } - private boolean areEqual( - ThriftMetadata.ThriftList data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftList data, Object o1, Object o2, StringBuilder sb) { List<Object> l1 = (List<Object>) o1; List<Object> l2 = (List<Object>) o2; @@ -221,11 +201,7 @@ public class PartialThriftComparer<T extends TBase> { return true; } - private boolean areEqual( - ThriftMetadata.ThriftSet data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftSet data, Object o1, Object o2, StringBuilder sb) { Set<Object> s1 = (Set<Object>) o1; Set<Object> s2 = (Set<Object>) o2; @@ -249,11 +225,7 @@ public class PartialThriftComparer<T extends TBase> { return true; } - private boolean areEqual( - ThriftMetadata.ThriftMap data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftMap data, Object o1, Object o2, StringBuilder sb) { Map<Object, Object> m1 = (Map<Object, Object>) o1; Map<Object, Object> m2 = (Map<Object, Object>) o2; @@ -303,10 +275,7 @@ public class PartialThriftComparer<T extends TBase> { } private void appendResult( - ThriftMetadata.ThriftObject data, - StringBuilder sb, - String format, - Object... args) { + ThriftMetadata.ThriftObject data, StringBuilder sb, String format, Object... args) { if (sb != null) { String msg = String.format(format, args); sb.append(data.fieldId.getFieldName()); @@ -330,16 +299,12 @@ public class PartialThriftComparer<T extends TBase> { appendResult(data, sb, "%s (%s) != %s (%s)", o1name, o1s, o2name, o2s); } else { appendResult( - data, sb, "%s != %s\n%s =\n%s\n%s =\n%s\n", - o1name, o2name, o1name, o1s, o2name, o2s); + data, sb, "%s != %s\n%s =\n%s\n%s =\n%s\n", o1name, o2name, o1name, o1s, o2name, o2s); } } private ComparisonResult checkNullEquality( - ThriftMetadata.ThriftObject data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftObject data, Object o1, Object o2, StringBuilder sb) { if ((o1 == null) && (o2 == null)) { return ComparisonResult.EQUAL; } @@ -364,8 +329,7 @@ public class PartialThriftComparer<T extends TBase> { if (c1.size() != c2.size()) { appendResult( - data, sb, "%s1.size(%d) != %s2.size(%d)", - typeName, c1.size(), typeName, c2.size()); + data, sb, "%s1.size(%d) != %s2.size(%d)", typeName, c1.size(), typeName, c2.size()); return false; } diff --git a/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java b/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java index d77302e48..5119259f9 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java @@ -22,8 +22,8 @@ package org.apache.thrift.partial; /** * Holds the type and id members of a {@link org.apache.thrift.protocol.TField} into a single int. * - * This encoding scheme obviates the need to instantiate TField - * during the partial deserialization process. + * <p>This encoding scheme obviates the need to instantiate TField during the partial + * deserialization process. */ public class TFieldData { public static int encode(byte type) { diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java index 1b5a08c80..a0fbda6a6 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java @@ -19,8 +19,6 @@ package org.apache.thrift.partial; -import org.apache.thrift.partial.Validate; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -28,21 +26,19 @@ import java.util.List; /** * Holds name of a thrift field and of its sub-fields recursively. - * <p> - * This class is meant to be used in conjunction with {@code TDeserializer}. + * + * <p>This class is meant to be used in conjunction with {@code TDeserializer}. */ public class ThriftField { - /** - * Name of this field as it appears in a thrift file. Case sensitive. - */ + /** Name of this field as it appears in a thrift file. Case sensitive. */ public final String name; /** * List of sub-fields of this field. * - * This list should have only those sub-fields that need to be deserialized - * by the {@code TDeserializer}. + * <p>This list should have only those sub-fields that need to be deserialized by the {@code + * TDeserializer}. */ public final List<ThriftField> fields; @@ -60,9 +56,7 @@ public class ThriftField { this.fields = Collections.unmodifiableList(fields); } - /** - * Constructs a {@link ThriftField} that does not have any sub-fields. - */ + /** Constructs a {@link ThriftField} that does not have any sub-fields. */ ThriftField(String name) { this(name, Collections.emptyList()); } @@ -146,15 +140,12 @@ public class ThriftField { /** * Generates and returns n-ary tree of fields and their sub-fields. - * <p> - * @param fieldNames collection of fully qualified field names. * - * for example, - * In case of PinJoin thrift struct, the following are valid field names - * -- signature - * -- pins.user.userId - * -- textSignal.termSignal.termDataMap + * <p> * + * @param fieldNames collection of fully qualified field names. + * <p>for example, In case of PinJoin thrift struct, the following are valid field names -- + * signature -- pins.user.userId -- textSignal.termSignal.termDataMap * @return n-ary tree of fields and their sub-fields. */ public static List<ThriftField> fromNames(Collection<String> fieldNames) { diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java index 33982d1d2..edb106c15 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java @@ -19,18 +19,17 @@ package org.apache.thrift.partial; +import java.nio.ByteBuffer; import org.apache.thrift.TEnum; import org.apache.thrift.TFieldIdEnum; -import java.nio.ByteBuffer; - /** - * Provides an abstraction to process deserialized field values and place them - * into the collection that holds them. This abstraction allows different types - * of collections to be output from partial deserialization. + * Provides an abstraction to process deserialized field values and place them into the collection + * that holds them. This abstraction allows different types of collections to be output from partial + * deserialization. * - * In case of the usual Thrift deserialization, the collection that holds field - * values is simply an instance of TBase. + * <p>In case of the usual Thrift deserialization, the collection that holds field values is simply + * an instance of TBase. */ public interface ThriftFieldValueProcessor<V> { @@ -39,15 +38,15 @@ public interface ThriftFieldValueProcessor<V> { V prepareStruct(Object instance); - void setBool(V valueCollection, TFieldIdEnum fieldId, boolean value); + void setBool(V valueCollection, TFieldIdEnum fieldId, boolean value); - void setByte(V valueCollection, TFieldIdEnum fieldId, byte value); + void setByte(V valueCollection, TFieldIdEnum fieldId, byte value); - void setInt16(V valueCollection, TFieldIdEnum fieldId, short value); + void setInt16(V valueCollection, TFieldIdEnum fieldId, short value); - void setInt32(V valueCollection, TFieldIdEnum fieldId, int value); + void setInt32(V valueCollection, TFieldIdEnum fieldId, int value); - void setInt64(V valueCollection, TFieldIdEnum fieldId, long value); + void setInt64(V valueCollection, TFieldIdEnum fieldId, long value); void setDouble(V valueCollection, TFieldIdEnum fieldId, double value); diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java index 46a37f2d9..69f76cff6 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java @@ -19,6 +19,14 @@ package org.apache.thrift.partial; +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.thrift.TBase; import org.apache.thrift.TFieldIdEnum; @@ -31,20 +39,10 @@ import org.apache.thrift.meta_data.SetMetaData; import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.protocol.TType; -import java.io.Serializable; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** - * Container for Thrift metadata classes such as {@link ThriftPrimitive}, - * {@link ThriftList}, etc. - * <p> - * This class is mainly used by {@code TDeserializer}. + * Container for Thrift metadata classes such as {@link ThriftPrimitive}, {@link ThriftList}, etc. + * + * <p>This class is mainly used by {@code TDeserializer}. */ public class ThriftMetadata { @@ -84,9 +82,8 @@ public class ThriftMetadata { /** * Base class of field types that can be partially deserialized. * - * Holds metadata necessary for partial deserialization. - * The metadata is internally computed and used; therefore it is not visible to - * the users of {@code TDeserializer}. + * <p>Holds metadata necessary for partial deserialization. The metadata is internally computed + * and used; therefore it is not visible to the users of {@code TDeserializer}. */ public abstract static class ThriftObject implements Serializable { public final ThriftObject parent; @@ -111,23 +108,17 @@ public class ThriftMetadata { */ protected abstract void toPrettyString(StringBuilder sb, int level); - /** - * Gets a space string whose length is proportional to the given indent level. - */ + /** Gets a space string whose length is proportional to the given indent level. */ protected String getIndent(int level) { return StringUtils.repeat(" ", level * 4); } - /** - * Helper method to append a formatted string to the given {@code StringBuilder}. - */ + /** Helper method to append a formatted string to the given {@code StringBuilder}. */ protected void append(StringBuilder sb, String format, Object... args) { sb.append(String.format(format, args)); } - /** - * Gets the name of this field. - */ + /** Gets the name of this field. */ protected String getName() { return this.fieldId.getFieldName(); } @@ -145,10 +136,7 @@ public class ThriftMetadata { private static class Factory { static ThriftObject createNew( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { byte fieldType = data.valueMetaData.type; switch (fieldType) { @@ -183,9 +171,7 @@ public class ThriftMetadata { } } - /** - * Metadata about primitive types. - */ + /** Metadata about primitive types. */ public static class ThriftPrimitive extends ThriftObject { ThriftPrimitive(ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data) { super(parent, fieldId, data); @@ -248,15 +234,10 @@ public class ThriftMetadata { } } - /** - * Metadata of container like objects: list, set, map - */ + /** Metadata of container like objects: list, set, map */ public abstract static class ThriftContainer extends ThriftObject { - public ThriftContainer( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data) { + public ThriftContainer(ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data) { super(parent, fieldId, data); } @@ -267,20 +248,18 @@ public class ThriftMetadata { public final ThriftObject elementData; ThriftList( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); - this.elementData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.LIST_ELEMENT, - new FieldMetaData( - getSubElementName(fieldId), - TFieldRequirementType.REQUIRED, - ((ListMetaData) data.valueMetaData).elemMetaData), - fields); + this.elementData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.LIST_ELEMENT, + new FieldMetaData( + getSubElementName(fieldId), + TFieldRequirementType.REQUIRED, + ((ListMetaData) data.valueMetaData).elemMetaData), + fields); } @Override @@ -300,20 +279,18 @@ public class ThriftMetadata { public final ThriftObject elementData; ThriftSet( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); - this.elementData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.SET_ELEMENT, - new FieldMetaData( - getSubElementName(fieldId), - TFieldRequirementType.REQUIRED, - ((SetMetaData) data.valueMetaData).elemMetaData), - fields); + this.elementData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.SET_ELEMENT, + new FieldMetaData( + getSubElementName(fieldId), + TFieldRequirementType.REQUIRED, + ((SetMetaData) data.valueMetaData).elemMetaData), + fields); } @Override @@ -334,29 +311,28 @@ public class ThriftMetadata { public final ThriftObject valueData; ThriftMap( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); - this.keyData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.MAP_KEY, - new FieldMetaData( - getSubElementName(fieldId, "key"), - TFieldRequirementType.REQUIRED, - ((MapMetaData) data.valueMetaData).keyMetaData), - Collections.emptyList()); - - this.valueData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.MAP_VALUE, - new FieldMetaData( - getSubElementName(fieldId, "value"), - TFieldRequirementType.REQUIRED, - ((MapMetaData) data.valueMetaData).valueMetaData), - fields); + this.keyData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.MAP_KEY, + new FieldMetaData( + getSubElementName(fieldId, "key"), + TFieldRequirementType.REQUIRED, + ((MapMetaData) data.valueMetaData).keyMetaData), + Collections.emptyList()); + + this.valueData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.MAP_VALUE, + new FieldMetaData( + getSubElementName(fieldId, "value"), + TFieldRequirementType.REQUIRED, + ((MapMetaData) data.valueMetaData).valueMetaData), + fields); } @Override @@ -378,14 +354,11 @@ public class ThriftMetadata { } /** - * Base class for metadata of ThriftStruct and ThriftUnion. - * Holds functionality that is common to both. + * Base class for metadata of ThriftStruct and ThriftUnion. Holds functionality that is common to + * both. */ public abstract static class ThriftStructBase<U extends TBase> extends ThriftObject { - public ThriftStructBase( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data) { + public ThriftStructBase(ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data) { super(parent, fieldId, data); } @@ -419,10 +392,7 @@ public class ThriftMetadata { } } - /** - * Metadata of a Thrift union. - * Currently not adequately supported. - */ + /** Metadata of a Thrift union. Currently not adequately supported. */ public static class ThriftUnion<U extends TBase> extends ThriftStructBase { public ThriftUnion( ThriftObject parent, @@ -442,9 +412,7 @@ public class ThriftMetadata { } } - /** - * Metadata of a Thrift struct. - */ + /** Metadata of a Thrift struct. */ public static class ThriftStruct<U extends TBase> extends ThriftStructBase { public final Map<Integer, ThriftObject> fields; @@ -474,14 +442,12 @@ public class ThriftMetadata { } public static <T extends TBase> ThriftStruct fromFieldNames( - Class<T> clasz, - Collection<String> fieldNames) { + Class<T> clasz, Collection<String> fieldNames) { return fromFields(clasz, ThriftField.fromNames(fieldNames)); } public static <T extends TBase> ThriftStruct fromFields( - Class<T> clasz, - Iterable<ThriftField> fields) { + Class<T> clasz, Iterable<ThriftField> fields) { Validate.checkNotNull(clasz, "clasz"); Validate.checkNotNull(fields, "fields"); @@ -521,9 +487,7 @@ public class ThriftMetadata { } private static <U extends TBase> Map<Integer, ThriftObject> getFields( - ThriftStruct parent, - Class<U> clasz, - Iterable<ThriftField> fieldsData) { + ThriftStruct parent, Class<U> clasz, Iterable<ThriftField> fieldsData) { Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData = FieldMetaData.getStructMetaDataMap(clasz); @@ -535,7 +499,8 @@ public class ThriftMetadata { TFieldIdEnum fieldId = entry.getKey(); FieldMetaData fieldMetaData = entry.getValue(); ThriftObject field = - ThriftObject.Factory.createNew(parent, fieldId, fieldMetaData, Collections.emptyList()); + ThriftObject.Factory.createNew( + parent, fieldId, fieldMetaData, Collections.emptyList()); fields.put((int) fieldId.getThriftFieldId(), field); } } else { @@ -553,8 +518,7 @@ public class ThriftMetadata { } private static FieldMetaData findFieldMetaData( - Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, - String fieldName) { + Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, String fieldName) { for (FieldMetaData fieldData : fieldsMetaData.values()) { if (fieldData.fieldName.equals(fieldName)) { @@ -566,8 +530,7 @@ public class ThriftMetadata { } private static TFieldIdEnum findFieldId( - Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, - String fieldName) { + Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, String fieldName) { for (TFieldIdEnum fieldId : fieldsMetaData.keySet()) { if (fieldId.getFieldName().equals(fieldName)) { diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java index 95789144d..249e6a256 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java @@ -19,20 +19,19 @@ package org.apache.thrift.partial; -import org.apache.thrift.TBase; -import org.apache.thrift.TEnum; -import org.apache.thrift.TFieldIdEnum; - import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.apache.thrift.TBase; +import org.apache.thrift.TEnum; +import org.apache.thrift.TFieldIdEnum; /** * Provides a way to create and initialize an instance of TBase during partial deserialization. * - * This class is supposed to be used as a helper class for {@code PartialThriftDeserializer}. + * <p>This class is supposed to be used as a helper class for {@code PartialThriftDeserializer}. */ public class ThriftStructProcessor implements ThriftFieldValueProcessor<TBase> { @@ -109,27 +108,27 @@ public class ThriftStructProcessor implements ThriftFieldValueProcessor<TBase> { } @Override - public void setBool(TBase valueCollection, TFieldIdEnum fieldId, boolean value) { + public void setBool(TBase valueCollection, TFieldIdEnum fieldId, boolean value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setByte(TBase valueCollection, TFieldIdEnum fieldId, byte value) { + public void setByte(TBase valueCollection, TFieldIdEnum fieldId, byte value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setInt16(TBase valueCollection, TFieldIdEnum fieldId, short value) { + public void setInt16(TBase valueCollection, TFieldIdEnum fieldId, short value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setInt32(TBase valueCollection, TFieldIdEnum fieldId, int value) { + public void setInt32(TBase valueCollection, TFieldIdEnum fieldId, int value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setInt64(TBase valueCollection, TFieldIdEnum fieldId, long value) { + public void setInt64(TBase valueCollection, TFieldIdEnum fieldId, long value) { valueCollection.setFieldValue(fieldId, value); } diff --git a/lib/java/src/main/java/org/apache/thrift/partial/Validate.java b/lib/java/src/main/java/org/apache/thrift/partial/Validate.java index ef0466a5e..f4bbd9a5a 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/Validate.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/Validate.java @@ -26,30 +26,24 @@ import java.util.Collection; /** * A superset of Validate class in Apache commons lang3. * - * It provides consistent message strings for frequently encountered checks. - * That simplifies callers because they have to supply only the name of the argument - * that failed a check instead of having to supply the entire message. + * <p>It provides consistent message strings for frequently encountered checks. That simplifies + * callers because they have to supply only the name of the argument that failed a check instead of + * having to supply the entire message. */ public final class Validate { private Validate() {} - /** - * Validates that the given reference argument is not null. - */ + /** Validates that the given reference argument is not null. */ public static void checkNotNull(Object obj, String argName) { checkArgument(obj != null, "'%s' must not be null.", argName); } - /** - * Validates that the given integer argument is not zero or negative. - */ + /** Validates that the given integer argument is not zero or negative. */ public static void checkPositiveInteger(long value, String argName) { checkArgument(value > 0, "'%s' must be a positive integer.", argName); } - /** - * Validates that the given integer argument is not negative. - */ + /** Validates that the given integer argument is not negative. */ public static void checkNotNegative(long value, String argName) { checkArgument(value >= 0, "'%s' must not be negative.", argName); } @@ -61,83 +55,60 @@ public final class Validate { checkArgument(isPresent, "'%s' is required.", argName); } - /** - * Validates that the expression (that checks a field is valid) is true. - */ + /** Validates that the expression (that checks a field is valid) is true. */ public static void checkValid(boolean isValid, String argName) { checkArgument(isValid, "'%s' is invalid.", argName); } - /** - * Validates that the expression (that checks a field is valid) is true. - */ + /** Validates that the expression (that checks a field is valid) is true. */ public static void checkValid(boolean isValid, String argName, String validValues) { checkArgument(isValid, "'%s' is invalid. Valid values are: %s.", argName, validValues); } - /** - * Validates that the given string is not null and has non-zero length. - */ + /** Validates that the given string is not null and has non-zero length. */ public static void checkNotNullAndNotEmpty(String arg, String argName) { Validate.checkNotNull(arg, argName); - Validate.checkArgument( - arg.length() > 0, - "'%s' must not be empty.", - argName); + Validate.checkArgument(arg.length() > 0, "'%s' must not be empty.", argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static <T> void checkNotNullAndNotEmpty(T[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(byte[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(short[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(int[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(long[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given buffer is not null and has non-zero capacity. - */ + /** Validates that the given buffer is not null and has non-zero capacity. */ public static <T> void checkNotNullAndNotEmpty(Iterable<T> iter, String argName) { Validate.checkNotNull(iter, argName); int minNumElements = iter.iterator().hasNext() ? 1 : 0; checkNotEmpty(minNumElements, argName); } - /** - * Validates that the given set is not null and has an exact number of items. - */ + /** Validates that the given set is not null and has an exact number of items. */ public static <T> void checkNotNullAndNumberOfElements( Collection<T> collection, int numElements, String argName) { Validate.checkNotNull(collection, argName); @@ -146,18 +117,12 @@ public final class Validate { "Number of elements in '%s' must be exactly %s, %s given.", argName, numElements, - collection.size() - ); + collection.size()); } - /** - * Validates that the given two values are equal. - */ + /** Validates that the given two values are equal. */ public static void checkValuesEqual( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 == value2, "'%s' (%s) must equal '%s' (%s).", @@ -167,14 +132,9 @@ public final class Validate { value2); } - /** - * Validates that the first value is an integer multiple of the second value. - */ + /** Validates that the first value is an integer multiple of the second value. */ public static void checkIntegerMultiple( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( (value1 % value2) == 0, "'%s' (%s) must be an integer multiple of '%s' (%s).", @@ -184,14 +144,8 @@ public final class Validate { value2); } - /** - * Validates that the first value is greater than the second value. - */ - public static void checkGreater( - long value1, - String value1Name, - long value2, - String value2Name) { + /** Validates that the first value is greater than the second value. */ + public static void checkGreater(long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 > value2, "'%s' (%s) must be greater than '%s' (%s).", @@ -201,14 +155,9 @@ public final class Validate { value2); } - /** - * Validates that the first value is greater than or equal to the second value. - */ + /** Validates that the first value is greater than or equal to the second value. */ public static void checkGreaterOrEqual( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 >= value2, "'%s' (%s) must be greater than or equal to '%s' (%s).", @@ -218,14 +167,9 @@ public final class Validate { value2); } - /** - * Validates that the first value is less than or equal to the second value. - */ + /** Validates that the first value is less than or equal to the second value. */ public static void checkLessOrEqual( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 <= value2, "'%s' (%s) must be less than or equal to '%s' (%s).", @@ -235,14 +179,9 @@ public final class Validate { value2); } - /** - * Validates that the given value is within the given range of values. - */ + /** Validates that the given value is within the given range of values. */ public static void checkWithinRange( - long value, - String valueName, - long minValueInclusive, - long maxValueInclusive) { + long value, String valueName, long minValueInclusive, long maxValueInclusive) { checkArgument( (value >= minValueInclusive) && (value <= maxValueInclusive), "'%s' (%s) must be within the range [%s, %s].", @@ -252,14 +191,9 @@ public final class Validate { maxValueInclusive); } - /** - * Validates that the given value is within the given range of values. - */ + /** Validates that the given value is within the given range of values. */ public static void checkWithinRange( - double value, - String valueName, - double minValueInclusive, - double maxValueInclusive) { + double value, String valueName, double minValueInclusive, double maxValueInclusive) { checkArgument( (value >= minValueInclusive) && (value <= maxValueInclusive), "'%s' (%s) must be within the range [%s, %s].", @@ -277,10 +211,7 @@ public final class Validate { public static void checkPathExistsAsDir(Path path, String argName) { checkPathExists(path, argName); checkArgument( - Files.isDirectory(path), - "Path %s (%s) must point to a directory.", - argName, - path); + Files.isDirectory(path), "Path %s (%s) must point to a directory.", argName, path); } public static void checkPathExistsAsFile(Path path, String argName) { @@ -297,9 +228,6 @@ public final class Validate { } private static void checkNotEmpty(int arraySize, String argName) { - Validate.checkArgument( - arraySize > 0, - "'%s' must have at least one element.", - argName); + Validate.checkArgument(arraySize > 0, "'%s' must have at least one element.", argName); } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java b/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java index 9e6593074..64afb6064 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java @@ -21,9 +21,9 @@ package org.apache.thrift.protocol; import java.util.Arrays; /** - * ShortStack is a short-specific Stack implementation written for the express - * purpose of very fast operations on TCompactProtocol's field id stack. This - * implementation performs at least 10x faster than java.util.Stack. + * ShortStack is a short-specific Stack implementation written for the express purpose of very fast + * operations on TCompactProtocol's field id stack. This implementation performs at least 10x faster + * than java.util.Stack. */ class ShortStack { diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java b/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java index abfc965b7..a948d13c0 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java @@ -22,105 +22,96 @@ package org.apache.thrift.protocol; /** * Class for encoding and decoding Base64 data. * - * This class is kept at package level because the interface does no input - * validation and is therefore too low-level for generalized reuse. - * - * Note also that the encoding does not pad with equal signs , as discussed in - * section 2.2 of the RFC (http://www.faqs.org/rfcs/rfc3548.html). Furthermore, - * bad data encountered when decoding is neither rejected or ignored but simply - * results in bad decoded data -- this is not in compliance with the RFC but is - * done in the interest of performance. + * <p>This class is kept at package level because the interface does no input validation and is + * therefore too low-level for generalized reuse. * + * <p>Note also that the encoding does not pad with equal signs , as discussed in section 2.2 of the + * RFC (http://www.faqs.org/rfcs/rfc3548.html). Furthermore, bad data encountered when decoding is + * neither rejected or ignored but simply results in bad decoded data -- this is not in compliance + * with the RFC but is done in the interest of performance. */ class TBase64Utils { private static final String ENCODE_TABLE = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** - * Encode len bytes of data in src at offset srcOff, storing the result into - * dst at offset dstOff. len must be 1, 2, or 3. dst must have at least len+1 - * bytes of space at dstOff. src and dst should not be the same object. This - * method does no validation of the input values in the interest of - * performance. + * Encode len bytes of data in src at offset srcOff, storing the result into dst at offset dstOff. + * len must be 1, 2, or 3. dst must have at least len+1 bytes of space at dstOff. src and dst + * should not be the same object. This method does no validation of the input values in the + * interest of performance. * - * @param src the source of bytes to encode - * @param srcOff the offset into the source to read the unencoded bytes - * @param len the number of bytes to encode (must be 1, 2, or 3). - * @param dst the destination for the encoding - * @param dstOff the offset into the destination to place the encoded bytes + * @param src the source of bytes to encode + * @param srcOff the offset into the source to read the unencoded bytes + * @param len the number of bytes to encode (must be 1, 2, or 3). + * @param dst the destination for the encoding + * @param dstOff the offset into the destination to place the encoded bytes */ - static final void encode(byte[] src, int srcOff, int len, byte[] dst, - int dstOff) { - dst[dstOff] = (byte)ENCODE_TABLE.charAt((src[srcOff] >> 2) & 0x3F); + static final void encode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) { + dst[dstOff] = (byte) ENCODE_TABLE.charAt((src[srcOff] >> 2) & 0x3F); if (len == 3) { dst[dstOff + 1] = - (byte)ENCODE_TABLE.charAt( - ((src[srcOff] << 4) & 0x30) | ((src[srcOff+1] >> 4) & 0x0F)); - dst[dstOff + 2] = - (byte)ENCODE_TABLE.charAt( - ((src[srcOff+1] << 2) & 0x3C) | ((src[srcOff+2] >> 6) & 0x03)); - dst[dstOff + 3] = - (byte)ENCODE_TABLE.charAt(src[srcOff+2] & 0x3F); - } - else if (len == 2) { - dst[dstOff+1] = - (byte)ENCODE_TABLE.charAt( - ((src[srcOff] << 4) & 0x30) | ((src[srcOff+1] >> 4) & 0x0F)); + (byte) ENCODE_TABLE.charAt(((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)); dst[dstOff + 2] = - (byte)ENCODE_TABLE.charAt((src[srcOff+1] << 2) & 0x3C); - } - else { // len == 1) { + (byte) + ENCODE_TABLE.charAt( + ((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03)); + dst[dstOff + 3] = (byte) ENCODE_TABLE.charAt(src[srcOff + 2] & 0x3F); + } else if (len == 2) { dst[dstOff + 1] = - (byte)ENCODE_TABLE.charAt((src[srcOff] << 4) & 0x30); + (byte) ENCODE_TABLE.charAt(((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)); + dst[dstOff + 2] = (byte) ENCODE_TABLE.charAt((src[srcOff + 1] << 2) & 0x3C); + } else { // len == 1) { + dst[dstOff + 1] = (byte) ENCODE_TABLE.charAt((src[srcOff] << 4) & 0x30); } } private static final byte[] DECODE_TABLE = { - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, - 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, - 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, - -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, - 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** - * Decode len bytes of data in src at offset srcOff, storing the result into - * dst at offset dstOff. len must be 2, 3, or 4. dst must have at least len-1 - * bytes of space at dstOff. src and dst may be the same object as long as - * dstoff <= srcOff. This method does no validation of the input values in - * the interest of performance. + * Decode len bytes of data in src at offset srcOff, storing the result into dst at offset dstOff. + * len must be 2, 3, or 4. dst must have at least len-1 bytes of space at dstOff. src and dst may + * be the same object as long as dstoff <= srcOff. This method does no validation of the input + * values in the interest of performance. * - * @param src the source of bytes to decode - * @param srcOff the offset into the source to read the encoded bytes - * @param len the number of bytes to decode (must be 2, 3, or 4) - * @param dst the destination for the decoding - * @param dstOff the offset into the destination to place the decoded bytes + * @param src the source of bytes to decode + * @param srcOff the offset into the source to read the encoded bytes + * @param len the number of bytes to decode (must be 2, 3, or 4) + * @param dst the destination for the decoding + * @param dstOff the offset into the destination to place the decoded bytes */ - static final void decode(byte[] src, int srcOff, int len, byte[] dst, - int dstOff) { - dst[dstOff] = (byte) - ((DECODE_TABLE[src[srcOff] & 0x0FF] << 2) | - (DECODE_TABLE[src[srcOff+1] & 0x0FF] >> 4)); + static final void decode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) { + dst[dstOff] = + (byte) + ((DECODE_TABLE[src[srcOff] & 0x0FF] << 2) + | (DECODE_TABLE[src[srcOff + 1] & 0x0FF] >> 4)); if (len > 2) { - dst[dstOff+1] = (byte) - (((DECODE_TABLE[src[srcOff+1] & 0x0FF] << 4) & 0xF0) | - (DECODE_TABLE[src[srcOff+2] & 0x0FF] >> 2)); + dst[dstOff + 1] = + (byte) + (((DECODE_TABLE[src[srcOff + 1] & 0x0FF] << 4) & 0xF0) + | (DECODE_TABLE[src[srcOff + 2] & 0x0FF] >> 2)); if (len > 3) { - dst[dstOff+2] = (byte) - (((DECODE_TABLE[src[srcOff+2] & 0x0FF] << 6) & 0xC0) | - DECODE_TABLE[src[srcOff+3] & 0x0FF]); + dst[dstOff + 2] = + (byte) + (((DECODE_TABLE[src[srcOff + 2] & 0x0FF] << 6) & 0xC0) + | DECODE_TABLE[src[srcOff + 3] & 0x0FF]); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java index e8444fefb..3b93dbf98 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java @@ -21,16 +21,12 @@ package org.apache.thrift.protocol; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; - import org.apache.thrift.TException; import org.apache.thrift.partial.TFieldData; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; -/** - * Binary protocol implementation for thrift. - * - */ +/** Binary protocol implementation for thrift. */ public class TBinaryProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(); private static final long NO_LENGTH_LIMIT = -1; @@ -39,15 +35,14 @@ public class TBinaryProtocol extends TProtocol { protected static final int VERSION_1 = 0x80010000; /** - * The maximum number of bytes to read from the transport for - * variable-length fields (such as strings or binary) or {@link #NO_LENGTH_LIMIT} for - * unlimited. + * The maximum number of bytes to read from the transport for variable-length fields (such as + * strings or binary) or {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long stringLengthLimit_; /** - * The maximum number of elements to read from the network for - * containers (maps, sets, lists), or {@link #NO_LENGTH_LIMIT} for unlimited. + * The maximum number of elements to read from the network for containers (maps, sets, lists), or + * {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long containerLengthLimit_; @@ -56,9 +51,7 @@ public class TBinaryProtocol extends TProtocol { private final byte[] inoutTemp = new byte[8]; - /** - * Factory - */ + /** Factory */ public static class Factory implements TProtocolFactory { protected long stringLengthLimit_; protected long containerLengthLimit_; @@ -77,7 +70,11 @@ public class TBinaryProtocol extends TProtocol { this(false, true, stringLengthLimit, containerLengthLimit); } - public Factory(boolean strictRead, boolean strictWrite, long stringLengthLimit, long containerLengthLimit) { + public Factory( + boolean strictRead, + boolean strictWrite, + long stringLengthLimit, + long containerLengthLimit) { stringLengthLimit_ = stringLengthLimit; containerLengthLimit_ = containerLengthLimit; strictRead_ = strictRead; @@ -85,13 +82,12 @@ public class TBinaryProtocol extends TProtocol { } public TProtocol getProtocol(TTransport trans) { - return new TBinaryProtocol(trans, stringLengthLimit_, containerLengthLimit_, strictRead_, strictWrite_); + return new TBinaryProtocol( + trans, stringLengthLimit_, containerLengthLimit_, strictRead_, strictWrite_); } } - /** - * Constructor - */ + /** Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } @@ -104,7 +100,12 @@ public class TBinaryProtocol extends TProtocol { this(trans, stringLengthLimit, containerLengthLimit, false, true); } - public TBinaryProtocol(TTransport trans, long stringLengthLimit, long containerLengthLimit, boolean strictRead, boolean strictWrite) { + public TBinaryProtocol( + TTransport trans, + long stringLengthLimit, + long containerLengthLimit, + boolean strictRead, + boolean strictWrite) { super(trans); stringLengthLimit_ = stringLengthLimit; containerLengthLimit_ = containerLengthLimit; @@ -179,7 +180,7 @@ public class TBinaryProtocol extends TProtocol { @Override public void writeBool(boolean b) throws TException { - writeByte(b ? (byte)1 : (byte)0); + writeByte(b ? (byte) 1 : (byte) 0); } @Override @@ -190,30 +191,30 @@ public class TBinaryProtocol extends TProtocol { @Override public void writeI16(short i16) throws TException { - inoutTemp[0] = (byte)(0xff & (i16 >> 8)); - inoutTemp[1] = (byte)(0xff & (i16)); + inoutTemp[0] = (byte) (0xff & (i16 >> 8)); + inoutTemp[1] = (byte) (0xff & (i16)); trans_.write(inoutTemp, 0, 2); } @Override public void writeI32(int i32) throws TException { - inoutTemp[0] = (byte)(0xff & (i32 >> 24)); - inoutTemp[1] = (byte)(0xff & (i32 >> 16)); - inoutTemp[2] = (byte)(0xff & (i32 >> 8)); - inoutTemp[3] = (byte)(0xff & (i32)); + inoutTemp[0] = (byte) (0xff & (i32 >> 24)); + inoutTemp[1] = (byte) (0xff & (i32 >> 16)); + inoutTemp[2] = (byte) (0xff & (i32 >> 8)); + inoutTemp[3] = (byte) (0xff & (i32)); trans_.write(inoutTemp, 0, 4); } @Override public void writeI64(long i64) throws TException { - inoutTemp[0] = (byte)(0xff & (i64 >> 56)); - inoutTemp[1] = (byte)(0xff & (i64 >> 48)); - inoutTemp[2] = (byte)(0xff & (i64 >> 40)); - inoutTemp[3] = (byte)(0xff & (i64 >> 32)); - inoutTemp[4] = (byte)(0xff & (i64 >> 24)); - inoutTemp[5] = (byte)(0xff & (i64 >> 16)); - inoutTemp[6] = (byte)(0xff & (i64 >> 8)); - inoutTemp[7] = (byte)(0xff & (i64)); + inoutTemp[0] = (byte) (0xff & (i64 >> 56)); + inoutTemp[1] = (byte) (0xff & (i64 >> 48)); + inoutTemp[2] = (byte) (0xff & (i64 >> 40)); + inoutTemp[3] = (byte) (0xff & (i64 >> 32)); + inoutTemp[4] = (byte) (0xff & (i64 >> 24)); + inoutTemp[5] = (byte) (0xff & (i64 >> 16)); + inoutTemp[6] = (byte) (0xff & (i64 >> 8)); + inoutTemp[7] = (byte) (0xff & (i64)); trans_.write(inoutTemp, 0, 8); } @@ -236,22 +237,21 @@ public class TBinaryProtocol extends TProtocol { trans_.write(bin.array(), bin.position() + bin.arrayOffset(), length); } - /** - * Reading methods. - */ - + /** Reading methods. */ @Override public TMessage readMessageBegin() throws TException { int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { - throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); + throw new TProtocolException( + TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } - return new TMessage(readString(), (byte)(size & 0x000000ff), readI32()); + return new TMessage(readString(), (byte) (size & 0x000000ff), readI32()); } else { if (strictRead_) { - throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); + throw new TProtocolException( + TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } return new TMessage(readStringBody(size), readByte(), readI32()); } @@ -343,10 +343,7 @@ public class TBinaryProtocol extends TProtocol { readAll(inoutTemp, 0, 2); } - return - (short) - (((buf[off] & 0xff) << 8) | - ((buf[off+1] & 0xff))); + return (short) (((buf[off] & 0xff) << 8) | ((buf[off + 1] & 0xff))); } @Override @@ -361,11 +358,10 @@ public class TBinaryProtocol extends TProtocol { } else { readAll(inoutTemp, 0, 4); } - return - ((buf[off] & 0xff) << 24) | - ((buf[off+1] & 0xff) << 16) | - ((buf[off+2] & 0xff) << 8) | - ((buf[off+3] & 0xff)); + return ((buf[off] & 0xff) << 24) + | ((buf[off + 1] & 0xff) << 16) + | ((buf[off + 2] & 0xff) << 8) + | ((buf[off + 3] & 0xff)); } @Override @@ -381,15 +377,14 @@ public class TBinaryProtocol extends TProtocol { readAll(inoutTemp, 0, 8); } - return - ((long)(buf[off] & 0xff) << 56) | - ((long)(buf[off+1] & 0xff) << 48) | - ((long)(buf[off+2] & 0xff) << 40) | - ((long)(buf[off+3] & 0xff) << 32) | - ((long)(buf[off+4] & 0xff) << 24) | - ((long)(buf[off+5] & 0xff) << 16) | - ((long)(buf[off+6] & 0xff) << 8) | - ((long)(buf[off+7] & 0xff)); + return ((long) (buf[off] & 0xff) << 56) + | ((long) (buf[off + 1] & 0xff) << 48) + | ((long) (buf[off + 2] & 0xff) << 40) + | ((long) (buf[off + 3] & 0xff) << 32) + | ((long) (buf[off + 4] & 0xff) << 24) + | ((long) (buf[off + 5] & 0xff) << 16) + | ((long) (buf[off + 6] & 0xff) << 8) + | ((long) (buf[off + 7] & 0xff)); } @Override @@ -402,8 +397,8 @@ public class TBinaryProtocol extends TProtocol { int size = readI32(); if (trans_.getBytesRemainingInBuffer() >= size) { - String s = new String(trans_.getBuffer(), trans_.getBufferPosition(), - size, StandardCharsets.UTF_8); + String s = + new String(trans_.getBuffer(), trans_.getBufferPosition(), size, StandardCharsets.UTF_8); trans_.consumeBuffer(size); return s; } @@ -437,26 +432,24 @@ public class TBinaryProtocol extends TProtocol { private void checkStringReadLength(int length) throws TException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } getTransport().checkReadBytesAvailable(length); if (stringLengthLimit_ != NO_LENGTH_LIMIT && length > stringLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } private void checkContainerReadLength(int length) throws TProtocolException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } if (containerLengthLimit_ != NO_LENGTH_LIMIT && length > containerLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } @@ -464,27 +457,37 @@ public class TBinaryProtocol extends TProtocol { return trans_.readAll(buf, off, len); } - /** - * - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TTransportException { - switch (type) - { - case 0: return 0; // Stop - case 1: return 0; // Void - case 2: return 1; // Bool sizeof(byte) - case 3: return 1; // Byte sizeof(byte) - case 4: return 8; // Double sizeof(double) - case 6: return 2; // I16 sizeof(short) - case 8: return 4; // I32 sizeof(int) - case 10: return 8;// I64 sizeof(long) - case 11: return 4; // string length sizeof(int) - case 12: return 0; // empty struct - case 13: return 4; // element count Map sizeof(int) - case 14: return 4; // element count Set sizeof(int) - case 15: return 4; // element count List sizeof(int) - default: throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool sizeof(byte) + case 3: + return 1; // Byte sizeof(byte) + case 4: + return 8; // Double sizeof(double) + case 6: + return 2; // I16 sizeof(short) + case 8: + return 4; // I32 sizeof(int) + case 10: + return 8; // I64 sizeof(long) + case 11: + return 4; // string length sizeof(int) + case 12: + return 0; // empty struct + case 13: + return 4; // element count Map sizeof(int) + case 14: + return 4; // element count Set sizeof(int) + case 15: + return 4; // element count List sizeof(int) + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); } } // ----------------------------------------------------------------- diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java index 3bace8e90..8adb25e69 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java @@ -17,36 +17,32 @@ * under the License. */ - package org.apache.thrift.protocol; -import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; - import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; /** - * TCompactProtocol2 is the Java implementation of the compact protocol specified - * in THRIFT-110. The fundamental approach to reducing the overhead of - * structures is a) use variable-length integers all over the place and b) make - * use of unused bits wherever possible. Your savings will obviously vary - * based on the specific makeup of your structs, but in general, the more - * fields, nested structures, short strings and collections, and low-value i32 - * and i64 fields you have, the more benefit you'll see. + * TCompactProtocol2 is the Java implementation of the compact protocol specified in THRIFT-110. The + * fundamental approach to reducing the overhead of structures is a) use variable-length integers + * all over the place and b) make use of unused bits wherever possible. Your savings will obviously + * vary based on the specific makeup of your structs, but in general, the more fields, nested + * structures, short strings and collections, and low-value i32 and i64 fields you have, the more + * benefit you'll see. */ public class TCompactProtocol extends TProtocol { - private final static byte[] EMPTY_BYTES = new byte[0]; - private final static ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(EMPTY_BYTES); + private static final byte[] EMPTY_BYTES = new byte[0]; + private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(EMPTY_BYTES); - private final static long NO_LENGTH_LIMIT = -1; + private static final long NO_LENGTH_LIMIT = -1; - private final static TStruct ANONYMOUS_STRUCT = new TStruct(""); - private final static TField TSTOP = new TField("", TType.STOP, (short)0); + private static final TStruct ANONYMOUS_STRUCT = new TStruct(""); + private static final TField TSTOP = new TField("", TType.STOP, (short) 0); - private final static byte[] ttypeToCompactType = new byte[16]; + private static final byte[] ttypeToCompactType = new byte[16]; static { ttypeToCompactType[TType.STOP] = TType.STOP; @@ -63,9 +59,7 @@ public class TCompactProtocol extends TProtocol { ttypeToCompactType[TType.STRUCT] = Types.STRUCT; } - /** - * TProtocolFactory that produces TCompactProtocols. - */ + /** TProtocolFactory that produces TCompactProtocols. */ public static class Factory implements TProtocolFactory { private final long stringLengthLimit_; private final long containerLengthLimit_; @@ -88,67 +82,63 @@ public class TCompactProtocol extends TProtocol { } } - private static final byte PROTOCOL_ID = (byte)0x82; + private static final byte PROTOCOL_ID = (byte) 0x82; private static final byte VERSION = 1; private static final byte VERSION_MASK = 0x1f; // 0001 1111 - private static final byte TYPE_MASK = (byte)0xE0; // 1110 0000 + private static final byte TYPE_MASK = (byte) 0xE0; // 1110 0000 private static final byte TYPE_BITS = 0x07; // 0000 0111 - private static final int TYPE_SHIFT_AMOUNT = 5; + private static final int TYPE_SHIFT_AMOUNT = 5; - /** - * All of the on-wire type codes. - */ + /** All of the on-wire type codes. */ private static class Types { - public static final byte BOOLEAN_TRUE = 0x01; - public static final byte BOOLEAN_FALSE = 0x02; - public static final byte BYTE = 0x03; - public static final byte I16 = 0x04; - public static final byte I32 = 0x05; - public static final byte I64 = 0x06; - public static final byte DOUBLE = 0x07; - public static final byte BINARY = 0x08; - public static final byte LIST = 0x09; - public static final byte SET = 0x0A; - public static final byte MAP = 0x0B; - public static final byte STRUCT = 0x0C; + public static final byte BOOLEAN_TRUE = 0x01; + public static final byte BOOLEAN_FALSE = 0x02; + public static final byte BYTE = 0x03; + public static final byte I16 = 0x04; + public static final byte I32 = 0x05; + public static final byte I64 = 0x06; + public static final byte DOUBLE = 0x07; + public static final byte BINARY = 0x08; + public static final byte LIST = 0x09; + public static final byte SET = 0x0A; + public static final byte MAP = 0x0B; + public static final byte STRUCT = 0x0C; } /** - * Used to keep track of the last field for the current and previous structs, - * so we can do the delta stuff. + * Used to keep track of the last field for the current and previous structs, so we can do the + * delta stuff. */ private final ShortStack lastField_ = new ShortStack(15); private short lastFieldId_ = 0; /** - * If we encounter a boolean field begin, save the TField here so it can - * have the value incorporated. + * If we encounter a boolean field begin, save the TField here so it can have the value + * incorporated. */ private TField booleanField_ = null; /** - * If we read a field header, and it's a boolean field, save the boolean - * value here so that readBool can use it. + * If we read a field header, and it's a boolean field, save the boolean value here so that + * readBool can use it. */ private Boolean boolValue_ = null; /** - * The maximum number of bytes to read from the transport for - * variable-length fields (such as strings or binary) or {@link #NO_LENGTH_LIMIT} for - * unlimited. + * The maximum number of bytes to read from the transport for variable-length fields (such as + * strings or binary) or {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long stringLengthLimit_; /** - * The maximum number of elements to read from the network for - * containers (maps, sets, lists), or {@link #NO_LENGTH_LIMIT} for unlimited. + * The maximum number of elements to read from the network for containers (maps, sets, lists), or + * {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long containerLengthLimit_; /** - * Temporary buffer used for various operations that would otherwise require a - * small allocation. + * Temporary buffer used for various operations that would otherwise require a small allocation. */ private final byte[] temp = new byte[10]; @@ -156,10 +146,8 @@ public class TCompactProtocol extends TProtocol { * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. - * @param stringLengthLimit the maximum number of bytes to read for - * variable-length fields. - * @param containerLengthLimit the maximum number of elements to read - * for containers. + * @param stringLengthLimit the maximum number of bytes to read for variable-length fields. + * @param containerLengthLimit the maximum number of elements to read for containers. */ public TCompactProtocol(TTransport transport, long stringLengthLimit, long containerLengthLimit) { super(transport); @@ -171,8 +159,7 @@ public class TCompactProtocol extends TProtocol { * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. - * @param stringLengthLimit the maximum number of bytes to read for - * variable-length fields. + * @param stringLengthLimit the maximum number of bytes to read for variable-length fields. * @deprecated Use constructor specifying both string limit and container limit instead */ @Deprecated @@ -200,8 +187,8 @@ public class TCompactProtocol extends TProtocol { // /** - * Write a message header to the wire. Compact Protocol messages contain the - * protocol version so we can migrate forwards in the future if need be. + * Write a message header to the wire. Compact Protocol messages contain the protocol version so + * we can migrate forwards in the future if need be. */ @Override public void writeMessageBegin(TMessage message) throws TException { @@ -212,9 +199,9 @@ public class TCompactProtocol extends TProtocol { } /** - * Write a struct begin. This doesn't actually put anything on the wire. We - * use it as an opportunity to put special placeholder markers on the field - * stack so we can get the field id deltas correct. + * Write a struct begin. This doesn't actually put anything on the wire. We use it as an + * opportunity to put special placeholder markers on the field stack so we can get the field id + * deltas correct. */ @Override public void writeStructBegin(TStruct struct) throws TException { @@ -223,33 +210,30 @@ public class TCompactProtocol extends TProtocol { } /** - * Write a struct end. This doesn't actually put anything on the wire. We use - * this as an opportunity to pop the last field from the current struct off - * of the field stack. + * Write a struct end. This doesn't actually put anything on the wire. We use this as an + * opportunity to pop the last field from the current struct off of the field stack. */ public void writeStructEnd() throws TException { lastFieldId_ = lastField_.pop(); } /** - * Write a field header containing the field id and field type. If the - * difference between the current field id and the last one is small (< 15), - * then the field id will be encoded in the 4 MSB as a delta. Otherwise, the - * field id will follow the type header as a zigzag varint. + * Write a field header containing the field id and field type. If the difference between the + * current field id and the last one is small (< 15), then the field id will be encoded in the + * 4 MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. */ public void writeFieldBegin(TField field) throws TException { if (field.type == TType.BOOL) { // we want to possibly include the value, so we'll wait. booleanField_ = field; } else { - writeFieldBeginInternal(field, (byte)-1); + writeFieldBeginInternal(field, (byte) -1); } } /** - * The workhorse of writeFieldBegin. It has the option of doing a - * 'type override' of the type header. This is used specifically in the - * boolean field case. + * The workhorse of writeFieldBegin. It has the option of doing a 'type override' of the type + * header. This is used specifically in the boolean field case. */ private void writeFieldBeginInternal(TField field, byte typeOverride) throws TException { // short lastField = lastField_.pop(); @@ -271,16 +255,14 @@ public class TCompactProtocol extends TProtocol { // lastField_.push(field.id); } - /** - * Write the STOP symbol so we know there are no more fields in this struct. - */ + /** Write the STOP symbol so we know there are no more fields in this struct. */ public void writeFieldStop() throws TException { writeByteDirect(TType.STOP); } /** - * Write a map header. If the map is empty, omit the key and value type - * headers, as we don't need any additional information to skip it. + * Write a map header. If the map is empty, omit the key and value type headers, as we don't need + * any additional information to skip it. */ public void writeMapBegin(TMap map) throws TException { if (map.size == 0) { @@ -291,25 +273,20 @@ public class TCompactProtocol extends TProtocol { } } - /** - * Write a list header. - */ + /** Write a list header. */ public void writeListBegin(TList list) throws TException { writeCollectionBegin(list.elemType, list.size); } - /** - * Write a set header. - */ + /** Write a set header. */ public void writeSetBegin(TSet set) throws TException { writeCollectionBegin(set.elemType, set.size); } /** - * Write a boolean value. Potentially, this could be a boolean field, in - * which case the field header info isn't written yet. If so, decide what the - * right type header is for the value and then write the field header. - * Otherwise, write a single byte. + * Write a boolean value. Potentially, this could be a boolean field, in which case the field + * header info isn't written yet. If so, decide what the right type header is for the value and + * then write the field header. Otherwise, write a single byte. */ public void writeBool(boolean b) throws TException { if (booleanField_ != null) { @@ -322,54 +299,40 @@ public class TCompactProtocol extends TProtocol { } } - /** - * Write a byte. Nothing to see here! - */ + /** Write a byte. Nothing to see here! */ public void writeByte(byte b) throws TException { writeByteDirect(b); } - /** - * Write an I16 as a zigzag varint. - */ + /** Write an I16 as a zigzag varint. */ public void writeI16(short i16) throws TException { writeVarint32(intToZigZag(i16)); } - /** - * Write an i32 as a zigzag varint. - */ + /** Write an i32 as a zigzag varint. */ public void writeI32(int i32) throws TException { writeVarint32(intToZigZag(i32)); } - /** - * Write an i64 as a zigzag varint. - */ + /** Write an i64 as a zigzag varint. */ public void writeI64(long i64) throws TException { writeVarint64(longToZigzag(i64)); } - /** - * Write a double to the wire as 8 bytes. - */ + /** Write a double to the wire as 8 bytes. */ public void writeDouble(double dub) throws TException { fixedLongToBytes(Double.doubleToLongBits(dub), temp, 0); trans_.write(temp, 0, 8); } - /** - * Write a string to the wire with a varint size preceding. - */ + /** Write a string to the wire with a varint size preceding. */ public void writeString(String str) throws TException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); writeVarint32(bytes.length); trans_.write(bytes, 0, bytes.length); } - /** - * Write a byte array, using a varint for the size. - */ + /** Write a byte array, using a varint for the size. */ public void writeBinary(ByteBuffer bin) throws TException { ByteBuffer bb = bin.asReadOnlyBuffer(); writeVarint32(bb.remaining()); @@ -382,9 +345,13 @@ public class TCompactProtocol extends TProtocol { // public void writeMessageEnd() throws TException {} + public void writeMapEnd() throws TException {} + public void writeListEnd() throws TException {} + public void writeSetEnd() throws TException {} + public void writeFieldEnd() throws TException {} // @@ -392,8 +359,8 @@ public class TCompactProtocol extends TProtocol { // /** - * Abstract method for writing the start of lists and sets. List and sets on - * the wire differ only by the type indicator. + * Abstract method for writing the start of lists and sets. List and sets on the wire differ only + * by the type indicator. */ protected void writeCollectionBegin(byte elemType, int size) throws TException { if (size <= 14) { @@ -405,19 +372,19 @@ public class TCompactProtocol extends TProtocol { } /** - * Write an i32 as a varint. Results in 1-5 bytes on the wire. - * TODO: make a permanent buffer like writeVarint64? + * Write an i32 as a varint. Results in 1-5 bytes on the wire. TODO: make a permanent buffer like + * writeVarint64? */ private void writeVarint32(int n) throws TException { int idx = 0; while (true) { if ((n & ~0x7F) == 0) { - temp[idx++] = (byte)n; + temp[idx++] = (byte) n; // writeByteDirect((byte)n); break; // return; } else { - temp[idx++] = (byte)((n & 0x7F) | 0x80); + temp[idx++] = (byte) ((n & 0x7F) | 0x80); // writeByteDirect((byte)((n & 0x7F) | 0x80)); n >>>= 7; } @@ -425,17 +392,15 @@ public class TCompactProtocol extends TProtocol { trans_.write(temp, 0, idx); } - /** - * Write an i64 as a varint. Results in 1-10 bytes on the wire. - */ + /** Write an i64 as a varint. Results in 1-10 bytes on the wire. */ private void writeVarint64(long n) throws TException { int idx = 0; while (true) { if ((n & ~0x7FL) == 0) { - temp[idx++] = (byte)n; + temp[idx++] = (byte) n; break; } else { - temp[idx++] = ((byte)((n & 0x7F) | 0x80)); + temp[idx++] = ((byte) ((n & 0x7F) | 0x80)); n >>>= 7; } } @@ -443,79 +408,75 @@ public class TCompactProtocol extends TProtocol { } /** - * Convert l into a zigzag long. This allows negative numbers to be - * represented compactly as a varint. + * Convert l into a zigzag long. This allows negative numbers to be represented compactly as a + * varint. */ private long longToZigzag(long l) { return (l << 1) ^ (l >> 63); } /** - * Convert n into a zigzag int. This allows negative numbers to be - * represented compactly as a varint. + * Convert n into a zigzag int. This allows negative numbers to be represented compactly as a + * varint. */ private int intToZigZag(int n) { return (n << 1) ^ (n >> 31); } - /** - * Convert a long into little-endian bytes in buf starting at off and going - * until off+7. - */ + /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedLongToBytes(long n, byte[] buf, int off) { - buf[off+0] = (byte)( n & 0xff); - buf[off+1] = (byte)((n >> 8 ) & 0xff); - buf[off+2] = (byte)((n >> 16) & 0xff); - buf[off+3] = (byte)((n >> 24) & 0xff); - buf[off+4] = (byte)((n >> 32) & 0xff); - buf[off+5] = (byte)((n >> 40) & 0xff); - buf[off+6] = (byte)((n >> 48) & 0xff); - buf[off+7] = (byte)((n >> 56) & 0xff); + buf[off + 0] = (byte) (n & 0xff); + buf[off + 1] = (byte) ((n >> 8) & 0xff); + buf[off + 2] = (byte) ((n >> 16) & 0xff); + buf[off + 3] = (byte) ((n >> 24) & 0xff); + buf[off + 4] = (byte) ((n >> 32) & 0xff); + buf[off + 5] = (byte) ((n >> 40) & 0xff); + buf[off + 6] = (byte) ((n >> 48) & 0xff); + buf[off + 7] = (byte) ((n >> 56) & 0xff); } /** - * Writes a byte without any possibility of all that field header nonsense. - * Used internally by other writing methods that know they need to write a byte. + * Writes a byte without any possibility of all that field header nonsense. Used internally by + * other writing methods that know they need to write a byte. */ private void writeByteDirect(byte b) throws TException { temp[0] = b; trans_.write(temp, 0, 1); } - /** - * Writes a byte without any possibility of all that field header nonsense. - */ + /** Writes a byte without any possibility of all that field header nonsense. */ private void writeByteDirect(int n) throws TException { - writeByteDirect((byte)n); + writeByteDirect((byte) n); } - // // Reading methods. // - /** - * Read a message header. - */ + /** Read a message header. */ public TMessage readMessageBegin() throws TException { byte protocolId = readByte(); if (protocolId != PROTOCOL_ID) { - throw new TProtocolException("Expected protocol id " + Integer.toHexString(PROTOCOL_ID) + " but got " + Integer.toHexString(protocolId)); + throw new TProtocolException( + "Expected protocol id " + + Integer.toHexString(PROTOCOL_ID) + + " but got " + + Integer.toHexString(protocolId)); } byte versionAndType = readByte(); - byte version = (byte)(versionAndType & VERSION_MASK); + byte version = (byte) (versionAndType & VERSION_MASK); if (version != VERSION) { throw new TProtocolException("Expected version " + VERSION + " but got " + version); } - byte type = (byte)((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS); + byte type = (byte) ((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS); int seqid = readVarint32(); String messageName = readString(); return new TMessage(messageName, type, seqid); } /** - * Read a struct begin. There's nothing on the wire for this, but it is our - * opportunity to push a new struct begin marker onto the field stack. + * Read a struct begin. There's nothing on the wire for this, but it is our opportunity to push a + * new struct begin marker onto the field stack. */ public TStruct readStructBegin() throws TException { lastField_.push(lastFieldId_); @@ -524,17 +485,15 @@ public class TCompactProtocol extends TProtocol { } /** - * Doesn't actually consume any wire data, just removes the last field for - * this struct from the field stack. + * Doesn't actually consume any wire data, just removes the last field for this struct from the + * field stack. */ public void readStructEnd() throws TException { // consume the last field we read off the wire. lastFieldId_ = lastField_.pop(); } - /** - * Read a field header off the wire. - */ + /** Read a field header off the wire. */ public TField readFieldBegin() throws TException { byte type = readByte(); @@ -546,21 +505,21 @@ public class TCompactProtocol extends TProtocol { short fieldId; // mask off the 4 MSB of the type header. it could contain a field id delta. - short modifier = (short)((type & 0xf0) >> 4); + short modifier = (short) ((type & 0xf0) >> 4); if (modifier == 0) { // not a delta. look ahead for the zigzag varint field id. fieldId = readI16(); } else { // has a delta. add the delta to the last read field id. - fieldId = (short)(lastFieldId_ + modifier); + fieldId = (short) (lastFieldId_ + modifier); } - TField field = new TField("", getTType((byte)(type & 0x0f)), fieldId); + TField field = new TField("", getTType((byte) (type & 0x0f)), fieldId); // if this happens to be a boolean field, the value is encoded in the type if (isBoolType(type)) { // save the boolean value in a special instance variable. - boolValue_ = (byte)(type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; + boolValue_ = (byte) (type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; } // push the new field onto the field stack so we can keep the deltas going. @@ -569,24 +528,26 @@ public class TCompactProtocol extends TProtocol { } /** - * Read a map header off the wire. If the size is zero, skip reading the key - * and value type. This means that 0-length maps will yield TMaps without the - * "correct" types. + * Read a map header off the wire. If the size is zero, skip reading the key and value type. This + * means that 0-length maps will yield TMaps without the "correct" types. */ public TMap readMapBegin() throws TException { int size = readVarint32(); checkContainerReadLength(size); byte keyAndValueType = size == 0 ? 0 : readByte(); - TMap map = new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size); + TMap map = + new TMap( + getTType((byte) (keyAndValueType >> 4)), + getTType((byte) (keyAndValueType & 0xf)), + size); checkReadBytesAvailable(map); return map; } /** - * Read a list header off the wire. If the list size is 0-14, the size will - * be packed into the element type header. If it's a longer list, the 4 MSB - * of the element type header will be 0xF, and a varint will follow with the - * true size. + * Read a list header off the wire. If the list size is 0-14, the size will be packed into the + * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF, + * and a varint will follow with the true size. */ public TList readListBegin() throws TException { byte size_and_type = readByte(); @@ -601,19 +562,17 @@ public class TCompactProtocol extends TProtocol { } /** - * Read a set header off the wire. If the set size is 0-14, the size will - * be packed into the element type header. If it's a longer set, the 4 MSB - * of the element type header will be 0xF, and a varint will follow with the - * true size. + * Read a set header off the wire. If the set size is 0-14, the size will be packed into the + * element type header. If it's a longer set, the 4 MSB of the element type header will be 0xF, + * and a varint will follow with the true size. */ public TSet readSetBegin() throws TException { return new TSet(readListBegin()); } /** - * Read a boolean off the wire. If this is a boolean field, the value should - * already have been read during readFieldBegin, so we'll just consume the - * pre-stored value. Otherwise, read a byte. + * Read a boolean off the wire. If this is a boolean field, the value should already have been + * read during readFieldBegin, so we'll just consume the pre-stored value. Otherwise, read a byte. */ public boolean readBool() throws TException { if (boolValue_ != null) { @@ -624,9 +583,7 @@ public class TCompactProtocol extends TProtocol { return readByte() == Types.BOOLEAN_TRUE; } - /** - * Read a single byte off the wire. Nothing interesting here. - */ + /** Read a single byte off the wire. Nothing interesting here. */ public byte readByte() throws TException { byte b; if (trans_.getBytesRemainingInBuffer() > 0) { @@ -639,38 +596,28 @@ public class TCompactProtocol extends TProtocol { return b; } - /** - * Read an i16 from the wire as a zigzag varint. - */ + /** Read an i16 from the wire as a zigzag varint. */ public short readI16() throws TException { - return (short)zigzagToInt(readVarint32()); + return (short) zigzagToInt(readVarint32()); } - /** - * Read an i32 from the wire as a zigzag varint. - */ + /** Read an i32 from the wire as a zigzag varint. */ public int readI32() throws TException { return zigzagToInt(readVarint32()); } - /** - * Read an i64 from the wire as a zigzag varint. - */ + /** Read an i64 from the wire as a zigzag varint. */ public long readI64() throws TException { return zigzagToLong(readVarint64()); } - /** - * No magic here - just read a double off the wire. - */ + /** No magic here - just read a double off the wire. */ public double readDouble() throws TException { trans_.readAll(temp, 0, 8); return Double.longBitsToDouble(bytesToLong(temp)); } - /** - * Reads a byte[] (via readBinary), and then UTF-8 decodes it. - */ + /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */ public String readString() throws TException { int length = readVarint32(); checkStringReadLength(length); @@ -681,8 +628,9 @@ public class TCompactProtocol extends TProtocol { final String str; if (trans_.getBytesRemainingInBuffer() >= length) { - str = new String(trans_.getBuffer(), trans_.getBufferPosition(), - length, StandardCharsets.UTF_8); + str = + new String( + trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8); trans_.consumeBuffer(length); } else { str = new String(readBinary(length), StandardCharsets.UTF_8); @@ -690,9 +638,7 @@ public class TCompactProtocol extends TProtocol { return str; } - /** - * Read a ByteBuffer from the wire. - */ + /** Read a ByteBuffer from the wire. */ public ByteBuffer readBinary() throws TException { int length = readVarint32(); if (length == 0) { @@ -710,9 +656,7 @@ public class TCompactProtocol extends TProtocol { return ByteBuffer.wrap(buf); } - /** - * Read a byte[] of a known length from the wire. - */ + /** Read a byte[] of a known length from the wire. */ private byte[] readBinary(int length) throws TException { if (length == 0) return EMPTY_BYTES; @@ -723,26 +667,24 @@ public class TCompactProtocol extends TProtocol { private void checkStringReadLength(int length) throws TException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } getTransport().checkReadBytesAvailable(length); if (stringLengthLimit_ != NO_LENGTH_LIMIT && length > stringLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } private void checkContainerReadLength(int length) throws TProtocolException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } if (containerLengthLimit_ != NO_LENGTH_LIMIT && length > containerLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } @@ -752,12 +694,16 @@ public class TCompactProtocol extends TProtocol { // @Override public void readMessageEnd() throws TException {} + @Override public void readFieldEnd() throws TException {} + @Override public void readMapEnd() throws TException {} + @Override public void readListEnd() throws TException {} + @Override public void readSetEnd() throws TException {} @@ -766,8 +712,8 @@ public class TCompactProtocol extends TProtocol { // /** - * Read an i32 from the wire as a varint. The MSB of each byte is set - * if there is another byte to follow. This can read up to 5 bytes. + * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to + * follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { int result = 0; @@ -777,13 +723,13 @@ public class TCompactProtocol extends TProtocol { int pos = trans_.getBufferPosition(); int off = 0; while (true) { - byte b = buf[pos+off]; + byte b = buf[pos + off]; result |= (b & 0x7f) << shift; if ((b & 0x80) != 0x80) break; shift += 7; off++; } - trans_.consumeBuffer(off+1); + trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); @@ -796,8 +742,8 @@ public class TCompactProtocol extends TProtocol { } /** - * Read an i64 from the wire as a proper varint. The MSB of each byte is set - * if there is another byte to follow. This can read up to 10 bytes. + * Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another + * byte to follow. This can read up to 10 bytes. */ private long readVarint64() throws TException { int shift = 0; @@ -807,19 +753,19 @@ public class TCompactProtocol extends TProtocol { int pos = trans_.getBufferPosition(); int off = 0; while (true) { - byte b = buf[pos+off]; + byte b = buf[pos + off]; result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) break; shift += 7; off++; } - trans_.consumeBuffer(off+1); + trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) break; - shift +=7; + shift += 7; } } return result; @@ -829,35 +775,29 @@ public class TCompactProtocol extends TProtocol { // encoding helpers // - /** - * Convert from zigzag int to int. - */ + /** Convert from zigzag int to int. */ private int zigzagToInt(int n) { return (n >>> 1) ^ -(n & 1); } - /** - * Convert from zigzag long to long. - */ + /** Convert from zigzag long to long. */ private long zigzagToLong(long n) { return (n >>> 1) ^ -(n & 1); } /** - * Note that it's important that the mask bytes are long literals, - * otherwise they'll default to ints, and when you shift an int left 56 bits, - * you just get a messed up int. + * Note that it's important that the mask bytes are long literals, otherwise they'll default to + * ints, and when you shift an int left 56 bits, you just get a messed up int. */ private long bytesToLong(byte[] bytes) { - return - ((bytes[7] & 0xffL) << 56) | - ((bytes[6] & 0xffL) << 48) | - ((bytes[5] & 0xffL) << 40) | - ((bytes[4] & 0xffL) << 32) | - ((bytes[3] & 0xffL) << 24) | - ((bytes[2] & 0xffL) << 16) | - ((bytes[1] & 0xffL) << 8) | - ((bytes[0] & 0xffL)); + return ((bytes[7] & 0xffL) << 56) + | ((bytes[6] & 0xffL) << 48) + | ((bytes[5] & 0xffL) << 40) + | ((bytes[4] & 0xffL) << 32) + | ((bytes[3] & 0xffL) << 24) + | ((bytes[2] & 0xffL) << 16) + | ((bytes[1] & 0xffL) << 8) + | ((bytes[0] & 0xffL)); } // @@ -869,12 +809,9 @@ public class TCompactProtocol extends TProtocol { return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } - /** - * Given a TCompactProtocol.Types constant, convert it to its corresponding - * TType value. - */ + /** Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. */ private byte getTType(byte type) throws TProtocolException { - switch ((byte)(type & 0x0f)) { + switch ((byte) (type & 0x0f)) { case TType.STOP: return TType.STOP; case Types.BOOLEAN_FALSE: @@ -901,51 +838,47 @@ public class TCompactProtocol extends TProtocol { case Types.STRUCT: return TType.STRUCT; default: - throw new TProtocolException("don't know what type: " + (byte)(type & 0x0f)); + throw new TProtocolException("don't know what type: " + (byte) (type & 0x0f)); } } - /** - * Given a TType value, find the appropriate TCompactProtocol.Types constant. - */ + /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */ private byte getCompactType(byte ttype) { return ttypeToCompactType[ttype]; } - /** - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TTransportException { - switch (type) { - case 0: - return 0; // Stop - case 1: - return 0; // Void - case 2: - return 1; // Bool sizeof(byte) - case 3: - return 1; // Byte sizeof(byte) - case 4: - return 8; // Double sizeof(double) - case 6: - return 1; // I16 sizeof(byte) - case 8: - return 1; // I32 sizeof(byte) - case 10: - return 1;// I64 sizeof(byte) - case 11: - return 1; // string length sizeof(byte) - case 12: - return 0; // empty struct - case 13: - return 1; // element count Map sizeof(byte) - case 14: - return 1; // element count Set sizeof(byte) - case 15: - return 1; // element count List sizeof(byte) - default: - throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); - } + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool sizeof(byte) + case 3: + return 1; // Byte sizeof(byte) + case 4: + return 8; // Double sizeof(double) + case 6: + return 1; // I16 sizeof(byte) + case 8: + return 1; // I32 sizeof(byte) + case 10: + return 1; // I64 sizeof(byte) + case 11: + return 1; // string length sizeof(byte) + case 12: + return 0; // empty struct + case 13: + return 1; // element count Map sizeof(byte) + case 14: + return 1; // element count Set sizeof(byte) + case 15: + return 1; // element count List sizeof(byte) + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + } } // ----------------------------------------------------------------- // Additional methods to improve performance. diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TField.java b/lib/java/src/main/java/org/apache/thrift/protocol/TField.java index 3872b008f..9fde33ca6 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TField.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TField.java @@ -21,11 +21,12 @@ package org.apache.thrift.protocol; /** * Helper class that encapsulates field metadata. - * <p>Two fields are considered equal if they have the same type and id.</p> + * + * <p>Two fields are considered equal if they have the same type and id. */ public class TField { public TField() { - this("", TType.STOP, (short)0); + this("", TType.STOP, (short) 0); } public TField(String n, byte t, short i) { @@ -35,8 +36,8 @@ public class TField { } public final String name; - public final byte type; - public final short id; + public final byte type; + public final short id; public String toString() { return "<TField name:'" + name + "' type:" + type + " field-id:" + id + ">"; @@ -53,12 +54,9 @@ public class TField { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; TField otherField = (TField) obj; return type == otherField.type && id == otherField.id; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java index 95eb62ced..53d0d715c 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java @@ -24,7 +24,6 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Stack; - import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; @@ -33,17 +32,13 @@ import org.apache.thrift.transport.TTransportException; /** * JSON protocol implementation for thrift. * - * This is a full-featured protocol supporting write and read. - * - * Please see the C++ class header for a detailed description of the - * protocol's wire format. + * <p>This is a full-featured protocol supporting write and read. * + * <p>Please see the C++ class header for a detailed description of the protocol's wire format. */ public class TJSONProtocol extends TProtocol { - /** - * Factory for JSON protocol objects - */ + /** Factory for JSON protocol objects */ public static class Factory implements TProtocolFactory { protected boolean fieldNamesAsString_ = false; @@ -56,7 +51,6 @@ public class TJSONProtocol extends TProtocol { public TProtocol getProtocol(TTransport trans) { return new TJSONProtocol(trans, fieldNamesAsString_); } - } private static final byte[] COMMA = new byte[] {','}; @@ -69,15 +63,15 @@ public class TJSONProtocol extends TProtocol { private static final byte[] BACKSLASH = new byte[] {'\\'}; private static final byte[] ZERO = new byte[] {'0'}; - private static final byte[] ESCSEQ = new byte[] {'\\','u','0','0'}; + private static final byte[] ESCSEQ = new byte[] {'\\', 'u', '0', '0'}; - private static final long VERSION = 1; + private static final long VERSION = 1; private static final byte[] JSON_CHAR_TABLE = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ - 0, 0, 0, 0, 0, 0, 0, 0,'b','t','n', 0,'f','r', 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 - 1, 1,'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, // 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 + 1, 1, '"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 }; private static final String ESCAPE_CHARS = "\"\\/bfnrt"; @@ -86,102 +80,97 @@ public class TJSONProtocol extends TProtocol { '"', '\\', '/', '\b', '\f', '\n', '\r', '\t', }; - private static final int DEF_STRING_SIZE = 16; + private static final int DEF_STRING_SIZE = 16; private static final byte[] NAME_BOOL = new byte[] {'t', 'f'}; - private static final byte[] NAME_BYTE = new byte[] {'i','8'}; - private static final byte[] NAME_I16 = new byte[] {'i','1','6'}; - private static final byte[] NAME_I32 = new byte[] {'i','3','2'}; - private static final byte[] NAME_I64 = new byte[] {'i','6','4'}; - private static final byte[] NAME_DOUBLE = new byte[] {'d','b','l'}; - private static final byte[] NAME_STRUCT = new byte[] {'r','e','c'}; - private static final byte[] NAME_STRING = new byte[] {'s','t','r'}; - private static final byte[] NAME_MAP = new byte[] {'m','a','p'}; - private static final byte[] NAME_LIST = new byte[] {'l','s','t'}; - private static final byte[] NAME_SET = new byte[] {'s','e','t'}; + private static final byte[] NAME_BYTE = new byte[] {'i', '8'}; + private static final byte[] NAME_I16 = new byte[] {'i', '1', '6'}; + private static final byte[] NAME_I32 = new byte[] {'i', '3', '2'}; + private static final byte[] NAME_I64 = new byte[] {'i', '6', '4'}; + private static final byte[] NAME_DOUBLE = new byte[] {'d', 'b', 'l'}; + private static final byte[] NAME_STRUCT = new byte[] {'r', 'e', 'c'}; + private static final byte[] NAME_STRING = new byte[] {'s', 't', 'r'}; + private static final byte[] NAME_MAP = new byte[] {'m', 'a', 'p'}; + private static final byte[] NAME_LIST = new byte[] {'l', 's', 't'}; + private static final byte[] NAME_SET = new byte[] {'s', 'e', 't'}; private static final TStruct ANONYMOUS_STRUCT = new TStruct(); - private static final byte[] getTypeNameForTypeID(byte typeID) - throws TException { + private static final byte[] getTypeNameForTypeID(byte typeID) throws TException { switch (typeID) { - case TType.BOOL: - return NAME_BOOL; - case TType.BYTE: - return NAME_BYTE; - case TType.I16: - return NAME_I16; - case TType.I32: - return NAME_I32; - case TType.I64: - return NAME_I64; - case TType.DOUBLE: - return NAME_DOUBLE; - case TType.STRING: - return NAME_STRING; - case TType.STRUCT: - return NAME_STRUCT; - case TType.MAP: - return NAME_MAP; - case TType.SET: - return NAME_SET; - case TType.LIST: - return NAME_LIST; - default: - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Unrecognized type"); - } - } - - private static final byte getTypeIDForTypeName(byte[] name) - throws TException { + case TType.BOOL: + return NAME_BOOL; + case TType.BYTE: + return NAME_BYTE; + case TType.I16: + return NAME_I16; + case TType.I32: + return NAME_I32; + case TType.I64: + return NAME_I64; + case TType.DOUBLE: + return NAME_DOUBLE; + case TType.STRING: + return NAME_STRING; + case TType.STRUCT: + return NAME_STRUCT; + case TType.MAP: + return NAME_MAP; + case TType.SET: + return NAME_SET; + case TType.LIST: + return NAME_LIST; + default: + throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); + } + } + + private static final byte getTypeIDForTypeName(byte[] name) throws TException { byte result = TType.STOP; if (name.length > 1) { switch (name[0]) { - case 'd': - result = TType.DOUBLE; - break; - case 'i': - switch (name[1]) { - case '8': - result = TType.BYTE; + case 'd': + result = TType.DOUBLE; break; - case '1': - result = TType.I16; + case 'i': + switch (name[1]) { + case '8': + result = TType.BYTE; + break; + case '1': + result = TType.I16; + break; + case '3': + result = TType.I32; + break; + case '6': + result = TType.I64; + break; + } break; - case '3': - result = TType.I32; + case 'l': + result = TType.LIST; break; - case '6': - result = TType.I64; + case 'm': + result = TType.MAP; + break; + case 'r': + result = TType.STRUCT; + break; + case 's': + if (name[1] == 't') { + result = TType.STRING; + } else if (name[1] == 'e') { + result = TType.SET; + } + break; + case 't': + result = TType.BOOL; break; - } - break; - case 'l': - result = TType.LIST; - break; - case 'm': - result = TType.MAP; - break; - case 'r': - result = TType.STRUCT; - break; - case 's': - if (name[1] == 't') { - result = TType.STRING; - } - else if (name[1] == 'e') { - result = TType.SET; - } - break; - case 't': - result = TType.BOOL; - break; } } if (result == TType.STOP) { - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Unrecognized type"); + throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); } return result; } @@ -194,7 +183,9 @@ public class TJSONProtocol extends TProtocol { protected void read() throws TException {} - protected boolean escapeNum() { return false; } + protected boolean escapeNum() { + return false; + } } // Context for JSON lists. Will insert/read commas before each item except @@ -268,8 +259,7 @@ public class TJSONProtocol extends TProtocol { protected byte read() throws TException { if (hasData_) { hasData_ = false; - } - else { + } else { trans_.readAll(data_, 0, 1); } return data_[0]; @@ -316,9 +306,7 @@ public class TJSONProtocol extends TProtocol { } } - /** - * Constructor - */ + /** Constructor */ public TJSONProtocol(TTransport trans) { super(trans); } @@ -344,8 +332,8 @@ public class TJSONProtocol extends TProtocol { protected void readJSONSyntaxChar(byte[] b) throws TException { byte ch = reader_.read(); if (ch != b[0]) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Unexpected character:" + (char)ch); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Unexpected character:" + (char) ch); } } @@ -353,14 +341,11 @@ public class TJSONProtocol extends TProtocol { // corresponding hex value private static final byte hexVal(byte ch) throws TException { if ((ch >= '0') && (ch <= '9')) { - return (byte)((char)ch - '0'); - } - else if ((ch >= 'a') && (ch <= 'f')) { - return (byte)((char)ch - 'a' + 10); - } - else { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected hex character"); + return (byte) ((char) ch - '0'); + } else if ((ch >= 'a') && (ch <= 'f')) { + return (byte) ((char) ch - 'a' + 10); + } else { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character"); } } @@ -368,10 +353,9 @@ public class TJSONProtocol extends TProtocol { private static final byte hexChar(byte val) { val &= 0x0F; if (val < 10) { - return (byte)((char)val + '0'); - } - else { - return (byte)((char)(val - 10) + 'a'); + return (byte) ((char) val + '0'); + } else { + return (byte) ((char) (val - 10) + 'a'); } } @@ -385,23 +369,19 @@ public class TJSONProtocol extends TProtocol { if (b[i] == BACKSLASH[0]) { trans_.write(BACKSLASH); trans_.write(BACKSLASH); - } - else { + } else { trans_.write(b, i, 1); } - } - else { + } else { tmpbuf_[0] = JSON_CHAR_TABLE[b[i]]; if (tmpbuf_[0] == 1) { trans_.write(b, i, 1); - } - else if (tmpbuf_[0] > 1) { + } else if (tmpbuf_[0] > 1) { trans_.write(BACKSLASH); trans_.write(tmpbuf_, 0, 1); - } - else { + } else { trans_.write(ESCSEQ); - tmpbuf_[0] = hexChar((byte)(b[i] >> 4)); + tmpbuf_[0] = hexChar((byte) (b[i] >> 4)); tmpbuf_[1] = hexChar(b[i]); trans_.write(tmpbuf_, 0, 2); } @@ -433,18 +413,18 @@ public class TJSONProtocol extends TProtocol { String str = Double.toString(num); boolean special = false; switch (str.charAt(0)) { - case 'N': // NaN - case 'I': // Infinity - special = true; - break; - case '-': - if (str.charAt(1) == 'I') { // -Infinity + case 'N': // NaN + case 'I': // Infinity special = true; - } - break; - default: - break; - } + break; + case '-': + if (str.charAt(1) == 'I') { // -Infinity + special = true; + } + break; + default: + break; + } boolean escapeNum = special || context_.escapeNum(); if (escapeNum) { @@ -587,7 +567,7 @@ public class TJSONProtocol extends TProtocol { @Override public void writeBool(boolean b) throws TException { - writeJSONInteger(b ? (long)1 : (long)0); + writeJSONInteger(b ? (long) 1 : (long) 0); } @Override @@ -623,17 +603,17 @@ public class TJSONProtocol extends TProtocol { @Override public void writeBinary(ByteBuffer bin) throws TException { - writeJSONBase64(bin.array(), bin.position() + bin.arrayOffset(), bin.limit() - bin.position() - bin.arrayOffset()); + writeJSONBase64( + bin.array(), + bin.position() + bin.arrayOffset(), + bin.limit() - bin.position() - bin.arrayOffset()); } - /** - * Reading methods. - */ + /** Reading methods. */ // Read in a JSON string, unescaping as appropriate.. Skip reading from the // context if skipContext is true. - private TByteArrayOutputStream readJSONString(boolean skipContext) - throws TException { + private TByteArrayOutputStream readJSONString(boolean skipContext) throws TException { TByteArrayOutputStream arr = new TByteArrayOutputStream(DEF_STRING_SIZE); ArrayList<Character> codeunits = new ArrayList<Character>(); if (!skipContext) { @@ -649,46 +629,42 @@ public class TJSONProtocol extends TProtocol { ch = reader_.read(); if (ch == ESCSEQ[1]) { trans_.readAll(tmpbuf_, 0, 4); - short cu = (short)( - ((short)hexVal(tmpbuf_[0]) << 12) + - ((short)hexVal(tmpbuf_[1]) << 8) + - ((short)hexVal(tmpbuf_[2]) << 4) + - (short)hexVal(tmpbuf_[3])); + short cu = + (short) + (((short) hexVal(tmpbuf_[0]) << 12) + + ((short) hexVal(tmpbuf_[1]) << 8) + + ((short) hexVal(tmpbuf_[2]) << 4) + + (short) hexVal(tmpbuf_[3])); try { - if (Character.isHighSurrogate((char)cu)) { + if (Character.isHighSurrogate((char) cu)) { if (codeunits.size() > 0) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected low surrogate char"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Expected low surrogate char"); } - codeunits.add((char)cu); - } - else if (Character.isLowSurrogate((char)cu)) { + codeunits.add((char) cu); + } else if (Character.isLowSurrogate((char) cu)) { if (codeunits.size() == 0) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected high surrogate char"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Expected high surrogate char"); } - codeunits.add((char)cu); + codeunits.add((char) cu); arr.write( - (new String(new int[] { codeunits.get(0), codeunits.get(1) }, - 0, 2)).getBytes(StandardCharsets.UTF_8)); + (new String(new int[] {codeunits.get(0), codeunits.get(1)}, 0, 2)) + .getBytes(StandardCharsets.UTF_8)); codeunits.clear(); - } - else { - arr.write((new String(new int[] { cu }, 0, 1)) - .getBytes(StandardCharsets.UTF_8)); + } else { + arr.write((new String(new int[] {cu}, 0, 1)).getBytes(StandardCharsets.UTF_8)); } continue; } catch (IOException ex) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Invalid unicode sequence"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Invalid unicode sequence"); } - } - else { + } else { int off = ESCAPE_CHARS.indexOf(ch); if (off == -1) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected control char"); + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char"); } ch = ESCAPE_CHAR_VALS[off]; } @@ -701,22 +677,22 @@ public class TJSONProtocol extends TProtocol { // Return true if the given byte could be a valid part of a JSON number. private boolean isJSONNumeric(byte b) { switch (b) { - case '+': - case '-': - case '.': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case 'E': - case 'e': - return true; + case '+': + case '-': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'E': + case 'e': + return true; } return false; } @@ -730,7 +706,7 @@ public class TJSONProtocol extends TProtocol { if (!isJSONNumeric(ch)) { break; } - strbld.append((char)reader_.read()); + strbld.append((char) reader_.read()); } return strbld.toString(); } @@ -747,10 +723,9 @@ public class TJSONProtocol extends TProtocol { } try { return Long.valueOf(str); - } - catch (NumberFormatException ex) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Bad data encounted in numeric data"); + } catch (NumberFormatException ex) { + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } @@ -761,25 +736,22 @@ public class TJSONProtocol extends TProtocol { if (reader_.peek() == QUOTE[0]) { TByteArrayOutputStream arr = readJSONString(true); double dub = Double.valueOf(arr.toString(StandardCharsets.UTF_8)); - if (!context_.escapeNum() && !Double.isNaN(dub) - && !Double.isInfinite(dub)) { + if (!context_.escapeNum() && !Double.isNaN(dub) && !Double.isInfinite(dub)) { // Throw exception -- we should not be in a string in this case - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Numeric data unexpectedly quoted"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted"); } return dub; - } - else { + } else { if (context_.escapeNum()) { // This will throw - we should have had a quote if escapeNum == true readJSONSyntaxChar(QUOTE); } try { return Double.valueOf(readJSONNumericChars()); - } - catch (NumberFormatException ex) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Bad data encounted in numeric data"); + } catch (NumberFormatException ex) { + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } } @@ -811,7 +783,7 @@ public class TJSONProtocol extends TProtocol { size += len - 1; } // Sadly we must copy the byte[] (any way around this?) - byte [] result = new byte[size]; + byte[] result = new byte[size]; System.arraycopy(b, 0, result, 0, size); return result; } @@ -843,8 +815,8 @@ public class TJSONProtocol extends TProtocol { resetContext(); // THRIFT-3743 readJSONArrayStart(); if (readJSONInteger() != VERSION) { - throw new TProtocolException(TProtocolException.BAD_VERSION, - "Message contained bad version."); + throw new TProtocolException( + TProtocolException.BAD_VERSION, "Message contained bad version."); } String name = readJSONString(false).toString(StandardCharsets.UTF_8); byte type = (byte) readJSONInteger(); @@ -875,8 +847,7 @@ public class TJSONProtocol extends TProtocol { short id = 0; if (ch == RBRACE[0]) { type = TType.STOP; - } - else { + } else { id = (short) readJSONInteger(); readJSONObjectStart(); type = getTypeIDForTypeName(readJSONString(false).get()); @@ -894,7 +865,7 @@ public class TJSONProtocol extends TProtocol { readJSONArrayStart(); byte keyType = getTypeIDForTypeName(readJSONString(false).get()); byte valueType = getTypeIDForTypeName(readJSONString(false).get()); - int size = (int)readJSONInteger(); + int size = (int) readJSONInteger(); readJSONObjectStart(); TMap map = new TMap(keyType, valueType, size); @@ -912,7 +883,7 @@ public class TJSONProtocol extends TProtocol { public TList readListBegin() throws TException { readJSONArrayStart(); byte elemType = getTypeIDForTypeName(readJSONString(false).get()); - int size = (int)readJSONInteger(); + int size = (int) readJSONInteger(); TList list = new TList(elemType, size); checkReadBytesAvailable(list); @@ -928,7 +899,7 @@ public class TJSONProtocol extends TProtocol { public TSet readSetBegin() throws TException { readJSONArrayStart(); byte elemType = getTypeIDForTypeName(readJSONString(false).get()); - int size = (int)readJSONInteger(); + int size = (int) readJSONInteger(); TSet set = new TSet(elemType, size); checkReadBytesAvailable(set); @@ -980,28 +951,37 @@ public class TJSONProtocol extends TProtocol { return ByteBuffer.wrap(readJSONBase64()); } - /** - * - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TTransportException { - switch (type) - { - case 0: return 0; // Stop - case 1: return 0; // Void - case 2: return 1; // Bool - case 3: return 1; // Byte - case 4: return 1; // Double - case 6: return 1; // I16 - case 8: return 1; // I32 - case 10: return 1;// I64 - case 11: return 2; // string length - case 12: return 2; // empty struct - case 13: return 2; // element count Map - case 14: return 2; // element count Set - case 15: return 2; // element count List - default: throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool + case 3: + return 1; // Byte + case 4: + return 1; // Double + case 6: + return 1; // I16 + case 8: + return 1; // I32 + case 10: + return 1; // I64 + case 11: + return 2; // string length + case 12: + return 2; // empty struct + case 13: + return 2; // element count Map + case 14: + return 2; // element count Set + case 15: + return 2; // element count List + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); } } - } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TList.java b/lib/java/src/main/java/org/apache/thrift/protocol/TList.java index 0d36e83d9..25368916d 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TList.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TList.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates list metadata. - * - */ +/** Helper class that encapsulates list metadata. */ public final class TList { public TList() { this(TType.STOP, 0); @@ -34,5 +31,5 @@ public final class TList { } public final byte elemType; - public final int size; + public final int size; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java index 20881f7ac..72dace2cd 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates map metadata. - * - */ +/** Helper class that encapsulates map metadata. */ public final class TMap { public TMap() { this(TType.STOP, TType.STOP, 0); @@ -34,7 +31,7 @@ public final class TMap { size = s; } - public final byte keyType; - public final byte valueType; - public final int size; + public final byte keyType; + public final byte valueType; + public final int size; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java index f13b8ca50..a5468d737 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates struct metadata. - * - */ +/** Helper class that encapsulates struct metadata. */ public final class TMessage { public TMessage() { this("", TType.STOP, 0); @@ -55,22 +52,15 @@ public final class TMessage { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; TMessage other = (TMessage) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (seqid != other.seqid) - return false; - if (type != other.type) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + if (seqid != other.seqid) return false; + if (type != other.type) return false; return true; } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java index aa3f93177..a768cb6ae 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java @@ -19,12 +19,9 @@ package org.apache.thrift.protocol; -/** - * Message type constants in the Thrift protocol. - * - */ +/** Message type constants in the Thrift protocol. */ public final class TMessageType { - public static final byte CALL = 1; + public static final byte CALL = 1; public static final byte REPLY = 2; public static final byte EXCEPTION = 3; public static final byte ONEWAY = 4; diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java index 0ea566ba6..09343303e 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java @@ -22,72 +22,67 @@ package org.apache.thrift.protocol; import org.apache.thrift.TException; /** - * <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator - * that allows a Thrift client to communicate with a multiplexing Thrift server, - * by prepending the service name to the function name during function calls. + * <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator that allows a + * Thrift client to communicate with a multiplexing Thrift server, by prepending the service name to + * the function name during function calls. * - * <p>NOTE: THIS IS NOT USED BY SERVERS. On the server, use {@link org.apache.thrift.TMultiplexedProcessor TMultiplexedProcessor} to handle requests - * from a multiplexing client. + * <p>NOTE: THIS IS NOT USED BY SERVERS. On the server, use {@link + * org.apache.thrift.TMultiplexedProcessor TMultiplexedProcessor} to handle requests from a + * multiplexing client. * * <p>This example uses a single socket transport to invoke two services: * - * <pre> - * {@code - * TSocket transport = new TSocket("localhost", 9090); - * transport.open(); + * <pre>{@code + * TSocket transport = new TSocket("localhost", 9090); + * transport.open(); * - * TBinaryProtocol protocol = new TBinaryProtocol(transport); + * TBinaryProtocol protocol = new TBinaryProtocol(transport); * - * TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); - * Calculator.Client service = new Calculator.Client(mp); + * TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); + * Calculator.Client service = new Calculator.Client(mp); * - * TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); - * WeatherReport.Client service2 = new WeatherReport.Client(mp2); + * TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); + * WeatherReport.Client service2 = new WeatherReport.Client(mp2); * - * System.out.println(service.add(2,2)); - * System.out.println(service2.getTemperature()); - * } - * </pre> + * System.out.println(service.add(2,2)); + * System.out.println(service2.getTemperature()); + * }</pre> * * @see org.apache.thrift.protocol.TProtocolDecorator */ public class TMultiplexedProtocol extends TProtocolDecorator { - /** Used to delimit the service name from the function name */ - public static final String SEPARATOR = ":"; + /** Used to delimit the service name from the function name */ + public static final String SEPARATOR = ":"; - private final String SERVICE_NAME; + private final String SERVICE_NAME; - /** - * Wrap the specified protocol, allowing it to be used to communicate with a - * multiplexing server. The <code>serviceName</code> is required as it is - * prepended to the message header so that the multiplexing server can broker - * the function call to the proper service. - * - * @param protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>. - * @param serviceName The service name of the service communicating via this protocol. - */ - public TMultiplexedProtocol(TProtocol protocol, String serviceName) { - super(protocol); - SERVICE_NAME = serviceName; - } + /** + * Wrap the specified protocol, allowing it to be used to communicate with a multiplexing server. + * The <code>serviceName</code> is required as it is prepended to the message header so that the + * multiplexing server can broker the function call to the proper service. + * + * @param protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>. + * @param serviceName The service name of the service communicating via this protocol. + */ + public TMultiplexedProtocol(TProtocol protocol, String serviceName) { + super(protocol); + SERVICE_NAME = serviceName; + } - /** - * Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. - * - * @param tMessage The original message. - * @throws TException Passed through from wrapped <code>TProtocol</code> instance. - */ - @Override - public void writeMessageBegin(TMessage tMessage) throws TException { - if (tMessage.type == TMessageType.CALL || tMessage.type == TMessageType.ONEWAY) { - super.writeMessageBegin(new TMessage( - SERVICE_NAME + SEPARATOR + tMessage.name, - tMessage.type, - tMessage.seqid - )); - } else { - super.writeMessageBegin(tMessage); - } + /** + * Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. + * + * @param tMessage The original message. + * @throws TException Passed through from wrapped <code>TProtocol</code> instance. + */ + @Override + public void writeMessageBegin(TMessage tMessage) throws TException { + if (tMessage.type == TMessageType.CALL || tMessage.type == TMessageType.ONEWAY) { + super.writeMessageBegin( + new TMessage(SERVICE_NAME + SEPARATOR + tMessage.name, tMessage.type, tMessage.seqid)); + } else { + super.writeMessageBegin(tMessage); } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java index 3589b64e3..a55d9f7ed 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java @@ -20,40 +20,28 @@ package org.apache.thrift.protocol; import java.nio.ByteBuffer; - import org.apache.thrift.TException; import org.apache.thrift.partial.TFieldData; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.transport.TTransport; -/** - * Protocol interface definition. - * - */ +/** Protocol interface definition. */ public abstract class TProtocol { - /** - * Prevent direct instantiation - */ + /** Prevent direct instantiation */ @SuppressWarnings("unused") private TProtocol() {} - /** - * Transport - */ + /** Transport */ protected TTransport trans_; - /** - * Constructor - */ + /** Constructor */ protected TProtocol(TTransport trans) { trans_ = trans; } - /** - * Transport accessor - */ + /** Transport accessor */ public TTransport getTransport() { return trans_; } @@ -73,16 +61,15 @@ public abstract class TProtocol { /** * Return - * @param type Returns the minimum amount of bytes needed to store the smallest possible instance of TType. + * + * @param type Returns the minimum amount of bytes needed to store the smallest possible instance + * of TType. * @return * @throws TException */ public abstract int getMinSerializedSize(byte type) throws TException; - /** - * Writing methods. - */ - + /** Writing methods. */ public abstract void writeMessageBegin(TMessage message) throws TException; public abstract void writeMessageEnd() throws TException; @@ -125,10 +112,7 @@ public abstract class TProtocol { public abstract void writeBinary(ByteBuffer buf) throws TException; - /** - * Reading methods. - */ - + /** Reading methods. */ public abstract TMessage readMessageBegin() throws TException; public abstract void readMessageEnd() throws TException; @@ -170,14 +154,12 @@ public abstract class TProtocol { public abstract ByteBuffer readBinary() throws TException; /** - * Reset any internal state back to a blank slate. This method only needs to - * be implemented for stateful protocols. + * Reset any internal state back to a blank slate. This method only needs to be implemented for + * stateful protocols. */ public void reset() {} - /** - * Scheme accessor - */ + /** Scheme accessor */ public Class<? extends IScheme> getScheme() { return StandardScheme.class; } @@ -277,10 +259,9 @@ public abstract class TProtocol { /** * The default implementation of all skip() methods calls the corresponding read() method. - * Protocols that derive from this class are strongly encouraged to provide - * a more efficient alternative. + * Protocols that derive from this class are strongly encouraged to provide a more efficient + * alternative. */ - protected void skipBool() throws TException { this.readBool(); } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java index 9d109622f..3b3205a98 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java @@ -19,205 +19,204 @@ package org.apache.thrift.protocol; -import org.apache.thrift.TException; - import java.nio.ByteBuffer; +import org.apache.thrift.TException; /** - * <code>TProtocolDecorator</code> forwards all requests to an enclosed - * <code>TProtocol</code> instance, providing a way to author concise - * concrete decorator subclasses. While it has no abstract methods, it - * is marked abstract as a reminder that by itself, it does not modify - * the behaviour of the enclosed <code>TProtocol</code>. + * <code>TProtocolDecorator</code> forwards all requests to an enclosed <code>TProtocol</code> + * instance, providing a way to author concise concrete decorator subclasses. While it has no + * abstract methods, it is marked abstract as a reminder that by itself, it does not modify the + * behaviour of the enclosed <code>TProtocol</code>. * - * <p>See p.175 of Design Patterns (by Gamma et al.)</p> + * <p>See p.175 of Design Patterns (by Gamma et al.) * * @see org.apache.thrift.protocol.TMultiplexedProtocol */ public abstract class TProtocolDecorator extends TProtocol { - private final TProtocol concreteProtocol; + private final TProtocol concreteProtocol; - /** - * Encloses the specified protocol. - * @param protocol All operations will be forward to this protocol. Must be non-null. - */ - public TProtocolDecorator(TProtocol protocol) { - super(protocol.getTransport()); - concreteProtocol = protocol; - } + /** + * Encloses the specified protocol. + * + * @param protocol All operations will be forward to this protocol. Must be non-null. + */ + public TProtocolDecorator(TProtocol protocol) { + super(protocol.getTransport()); + concreteProtocol = protocol; + } - public void writeMessageBegin(TMessage tMessage) throws TException { - concreteProtocol.writeMessageBegin(tMessage); - } + public void writeMessageBegin(TMessage tMessage) throws TException { + concreteProtocol.writeMessageBegin(tMessage); + } - public void writeMessageEnd() throws TException { - concreteProtocol.writeMessageEnd(); - } + public void writeMessageEnd() throws TException { + concreteProtocol.writeMessageEnd(); + } - public void writeStructBegin(TStruct tStruct) throws TException { - concreteProtocol.writeStructBegin(tStruct); - } + public void writeStructBegin(TStruct tStruct) throws TException { + concreteProtocol.writeStructBegin(tStruct); + } - public void writeStructEnd() throws TException { - concreteProtocol.writeStructEnd(); - } + public void writeStructEnd() throws TException { + concreteProtocol.writeStructEnd(); + } - public void writeFieldBegin(TField tField) throws TException { - concreteProtocol.writeFieldBegin(tField); - } + public void writeFieldBegin(TField tField) throws TException { + concreteProtocol.writeFieldBegin(tField); + } - public void writeFieldEnd() throws TException { - concreteProtocol.writeFieldEnd(); - } + public void writeFieldEnd() throws TException { + concreteProtocol.writeFieldEnd(); + } - public void writeFieldStop() throws TException { - concreteProtocol.writeFieldStop(); - } + public void writeFieldStop() throws TException { + concreteProtocol.writeFieldStop(); + } - public void writeMapBegin(TMap tMap) throws TException { - concreteProtocol.writeMapBegin(tMap); - } + public void writeMapBegin(TMap tMap) throws TException { + concreteProtocol.writeMapBegin(tMap); + } - public void writeMapEnd() throws TException { - concreteProtocol.writeMapEnd(); - } + public void writeMapEnd() throws TException { + concreteProtocol.writeMapEnd(); + } - public void writeListBegin(TList tList) throws TException { - concreteProtocol.writeListBegin(tList); - } + public void writeListBegin(TList tList) throws TException { + concreteProtocol.writeListBegin(tList); + } - public void writeListEnd() throws TException { - concreteProtocol.writeListEnd(); - } + public void writeListEnd() throws TException { + concreteProtocol.writeListEnd(); + } - public void writeSetBegin(TSet tSet) throws TException { - concreteProtocol.writeSetBegin(tSet); - } + public void writeSetBegin(TSet tSet) throws TException { + concreteProtocol.writeSetBegin(tSet); + } - public void writeSetEnd() throws TException { - concreteProtocol.writeSetEnd(); - } + public void writeSetEnd() throws TException { + concreteProtocol.writeSetEnd(); + } - public void writeBool(boolean b) throws TException { - concreteProtocol.writeBool(b); - } + public void writeBool(boolean b) throws TException { + concreteProtocol.writeBool(b); + } - public void writeByte(byte b) throws TException { - concreteProtocol.writeByte(b); - } + public void writeByte(byte b) throws TException { + concreteProtocol.writeByte(b); + } - public void writeI16(short i) throws TException { - concreteProtocol.writeI16(i); - } + public void writeI16(short i) throws TException { + concreteProtocol.writeI16(i); + } - public void writeI32(int i) throws TException { - concreteProtocol.writeI32(i); - } - - public void writeI64(long l) throws TException { - concreteProtocol.writeI64(l); - } - - public void writeDouble(double v) throws TException { - concreteProtocol.writeDouble(v); - } - - public void writeString(String s) throws TException { - concreteProtocol.writeString(s); - } - - public void writeBinary(ByteBuffer buf) throws TException { - concreteProtocol.writeBinary(buf); - } - - public TMessage readMessageBegin() throws TException { - return concreteProtocol.readMessageBegin(); - } - - public void readMessageEnd() throws TException { - concreteProtocol.readMessageEnd(); - } - - public TStruct readStructBegin() throws TException { - return concreteProtocol.readStructBegin(); - } - - public void readStructEnd() throws TException { - concreteProtocol.readStructEnd(); - } - - public TField readFieldBegin() throws TException { - return concreteProtocol.readFieldBegin(); - } - - public void readFieldEnd() throws TException { - concreteProtocol.readFieldEnd(); - } - - public TMap readMapBegin() throws TException { - return concreteProtocol.readMapBegin(); - } - - public void readMapEnd() throws TException { - concreteProtocol.readMapEnd(); - } - - public TList readListBegin() throws TException { - return concreteProtocol.readListBegin(); - } - - public void readListEnd() throws TException { - concreteProtocol.readListEnd(); - } - - public TSet readSetBegin() throws TException { - return concreteProtocol.readSetBegin(); - } - - public void readSetEnd() throws TException { - concreteProtocol.readSetEnd(); - } - - public boolean readBool() throws TException { - return concreteProtocol.readBool(); - } - - public byte readByte() throws TException { - return concreteProtocol.readByte(); - } - - public short readI16() throws TException { - return concreteProtocol.readI16(); - } - - public int readI32() throws TException { - return concreteProtocol.readI32(); - } - - public long readI64() throws TException { - return concreteProtocol.readI64(); - } - - public double readDouble() throws TException { - return concreteProtocol.readDouble(); - } - - public String readString() throws TException { - return concreteProtocol.readString(); - } - - public ByteBuffer readBinary() throws TException { - return concreteProtocol.readBinary(); - } - - /** - * - * @param type Returns the minimum amount of bytes needed to store the smallest possible instance of TType. - * @return - * @throws TException - */ - public int getMinSerializedSize(byte type) throws TException { - return concreteProtocol.getMinSerializedSize(type); - } + public void writeI32(int i) throws TException { + concreteProtocol.writeI32(i); + } + + public void writeI64(long l) throws TException { + concreteProtocol.writeI64(l); + } + + public void writeDouble(double v) throws TException { + concreteProtocol.writeDouble(v); + } + + public void writeString(String s) throws TException { + concreteProtocol.writeString(s); + } + + public void writeBinary(ByteBuffer buf) throws TException { + concreteProtocol.writeBinary(buf); + } + + public TMessage readMessageBegin() throws TException { + return concreteProtocol.readMessageBegin(); + } + + public void readMessageEnd() throws TException { + concreteProtocol.readMessageEnd(); + } + + public TStruct readStructBegin() throws TException { + return concreteProtocol.readStructBegin(); + } + + public void readStructEnd() throws TException { + concreteProtocol.readStructEnd(); + } + + public TField readFieldBegin() throws TException { + return concreteProtocol.readFieldBegin(); + } + + public void readFieldEnd() throws TException { + concreteProtocol.readFieldEnd(); + } + + public TMap readMapBegin() throws TException { + return concreteProtocol.readMapBegin(); + } + + public void readMapEnd() throws TException { + concreteProtocol.readMapEnd(); + } + + public TList readListBegin() throws TException { + return concreteProtocol.readListBegin(); + } + + public void readListEnd() throws TException { + concreteProtocol.readListEnd(); + } + + public TSet readSetBegin() throws TException { + return concreteProtocol.readSetBegin(); + } + + public void readSetEnd() throws TException { + concreteProtocol.readSetEnd(); + } + + public boolean readBool() throws TException { + return concreteProtocol.readBool(); + } + + public byte readByte() throws TException { + return concreteProtocol.readByte(); + } + + public short readI16() throws TException { + return concreteProtocol.readI16(); + } + + public int readI32() throws TException { + return concreteProtocol.readI32(); + } + + public long readI64() throws TException { + return concreteProtocol.readI64(); + } + + public double readDouble() throws TException { + return concreteProtocol.readDouble(); + } + + public String readString() throws TException { + return concreteProtocol.readString(); + } + + public ByteBuffer readBinary() throws TException { + return concreteProtocol.readBinary(); + } + + /** + * @param type Returns the minimum amount of bytes needed to store the smallest possible instance + * of TType. + * @return + * @throws TException + */ + public int getMinSerializedSize(byte type) throws TException { + return concreteProtocol.getMinSerializedSize(type); + } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java index 870f1b939..3d645c47f 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java @@ -21,13 +21,9 @@ package org.apache.thrift.protocol; import org.apache.thrift.TException; -/** - * Protocol exceptions. - * - */ +/** Protocol exceptions. */ public class TProtocolException extends TException { - private static final long serialVersionUID = 1L; public static final int UNKNOWN = 0; public static final int INVALID_DATA = 1; @@ -78,5 +74,4 @@ public class TProtocolException extends TException { public int getType() { return type_; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java index b72e87b38..b99725320 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java @@ -20,12 +20,9 @@ package org.apache.thrift.protocol; import java.io.Serializable; - import org.apache.thrift.transport.TTransport; -/** - * Factory interface for constructing protocol instances. - */ +/** Factory interface for constructing protocol instances. */ public interface TProtocolFactory extends Serializable { public TProtocol getProtocol(TTransport trans); } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java index cdaa30b87..86cfb459a 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java @@ -21,29 +21,20 @@ package org.apache.thrift.protocol; import org.apache.thrift.TException; -/** - * Utility class with static methods for interacting with protocol data - * streams. - * - */ +/** Utility class with static methods for interacting with protocol data streams. */ public class TProtocolUtil { - /** - * The maximum recursive depth the skip() function will traverse before - * throwing a TException. - */ + /** The maximum recursive depth the skip() function will traverse before throwing a TException. */ private static int maxSkipDepth = Integer.MAX_VALUE; /** - * Specifies the maximum recursive depth that the skip function will - * traverse before throwing a TException. This is a global setting, so - * any call to skip in this JVM will enforce this value. + * Specifies the maximum recursive depth that the skip function will traverse before throwing a + * TException. This is a global setting, so any call to skip in this JVM will enforce this value. * - * @param depth the maximum recursive depth. A value of 2 would allow - * the skip function to skip a structure or collection with basic children, - * but it would not permit skipping a struct that had a field containing - * a child struct. A value of 1 would only allow skipping of simple - * types and empty structs/collections. + * @param depth the maximum recursive depth. A value of 2 would allow the skip function to skip a + * structure or collection with basic children, but it would not permit skipping a struct that + * had a field containing a child struct. A value of 1 would only allow skipping of simple + * types and empty structs/collections. */ public static void setMaxSkipDepth(int depth) { maxSkipDepth = depth; @@ -52,24 +43,22 @@ public class TProtocolUtil { /** * Skips over the next data element from the provided input TProtocol object. * - * @param prot the protocol object to read from - * @param type the next value will be interpreted as this TType value. + * @param prot the protocol object to read from + * @param type the next value will be interpreted as this TType value. */ - public static void skip(TProtocol prot, byte type) - throws TException { + public static void skip(TProtocol prot, byte type) throws TException { skip(prot, type, maxSkipDepth); } /** * Skips over the next data element from the provided input TProtocol object. * - * @param prot the protocol object to read from - * @param type the next value will be interpreted as this TType value. - * @param maxDepth this function will only skip complex objects to this - * recursive depth, to prevent Java stack overflow. + * @param prot the protocol object to read from + * @param type the next value will be interpreted as this TType value. + * @param maxDepth this function will only skip complex objects to this recursive depth, to + * prevent Java stack overflow. */ - public static void skip(TProtocol prot, byte type, int maxDepth) - throws TException { + public static void skip(TProtocol prot, byte type, int maxDepth) throws TException { if (maxDepth <= 0) { throw new TException("Maximum skip depth exceeded"); } @@ -141,19 +130,16 @@ public class TProtocolUtil { break; default: - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Unrecognized type " + type); + throw new TProtocolException(TProtocolException.INVALID_DATA, "Unrecognized type " + type); } } /** * Attempt to determine the protocol used to serialize some data. * - * The guess is based on known specificities of supported protocols. - * In some cases, no guess can be done, in that case we return the - * fallback TProtocolFactory. - * To be certain to correctly detect the protocol, the first encoded - * field should have a field id < 256 + * <p>The guess is based on known specificities of supported protocols. In some cases, no guess + * can be done, in that case we return the fallback TProtocolFactory. To be certain to correctly + * detect the protocol, the first encoded field should have a field id < 256 * * @param data The serialized data to guess the protocol for. * @param fallback The TProtocol to return if no guess can be made. diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java b/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java index 38be9a991..1d1651e7f 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates set metadata. - * - */ +/** Helper class that encapsulates set metadata. */ public final class TSet { public TSet() { this(TType.STOP, 0); @@ -38,5 +35,5 @@ public final class TSet { } public final byte elemType; - public final int size; + public final int size; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java index 6a3ee55d9..506572b59 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java @@ -22,7 +22,6 @@ package org.apache.thrift.protocol; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Stack; - import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; @@ -30,16 +29,12 @@ import org.apache.thrift.transport.TTransportException; /** * JSON protocol implementation for thrift. * - * This protocol is write-only and produces a simple output format - * suitable for parsing by scripting languages. It should not be - * confused with the full-featured TJSONProtocol. - * + * <p>This protocol is write-only and produces a simple output format suitable for parsing by + * scripting languages. It should not be confused with the full-featured TJSONProtocol. */ public class TSimpleJSONProtocol extends TProtocol { - /** - * Factory - */ + /** Factory */ public static class Factory implements TProtocolFactory { public TProtocol getProtocol(TTransport trans) { return new TSimpleJSONProtocol(trans); @@ -67,10 +62,10 @@ public class TSimpleJSONProtocol extends TProtocol { protected class Context { protected void write() throws TException {} - /** - * Returns whether the current value is a key in a map - */ - protected boolean isMapKey() { return false; } + /** Returns whether the current value is a key in a map */ + protected boolean isMapKey() { + return false; + } } protected class ListContext extends Context { @@ -118,52 +113,39 @@ public class TSimpleJSONProtocol extends TProtocol { protected final Context BASE_CONTEXT = new Context(); - /** - * Stack of nested contexts that we may be in. - */ + /** Stack of nested contexts that we may be in. */ protected Stack<Context> writeContextStack_ = new Stack<Context>(); - /** - * Current context that we are in - */ + /** Current context that we are in */ protected Context writeContext_ = BASE_CONTEXT; - /** - * Push a new write context onto the stack. - */ + /** Push a new write context onto the stack. */ protected void pushWriteContext(Context c) { writeContextStack_.push(writeContext_); writeContext_ = c; } - /** - * Pop the last write context off the stack - */ + /** Pop the last write context off the stack */ protected void popWriteContext() { writeContext_ = writeContextStack_.pop(); } - /** - * Reset the write context stack to its initial state. - */ + /** Reset the write context stack to its initial state. */ protected void resetWriteContext() { while (!writeContextStack_.isEmpty()) { popWriteContext(); } } - /** - * Used to make sure that we are not encountering a map whose keys are containers - */ + /** Used to make sure that we are not encountering a map whose keys are containers */ protected void assertContextIsNotMapKey(String invalidKeyType) throws CollectionMapKeyException { if (writeContext_.isMapKey()) { - throw new CollectionMapKeyException("Cannot serialize a map with keys that are of type " + invalidKeyType); + throw new CollectionMapKeyException( + "Cannot serialize a map with keys that are of type " + invalidKeyType); } } - /** - * Constructor - */ + /** Constructor */ public TSimpleJSONProtocol(TTransport trans) { super(trans); } @@ -256,7 +238,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeBool(boolean b) throws TException { - writeByte(b ? (byte)1 : (byte)0); + writeByte(b ? (byte) 1 : (byte) 0); } @Override @@ -271,7 +253,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeI32(int i32) throws TException { - if(writeContext_.isMapKey()) { + if (writeContext_.isMapKey()) { writeString(Integer.toString(i32)); } else { writeContext_.write(); @@ -286,7 +268,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeI64(long i64) throws TException { - if(writeContext_.isMapKey()) { + if (writeContext_.isMapKey()) { writeString(Long.toString(i64)); } else { writeContext_.write(); @@ -296,7 +278,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeDouble(double dub) throws TException { - if(writeContext_.isMapKey()) { + if (writeContext_.isMapKey()) { writeString(Double.toString(dub)); } else { writeContext_.write(); @@ -313,45 +295,45 @@ public class TSimpleJSONProtocol extends TProtocol { for (int i = 0; i < length; ++i) { char c = str.charAt(i); switch (c) { - case '"': - case '\\': - escape.append('\\'); - escape.append(c); - break; - case '\b': - escape.append('\\'); - escape.append('b'); - break; - case '\f': - escape.append('\\'); - escape.append('f'); - break; - case '\n': - escape.append('\\'); - escape.append('n'); - break; - case '\r': - escape.append('\\'); - escape.append('r'); - break; - case '\t': - escape.append('\\'); - escape.append('t'); - break; - default: - // Control characters! According to JSON RFC u0020 (space) - if (c < ' ') { - String hex = Integer.toHexString(c); + case '"': + case '\\': escape.append('\\'); - escape.append('u'); - for (int j = 4; j > hex.length(); --j) { - escape.append('0'); - } - escape.append(hex); - } else { escape.append(c); - } - break; + break; + case '\b': + escape.append('\\'); + escape.append('b'); + break; + case '\f': + escape.append('\\'); + escape.append('f'); + break; + case '\n': + escape.append('\\'); + escape.append('n'); + break; + case '\r': + escape.append('\\'); + escape.append('r'); + break; + case '\t': + escape.append('\\'); + escape.append('t'); + break; + default: + // Control characters! According to JSON RFC u0020 (space) + if (c < ' ') { + String hex = Integer.toHexString(c); + escape.append('\\'); + escape.append('u'); + for (int j = 4; j > hex.length(); --j) { + escape.append('0'); + } + escape.append(hex); + } else { + escape.append(c); + } + break; } } escape.append(QUOTE); @@ -361,19 +343,20 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeBinary(ByteBuffer bin) throws TException { // TODO(mcslee): Fix this - writeString(new String(bin.array(), bin.position() + bin.arrayOffset(), - bin.limit() - bin.position() - bin.arrayOffset(), - StandardCharsets.UTF_8)); + writeString( + new String( + bin.array(), + bin.position() + bin.arrayOffset(), + bin.limit() - bin.position() - bin.arrayOffset(), + StandardCharsets.UTF_8)); } /** * Reading methods. * - * simplejson is not meant to be read back into thrift - * - see http://wiki.apache.org/thrift/ThriftUsageJava - * - use JSON instead + * <p>simplejson is not meant to be read back into thrift - see + * http://wiki.apache.org/thrift/ThriftUsageJava - use JSON instead */ - @Override public TMessage readMessageBegin() throws TException { throw new TException("Not implemented"); @@ -381,7 +364,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readMessageEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TStruct readStructBegin() throws TException { @@ -390,7 +374,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readStructEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TField readFieldBegin() throws TException { @@ -399,7 +384,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readFieldEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TMap readMapBegin() throws TException { @@ -408,7 +394,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readMapEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TList readListBegin() throws TException { @@ -417,7 +404,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readListEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TSet readSetBegin() throws TException { @@ -426,7 +414,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readSetEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public boolean readBool() throws TException { @@ -478,27 +467,37 @@ public class TSimpleJSONProtocol extends TProtocol { } } - /** - * - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TException { - switch (type) - { - case 0: return 0; // Stop - case 1: return 0; // Void - case 2: return 1; // Bool - case 3: return 1; // Byte - case 4: return 1; // Double - case 6: return 1; // I16 - case 8: return 1; // I32 - case 10: return 1;// I64 - case 11: return 2; // string length - case 12: return 2; // empty struct - case 13: return 2; // element count Map - case 14: return 2; // element count Set - case 15: return 2; // element count List - default: throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool + case 3: + return 1; // Byte + case 4: + return 1; // Double + case 6: + return 1; // I16 + case 8: + return 1; // I32 + case 10: + return 1; // I64 + case 11: + return 2; // string length + case 12: + return 2; // empty struct + case 13: + return 2; // element count Map + case 14: + return 2; // element count Set + case 15: + return 2; // element count List + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java b/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java index a0f79012a..559c61413 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates struct metadata. - * - */ +/** Helper class that encapsulates struct metadata. */ public final class TStruct { public TStruct() { this(""); diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java index 67d00edb7..de47d6f0a 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java @@ -19,7 +19,6 @@ package org.apache.thrift.protocol; import java.util.BitSet; - import org.apache.thrift.TException; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.TupleScheme; @@ -51,7 +50,7 @@ public final class TTupleProtocol extends TCompactProtocol { } public BitSet readBitSet(int i) throws TException { - int length = (int) Math.ceil(i/8.0); + int length = (int) Math.ceil(i / 8.0); byte[] bytes = new byte[length]; for (int j = 0; j < length; j++) { bytes[j] = readByte(); @@ -60,10 +59,7 @@ public final class TTupleProtocol extends TCompactProtocol { return bs; } - /** - * Returns a bitset containing the values in bytes. The byte-ordering must be - * big-endian. - */ + /** Returns a bitset containing the values in bytes. The byte-ordering must be big-endian. */ public static BitSet fromByteArray(byte[] bytes) { BitSet bits = new BitSet(); for (int i = 0; i < bytes.length * 8; i++) { @@ -75,18 +71,17 @@ public final class TTupleProtocol extends TCompactProtocol { } /** - * Returns a byte array of at least length 1. The most significant bit in the - * result is guaranteed not to be a 1 (since BitSet does not support sign - * extension). The byte-ordering of the result is big-endian which means the - * most significant bit is in element 0. The bit at index 0 of the bit set is - * assumed to be the least significant bit. + * Returns a byte array of at least length 1. The most significant bit in the result is guaranteed + * not to be a 1 (since BitSet does not support sign extension). The byte-ordering of the result + * is big-endian which means the most significant bit is in element 0. The bit at index 0 of the + * bit set is assumed to be the least significant bit. * * @param bits * @param vectorWidth * @return a byte array of at least length 1 */ public static byte[] toByteArray(BitSet bits, int vectorWidth) { - byte[] bytes = new byte[(int) Math.ceil(vectorWidth/8.0)]; + byte[] bytes = new byte[(int) Math.ceil(vectorWidth / 8.0)]; for (int i = 0; i < bits.length(); i++) { if (bits.get(i)) { bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8); @@ -116,6 +111,8 @@ public final class TTupleProtocol extends TCompactProtocol { } public void readMapEnd() throws TException {} + public void readListEnd() throws TException {} + public void readSetEnd() throws TException {} } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TType.java b/lib/java/src/main/java/org/apache/thrift/protocol/TType.java index c3c1a0abd..4b70bb2b7 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TType.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TType.java @@ -19,22 +19,20 @@ package org.apache.thrift.protocol; -/** - * Type constants in the Thrift protocol. - */ +/** Type constants in the Thrift protocol. */ public final class TType { - public static final byte STOP = 0; - public static final byte VOID = 1; - public static final byte BOOL = 2; - public static final byte BYTE = 3; + public static final byte STOP = 0; + public static final byte VOID = 1; + public static final byte BOOL = 2; + public static final byte BYTE = 3; public static final byte DOUBLE = 4; - public static final byte I16 = 6; - public static final byte I32 = 8; - public static final byte I64 = 10; + public static final byte I16 = 6; + public static final byte I32 = 8; + public static final byte I64 = 10; public static final byte STRING = 11; public static final byte STRUCT = 12; - public static final byte MAP = 13; - public static final byte SET = 14; - public static final byte LIST = 15; - public static final byte ENUM = 16; + public static final byte MAP = 13; + public static final byte SET = 14; + public static final byte LIST = 15; + public static final byte ENUM = 16; } diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java b/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java index aa3550705..c4a85b95e 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java @@ -22,8 +22,9 @@ import org.apache.thrift.TBase; public interface IScheme<T extends TBase> { - public void read(org.apache.thrift.protocol.TProtocol iproto, T struct) throws org.apache.thrift.TException; - - public void write(org.apache.thrift.protocol.TProtocol oproto, T struct) throws org.apache.thrift.TException; + public void read(org.apache.thrift.protocol.TProtocol iproto, T struct) + throws org.apache.thrift.TException; + public void write(org.apache.thrift.protocol.TProtocol oproto, T struct) + throws org.apache.thrift.TException; } diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java b/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java index 006a66805..e9d76406d 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java @@ -21,5 +21,4 @@ package org.apache.thrift.scheme; public interface SchemeFactory { public <S extends IScheme> S getScheme(); - } diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java b/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java index ffab04db6..2d2683bea 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java @@ -20,6 +20,4 @@ package org.apache.thrift.scheme; import org.apache.thrift.TBase; -public abstract class StandardScheme<T extends TBase> implements IScheme<T> { - -} +public abstract class StandardScheme<T extends TBase> implements IScheme<T> {} diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java b/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java index 365242b11..0efa4cf2a 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java @@ -20,6 +20,4 @@ package org.apache.thrift.scheme; import org.apache.thrift.TBase; -public abstract class TupleScheme<T extends TBase> implements IScheme<T> { - -} +public abstract class TupleScheme<T extends TBase> implements IScheme<T> {} diff --git a/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java b/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java index beef954ef..44341d909 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java @@ -19,37 +19,35 @@ package org.apache.thrift.server; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.SelectorProvider; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; import org.apache.thrift.TAsyncProcessor; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TException; import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TNonblockingServerTransport; import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; +import org.apache.thrift.transport.layered.TFramedTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.SelectorProvider; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Provides common methods and classes used by nonblocking TServer - * implementations. - */ +/** Provides common methods and classes used by nonblocking TServer implementations. */ public abstract class AbstractNonblockingServer extends TServer { protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); - public static abstract class AbstractNonblockingServerArgs<T extends AbstractNonblockingServerArgs<T>> extends AbstractServerArgs<T> { + public abstract static class AbstractNonblockingServerArgs< + T extends AbstractNonblockingServerArgs<T>> + extends AbstractServerArgs<T> { public long maxReadBufferBytes = 256 * 1024 * 1024; public AbstractNonblockingServerArgs(TNonblockingServerTransport transport) { @@ -59,15 +57,13 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * The maximum amount of memory we will allocate to client IO buffers at a - * time. Without this limit, the server will gladly allocate client buffers - * right into an out of memory exception, rather than waiting. + * The maximum amount of memory we will allocate to client IO buffers at a time. Without this + * limit, the server will gladly allocate client buffers right into an out of memory exception, + * rather than waiting. */ final long MAX_READ_BUFFER_BYTES; - /** - * How many bytes are currently allocated to read buffers. - */ + /** How many bytes are currently allocated to read buffers. */ final AtomicLong readBufferBytesAllocated = new AtomicLong(0); public AbstractNonblockingServer(AbstractNonblockingServerArgs args) { @@ -75,9 +71,7 @@ public abstract class AbstractNonblockingServer extends TServer { MAX_READ_BUFFER_BYTES = args.maxReadBufferBytes; } - /** - * Begin accepting connections and processing invocations. - */ + /** Begin accepting connections and processing invocations. */ public void serve() { // start any IO threads if (!startThreads()) { @@ -107,17 +101,13 @@ public abstract class AbstractNonblockingServer extends TServer { */ protected abstract boolean startThreads(); - /** - * A method that will block until when threads handling the serving have been - * shut down. - */ + /** A method that will block until when threads handling the serving have been shut down. */ protected abstract void waitForShutdown(); /** * Have the server transport start accepting connections. * - * @return true if we started listening successfully, false if something went - * wrong. + * @return true if we started listening successfully, false if something went wrong. */ protected boolean startListening() { try { @@ -129,27 +119,23 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Stop listening for connections. - */ + /** Stop listening for connections. */ protected void stopListening() { serverTransport_.close(); } /** - * Perform an invocation. This method could behave several different ways - - * invoke immediately inline, queue for separate execution, etc. + * Perform an invocation. This method could behave several different ways - invoke immediately + * inline, queue for separate execution, etc. * - * @return true if invocation was successfully requested, which is not a - * guarantee that invocation has completed. False if the request - * failed. + * @return true if invocation was successfully requested, which is not a guarantee that invocation + * has completed. False if the request failed. */ protected abstract boolean requestInvoke(FrameBuffer frameBuffer); /** - * An abstract thread that handles selecting on a set of transports and - * {@link FrameBuffer FrameBuffers} associated with selected keys - * corresponding to requests. + * An abstract thread that handles selecting on a set of transports and {@link FrameBuffer + * FrameBuffers} associated with selected keys corresponding to requests. */ protected abstract class AbstractSelectThread extends Thread { protected Selector selector; @@ -161,17 +147,15 @@ public abstract class AbstractNonblockingServer extends TServer { this.selector = SelectorProvider.provider().openSelector(); } - /** - * If the selector is blocked, wake it up. - */ + /** If the selector is blocked, wake it up. */ public void wakeupSelector() { selector.wakeup(); } /** - * Add FrameBuffer to the list of select interest changes and wake up the - * selector if it's blocked. When the select() call exits, it'll give the - * FrameBuffer a chance to change its interests. + * Add FrameBuffer to the list of select interest changes and wake up the selector if it's + * blocked. When the select() call exits, it'll give the FrameBuffer a chance to change its + * interests. */ public void requestSelectInterestChange(FrameBuffer frameBuffer) { synchronized (selectInterestChanges) { @@ -182,8 +166,8 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * Check to see if there are any FrameBuffers that have switched their - * interest type from read to write or vice versa. + * Check to see if there are any FrameBuffers that have switched their interest type from read + * to write or vice versa. */ protected void processInterestChanges() { synchronized (selectInterestChanges) { @@ -195,8 +179,8 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * Do the work required to read from a readable client. If the frame is - * fully read, then invoke the method call. + * Do the work required to read from a readable client. If the frame is fully read, then invoke + * the method call. */ protected void handleRead(SelectionKey key) { FrameBuffer buffer = (FrameBuffer) key.attachment(); @@ -213,9 +197,7 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Let a writable client get written, if there's data to be written. - */ + /** Let a writable client get written, if there's data to be written. */ protected void handleWrite(SelectionKey key) { FrameBuffer buffer = (FrameBuffer) key.attachment(); if (!buffer.write()) { @@ -223,9 +205,7 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Do connection-close cleanup on a given SelectionKey. - */ + /** Do connection-close cleanup on a given SelectionKey. */ protected void cleanupSelectionKey(SelectionKey key) { // remove the records from the two maps FrameBuffer buffer = (FrameBuffer) key.attachment(); @@ -238,9 +218,7 @@ public abstract class AbstractNonblockingServer extends TServer { } } // SelectThread - /** - * Possible states for the FrameBuffer state machine. - */ + /** Possible states for the FrameBuffer state machine. */ private enum FrameBufferState { // in the midst of reading the frame size off the wire READING_FRAME_SIZE, @@ -260,13 +238,12 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * Class that implements a sort of state machine around the interaction with a - * client and an invoker. It manages reading the frame size and frame data, - * getting it handed off as wrapped transports, and then the writing of - * response data back to the client. In the process it manages flipping the - * read and write bits on the selection key for its client. + * Class that implements a sort of state machine around the interaction with a client and an + * invoker. It manages reading the frame size and frame data, getting it handed off as wrapped + * transports, and then the writing of response data back to the client. In the process it manages + * flipping the read and write bits on the selection key for its client. */ - public class FrameBuffer { + public class FrameBuffer { private final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); // the actual transport hooked up to the client. @@ -303,9 +280,11 @@ public abstract class AbstractNonblockingServer extends TServer { // context associated with this connection protected final ServerContext context_; - public FrameBuffer(final TNonblockingTransport trans, + public FrameBuffer( + final TNonblockingTransport trans, final SelectionKey selectionKey, - final AbstractSelectThread selectThread) throws TTransportException { + final AbstractSelectThread selectThread) + throws TTransportException { trans_ = trans; selectionKey_ = selectionKey; selectThread_ = selectThread; @@ -321,16 +300,15 @@ public abstract class AbstractNonblockingServer extends TServer { if (eventHandler_ != null) { context_ = eventHandler_.createContext(inProt_, outProt_); } else { - context_ = null; + context_ = null; } } /** - * Give this FrameBuffer a chance to read. The selector loop should have - * received a read event for this FrameBuffer. + * Give this FrameBuffer a chance to read. The selector loop should have received a read event + * for this FrameBuffer. * - * @return true if the connection should live on, false if it should be - * closed + * @return true if the connection should live on, false if it should be closed */ public boolean read() { if (state_ == FrameBufferState.READING_FRAME_SIZE) { @@ -345,17 +323,22 @@ public abstract class AbstractNonblockingServer extends TServer { // pull out the frame size as an integer. int frameSize = buffer_.getInt(0); if (frameSize <= 0) { - LOGGER.error("Read an invalid frame size of " + frameSize - + ". Are you using TFramedTransport on the client side?"); + LOGGER.error( + "Read an invalid frame size of " + + frameSize + + ". Are you using TFramedTransport on the client side?"); return false; } // if this frame will always be too large for this server, log the // error and close the connection. if (frameSize > trans_.getMaxFrameSize()) { - LOGGER.error("Read a frame size of " + frameSize - + ", which is bigger than the maximum allowable frame size " - + trans_.getMaxFrameSize() + " for ALL connections."); + LOGGER.error( + "Read a frame size of " + + frameSize + + ", which is bigger than the maximum allowable frame size " + + trans_.getMaxFrameSize() + + " for ALL connections."); return false; } @@ -406,9 +389,7 @@ public abstract class AbstractNonblockingServer extends TServer { return false; } - /** - * Give this FrameBuffer a chance to write its output to the final client. - */ + /** Give this FrameBuffer a chance to write its output to the final client. */ public boolean write() { if (state_ == FrameBufferState.WRITING) { try { @@ -431,40 +412,33 @@ public abstract class AbstractNonblockingServer extends TServer { return false; } - /** - * Give this FrameBuffer a chance to set its interest to write, once data - * has come in. - */ + /** Give this FrameBuffer a chance to set its interest to write, once data has come in. */ public void changeSelectInterests() { switch (state_) { - case AWAITING_REGISTER_WRITE: - // set the OP_WRITE interest - selectionKey_.interestOps(SelectionKey.OP_WRITE); - state_ = FrameBufferState.WRITING; - break; - case AWAITING_REGISTER_READ: - prepareRead(); - break; - case AWAITING_CLOSE: - close(); - selectionKey_.cancel(); - break; - default: - LOGGER.error( - "changeSelectInterest was called, but state is invalid ({})", - state_); + case AWAITING_REGISTER_WRITE: + // set the OP_WRITE interest + selectionKey_.interestOps(SelectionKey.OP_WRITE); + state_ = FrameBufferState.WRITING; + break; + case AWAITING_REGISTER_READ: + prepareRead(); + break; + case AWAITING_CLOSE: + close(); + selectionKey_.cancel(); + break; + default: + LOGGER.error("changeSelectInterest was called, but state is invalid ({})", state_); } } - /** - * Shut the connection down. - */ + /** Shut the connection down. */ public void close() { // if we're being closed due to an error, we might have allocated a // buffer that we need to subtract for our memory accounting. - if (state_ == FrameBufferState.READING_FRAME || - state_ == FrameBufferState.READ_FRAME_COMPLETE || - state_ == FrameBufferState.AWAITING_CLOSE) { + if (state_ == FrameBufferState.READING_FRAME + || state_ == FrameBufferState.READ_FRAME_COMPLETE + || state_ == FrameBufferState.AWAITING_CLOSE) { readBufferBytesAllocated.addAndGet(-buffer_.array().length); } trans_.close(); @@ -473,19 +447,16 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Check if this FrameBuffer has a full frame read. - */ + /** Check if this FrameBuffer has a full frame read. */ public boolean isFrameFullyRead() { return state_ == FrameBufferState.READ_FRAME_COMPLETE; } /** - * After the processor has processed the invocation, whatever thread is - * managing invocations should call this method on this FrameBuffer so we - * know it's time to start trying to write again. Also, if it turns out that - * there actually isn't any data in the response buffer, we'll skip trying - * to write and instead go back to reading. + * After the processor has processed the invocation, whatever thread is managing invocations + * should call this method on this FrameBuffer so we know it's time to start trying to write + * again. Also, if it turns out that there actually isn't any data in the response buffer, we'll + * skip trying to write and instead go back to reading. */ public void responseReady() { // the read buffer is definitely no longer in use, so we will decrement @@ -511,9 +482,7 @@ public abstract class AbstractNonblockingServer extends TServer { requestSelectInterestChange(); } - /** - * Actually invoke the method signified by this FrameBuffer. - */ + /** Actually invoke the method signified by this FrameBuffer. */ public void invoke() { frameTrans_.reset(buffer_.array()); response_.reset(); @@ -538,22 +507,18 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Perform a read into buffer. * - * @return true if the read succeeded, false if there was an error or the - * connection closed. + * @return true if the read succeeded, false if there was an error or the connection closed. */ private boolean internalRead() { try { - return trans_.read(buffer_) >= 0; + return trans_.read(buffer_) >= 0; } catch (TTransportException e) { LOGGER.warn("Got an Exception in internalRead", e); return false; } } - /** - * We're done writing, so reset our interest ops and change state - * accordingly. - */ + /** We're done writing, so reset our interest ops and change state accordingly. */ private void prepareRead() { // we can set our interest directly without using the queue because // we're in the select thread. @@ -564,11 +529,10 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * When this FrameBuffer needs to change its select interests and execution - * might not be in its select thread, then this method will make sure the - * interest change gets done when the select thread wakes back up. When the - * current thread is this FrameBuffer's select thread, then it just does the - * interest change immediately. + * When this FrameBuffer needs to change its select interests and execution might not be in its + * select thread, then this method will make sure the interest change gets done when the select + * thread wakes back up. When the current thread is this FrameBuffer's select thread, then it + * just does the interest change immediately. */ protected void requestSelectInterestChange() { if (Thread.currentThread() == this.selectThread_) { @@ -580,19 +544,20 @@ public abstract class AbstractNonblockingServer extends TServer { } // FrameBuffer public class AsyncFrameBuffer extends FrameBuffer { - public AsyncFrameBuffer(TNonblockingTransport trans, SelectionKey selectionKey, AbstractSelectThread selectThread) throws TTransportException { + public AsyncFrameBuffer( + TNonblockingTransport trans, SelectionKey selectionKey, AbstractSelectThread selectThread) + throws TTransportException { super(trans, selectionKey, selectThread); } public TProtocol getInputProtocol() { - return inProt_; + return inProt_; } public TProtocol getOutputProtocol() { return outProt_; } - public void invoke() { frameTrans_.reset(buffer_.array()); response_.reset(); @@ -601,7 +566,7 @@ public abstract class AbstractNonblockingServer extends TServer { if (eventHandler_ != null) { eventHandler_.processContext(context_, inTrans_, outTrans_); } - ((TAsyncProcessor)processorFactory_.getProcessor(inTrans_)).process(this); + ((TAsyncProcessor) processorFactory_.getProcessor(inTrans_)).process(this); return; } catch (TException te) { LOGGER.warn("Exception while invoking!", te); diff --git a/lib/java/src/main/java/org/apache/thrift/server/Invocation.java b/lib/java/src/main/java/org/apache/thrift/server/Invocation.java index e8210f419..64f896927 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/Invocation.java +++ b/lib/java/src/main/java/org/apache/thrift/server/Invocation.java @@ -3,9 +3,9 @@ package org.apache.thrift.server; import org.apache.thrift.server.AbstractNonblockingServer.FrameBuffer; /** - * An Invocation represents a method call that is prepared to execute, given - * an idle worker thread. It contains the input and output protocols the - * thread's processor should use to perform the usual Thrift invocation. + * An Invocation represents a method call that is prepared to execute, given an idle worker thread. + * It contains the input and output protocols the thread's processor should use to perform the usual + * Thrift invocation. */ class Invocation implements Runnable { private final FrameBuffer frameBuffer; @@ -17,4 +17,4 @@ class Invocation implements Runnable { public void run() { frameBuffer.invoke(); } -}
\ No newline at end of file +} diff --git a/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java b/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java index b7c587f37..adf2a438b 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java +++ b/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java @@ -17,33 +17,29 @@ * under the License. */ -/** - * Interface for storing server's connection context. - */ +/** Interface for storing server's connection context. */ package org.apache.thrift.server; public interface ServerContext { /** - * Returns an object that implements the given interface to allow access to - * application specific contexts. + * Returns an object that implements the given interface to allow access to application specific + * contexts. * * @param iface A Class defining an interface that the result must implement * @return an object that implements the interface - * @throws RuntimeException If the context cannot be unwrapped to the provided - * class + * @throws RuntimeException If the context cannot be unwrapped to the provided class */ <T> T unwrap(Class<T> iface); /** - * Returns true if this server context is a wrapper for the provided - * application specific context interface argument or returns false otherwise. + * Returns true if this server context is a wrapper for the provided application specific context + * interface argument or returns false otherwise. * * @param iface a Class defining the underlying context - * @return true if this implements the interface can be unwrapped to the - * provided class - * @throws RuntimeException if an error occurs while determining whether the - * provided class can be unwrapped from this context. + * @return true if this implements the interface can be unwrapped to the provided class + * @throws RuntimeException if an error occurs while determining whether the provided class can be + * unwrapped from this context. */ boolean isWrapperFor(Class<?> iface); } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java b/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java index 75082c0f7..5773e9c3c 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java @@ -25,14 +25,12 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Map; - import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -41,12 +39,11 @@ import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransport; /** - * Servlet implementation class ThriftServer, that allows {@link TProcessor} and - * {@link TProtocolFactory} to be supplied after the {@link #init()} method has - * finished. <br> - * Subclasses must implement the abstract methods that return the TProcessor and - * two TProtocolFactory. Those methods are guaranteed to be called exactly once, - * and that {@link ServletContext} is available. + * Servlet implementation class ThriftServer, that allows {@link TProcessor} and {@link + * TProtocolFactory} to be supplied after the {@link #init()} method has finished. <br> + * Subclasses must implement the abstract methods that return the TProcessor and two + * TProtocolFactory. Those methods are guaranteed to be called exactly once, and that {@link + * ServletContext} is available. */ public abstract class TExtensibleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @@ -60,32 +57,32 @@ public abstract class TExtensibleServlet extends HttpServlet { private Collection<Map.Entry<String, String>> customHeaders; /** - * Returns the appropriate {@link TProcessor}. This will be called <b>once</b> just - * after the {@link #init()} method - * + * Returns the appropriate {@link TProcessor}. This will be called <b>once</b> just after the + * {@link #init()} method + * * @return the appropriate {@link TProcessor} */ protected abstract TProcessor getProcessor(); /** - * Returns the appropriate in {@link TProtocolFactory}. This will be called - * <b>once</b> just after the {@link #init()} method - * + * Returns the appropriate in {@link TProtocolFactory}. This will be called <b>once</b> just after + * the {@link #init()} method + * * @return the appropriate in {@link TProtocolFactory} */ protected abstract TProtocolFactory getInProtocolFactory(); /** - * Returns the appropriate out {@link TProtocolFactory}. This will be called - * <b>once</b> just after the {@link #init()} method - * + * Returns the appropriate out {@link TProtocolFactory}. This will be called <b>once</b> just + * after the {@link #init()} method + * * @return the appropriate out {@link TProtocolFactory} */ protected abstract TProtocolFactory getOutProtocolFactory(); @Override public final void init(ServletConfig config) throws ServletException { - super.init(config); //no-args init() happens here + super.init(config); // no-args init() happens here this.processor = getProcessor(); this.inFactory = getInProtocolFactory(); this.outFactory = getOutProtocolFactory(); @@ -102,10 +99,7 @@ public abstract class TExtensibleServlet extends HttpServlet { } } - /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -116,9 +110,9 @@ public abstract class TExtensibleServlet extends HttpServlet { response.setContentType("application/x-thrift"); if (null != this.customHeaders) { - for (Map.Entry<String, String> header : this.customHeaders) { - response.addHeader(header.getKey(), header.getValue()); - } + for (Map.Entry<String, String> header : this.customHeaders) { + response.addHeader(header.getKey(), header.getValue()); + } } InputStream in = request.getInputStream(); @@ -138,10 +132,7 @@ public abstract class TExtensibleServlet extends HttpServlet { } } - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -149,19 +140,20 @@ public abstract class TExtensibleServlet extends HttpServlet { } public void addCustomHeader(final String key, final String value) { - this.customHeaders.add(new Map.Entry<String, String>() { - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - public String setValue(String value) { - return null; - } - }); + this.customHeaders.add( + new Map.Entry<String, String>() { + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + public String setValue(String value) { + return null; + } + }); } public void setCustomHeaders(Collection<Map.Entry<String, String>> headers) { diff --git a/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java b/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java index 4c5d7b5b5..6e59638a5 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.server; import java.util.concurrent.ExecutorService; @@ -25,12 +24,11 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; - import org.apache.thrift.transport.TNonblockingServerTransport; /** - * An extension of the TNonblockingServer to a Half-Sync/Half-Async server. - * Like TNonblockingServer, it relies on the use of TFramedTransport. + * An extension of the TNonblockingServer to a Half-Sync/Half-Async server. Like TNonblockingServer, + * it relies on the use of TFramedTransport. */ public class THsHaServer extends TNonblockingServer { @@ -45,11 +43,10 @@ public class THsHaServer extends TNonblockingServer { super(transport); } - /** * Sets the min and max threads. * - * @deprecated use {@link #minWorkerThreads(int)} and {@link #maxWorkerThreads(int)} instead. + * @deprecated use {@link #minWorkerThreads(int)} and {@link #maxWorkerThreads(int)} instead. */ @Deprecated public Args workerThreads(int n) { @@ -113,16 +110,13 @@ public class THsHaServer extends TNonblockingServer { } } - // This wraps all the functionality of queueing and thread pool management // for the passing of Invocations from the Selector to workers. private final ExecutorService invoker; private final Args args; - /** - * Create the server with the specified Args configuration - */ + /** Create the server with the specified Args configuration */ public THsHaServer(Args args) { super(args); @@ -130,18 +124,14 @@ public class THsHaServer extends TNonblockingServer { this.args = args; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override protected void waitForShutdown() { joinSelector(); gracefullyShutdownInvokerPool(); } - /** - * Helper to create an invoker pool - */ + /** Helper to create an invoker pool */ protected static ExecutorService createInvokerPool(Args options) { int minWorkerThreads = options.minWorkerThreads; int maxWorkerThreads = options.maxWorkerThreads; @@ -149,8 +139,9 @@ public class THsHaServer extends TNonblockingServer { TimeUnit stopTimeoutUnit = options.stopTimeoutUnit; LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(); - ExecutorService invoker = new ThreadPoolExecutor(minWorkerThreads, - maxWorkerThreads, stopTimeoutVal, stopTimeoutUnit, queue); + ExecutorService invoker = + new ThreadPoolExecutor( + minWorkerThreads, maxWorkerThreads, stopTimeoutVal, stopTimeoutUnit, queue); return invoker; } @@ -182,9 +173,8 @@ public class THsHaServer extends TNonblockingServer { } /** - * We override the standard invoke method here to queue the invocation for - * invoker service instead of immediately invoking. The thread pool takes care - * of the rest. + * We override the standard invoke method here to queue the invocation for invoker service instead + * of immediately invoking. The thread pool takes care of the rest. */ @Override protected boolean requestInvoke(FrameBuffer frameBuffer) { @@ -198,7 +188,7 @@ public class THsHaServer extends TNonblockingServer { } } - protected Runnable getRunnable(FrameBuffer frameBuffer){ + protected Runnable getRunnable(FrameBuffer frameBuffer) { return new Invocation(frameBuffer); } } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java b/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java index eac05a876..fa75569d9 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java @@ -17,27 +17,25 @@ * under the License. */ - package org.apache.thrift.server; -import org.apache.thrift.transport.TNonblockingServerTransport; -import org.apache.thrift.transport.TNonblockingTransport; -import org.apache.thrift.transport.TTransportException; - import java.io.IOException; import java.nio.channels.SelectionKey; import java.util.Iterator; +import org.apache.thrift.transport.TNonblockingServerTransport; +import org.apache.thrift.transport.TNonblockingTransport; +import org.apache.thrift.transport.TTransportException; /** - * A nonblocking TServer implementation. This allows for fairness amongst all - * connected clients in terms of invocations. + * A nonblocking TServer implementation. This allows for fairness amongst all connected clients in + * terms of invocations. * - * This server is inherently single-threaded. If you want a limited thread pool - * coupled with invocation-fairness, see THsHaServer. + * <p>This server is inherently single-threaded. If you want a limited thread pool coupled with + * invocation-fairness, see THsHaServer. * - * To use this server, you MUST use a TFramedTransport at the outermost - * transport, otherwise this server will be unable to determine when a whole - * method call has been read off the wire. Clients must also use TFramedTransport. + * <p>To use this server, you MUST use a TFramedTransport at the outermost transport, otherwise this + * server will be unable to determine when a whole method call has been read off the wire. Clients + * must also use TFramedTransport. */ public class TNonblockingServer extends AbstractNonblockingServer { @@ -53,18 +51,16 @@ public class TNonblockingServer extends AbstractNonblockingServer { super(args); } - /** * Start the selector thread to deal with accepts and client messages. * - * @return true if everything went ok, false if we couldn't start for some - * reason. + * @return true if everything went ok, false if we couldn't start for some reason. */ @Override protected boolean startThreads() { // start the selector try { - selectAcceptThread_ = new SelectAcceptThread((TNonblockingServerTransport)serverTransport_); + selectAcceptThread_ = new SelectAcceptThread((TNonblockingServerTransport) serverTransport_); selectAcceptThread_.start(); return true; } catch (IOException e) { @@ -78,9 +74,7 @@ public class TNonblockingServer extends AbstractNonblockingServer { joinSelector(); } - /** - * Block until the selector thread exits. - */ + /** Block until the selector thread exits. */ protected void joinSelector() { // wait until the selector thread exits try { @@ -91,9 +85,7 @@ public class TNonblockingServer extends AbstractNonblockingServer { } } - /** - * Stop serving and shut everything down. - */ + /** Stop serving and shut everything down. */ @Override public void stop() { stopped_ = true; @@ -103,8 +95,8 @@ public class TNonblockingServer extends AbstractNonblockingServer { } /** - * Perform an invocation. This method could behave several different ways - * - invoke immediately inline, queue for separate execution, etc. + * Perform an invocation. This method could behave several different ways - invoke immediately + * inline, queue for separate execution, etc. */ @Override protected boolean requestInvoke(FrameBuffer frameBuffer) { @@ -112,26 +104,22 @@ public class TNonblockingServer extends AbstractNonblockingServer { return true; } - public boolean isStopped() { return selectAcceptThread_.isStopped(); } /** - * The thread that will be doing all the selecting, managing new connections - * and those that still need to be read. + * The thread that will be doing all the selecting, managing new connections and those that still + * need to be read. */ protected class SelectAcceptThread extends AbstractSelectThread { // The server transport on which new client transports will be accepted private final TNonblockingServerTransport serverTransport; - /** - * Set up the thread that will handle the non-blocking accepts, reads, and - * writes. - */ + /** Set up the thread that will handle the non-blocking accepts, reads, and writes. */ public SelectAcceptThread(final TNonblockingServerTransport serverTransport) - throws IOException { + throws IOException { this.serverTransport = serverTransport; serverTransport.registerSelector(selector); } @@ -141,8 +129,8 @@ public class TNonblockingServer extends AbstractNonblockingServer { } /** - * The work loop. Handles both selecting (all IO operations) and managing - * the selection preferences of all existing connections. + * The work loop. Handles both selecting (all IO operations) and managing the selection + * preferences of all existing connections. */ public void run() { try { @@ -170,12 +158,10 @@ public class TNonblockingServer extends AbstractNonblockingServer { } /** - * Select and process IO events appropriately: - * If there are connections to be accepted, accept them. - * If there are existing connections with data waiting to be read, read it, - * buffering until a whole frame has been read. - * If there are any pending responses, buffer them until their target client - * is available, and then send the data. + * Select and process IO events appropriately: If there are connections to be accepted, accept + * them. If there are existing connections with data waiting to be read, read it, buffering + * until a whole frame has been read. If there are any pending responses, buffer them until + * their target client is available, and then send the data. */ private void select() { try { @@ -213,17 +199,17 @@ public class TNonblockingServer extends AbstractNonblockingServer { } } - protected FrameBuffer createFrameBuffer(final TNonblockingTransport trans, + protected FrameBuffer createFrameBuffer( + final TNonblockingTransport trans, final SelectionKey selectionKey, - final AbstractSelectThread selectThread) throws TTransportException { - return processorFactory_.isAsyncProcessor() ? - new AsyncFrameBuffer(trans, selectionKey, selectThread) : - new FrameBuffer(trans, selectionKey, selectThread); + final AbstractSelectThread selectThread) + throws TTransportException { + return processorFactory_.isAsyncProcessor() + ? new AsyncFrameBuffer(trans, selectionKey, selectThread) + : new FrameBuffer(trans, selectionKey, selectThread); } - /** - * Accept a new connection. - */ + /** Accept a new connection. */ private void handleAccept() throws IOException { SelectionKey clientKey = null; TNonblockingTransport client = null; @@ -233,9 +219,9 @@ public class TNonblockingServer extends AbstractNonblockingServer { clientKey = client.registerSelector(selector, SelectionKey.OP_READ); // add this key to the map - FrameBuffer frameBuffer = createFrameBuffer(client, clientKey, SelectAcceptThread.this); + FrameBuffer frameBuffer = createFrameBuffer(client, clientKey, SelectAcceptThread.this); - clientKey.attach(frameBuffer); + clientKey.attach(frameBuffer); } catch (TTransportException tte) { // something went wrong accepting. LOGGER.warn("Exception trying to accept!", tte); diff --git a/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java b/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java index 89dbb7872..6f22d8bb4 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java @@ -32,9 +32,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; - import javax.security.auth.callback.CallbackHandler; - import org.apache.thrift.TProcessor; import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TNonblockingServerTransport; @@ -48,9 +46,7 @@ import org.apache.thrift.transport.sasl.TSaslServerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * TServer with sasl support, using asynchronous execution and nonblocking io. - */ +/** TServer with sasl support, using asynchronous execution and nonblocking io. */ public class TSaslNonblockingServer extends TServer { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslNonblockingServer.class); @@ -85,9 +81,7 @@ public class TSaslNonblockingServer extends TServer { setServing(true); } - /** - * Trigger a graceful shutdown, but it does not block to wait for the shutdown to finish. - */ + /** Trigger a graceful shutdown, but it does not block to wait for the shutdown to finish. */ @Override public void stop() { if (!stopped_) { @@ -202,8 +196,10 @@ public class TSaslNonblockingServer extends TServer { } private class NetworkThread extends Thread { - private final BlockingQueue<TNonblockingTransport> incomingConnections = new LinkedBlockingQueue<>(); - private final BlockingQueue<NonblockingSaslHandler> stateTransitions = new LinkedBlockingQueue<>(); + private final BlockingQueue<TNonblockingTransport> incomingConnections = + new LinkedBlockingQueue<>(); + private final BlockingQueue<NonblockingSaslHandler> stateTransitions = + new LinkedBlockingQueue<>(); private final Selector ioSelector; NetworkThread(String name) throws IOException { @@ -285,9 +281,15 @@ public class TSaslNonblockingServer extends TServer { try { SelectionKey selectionKey = connection.registerSelector(ioSelector, SelectionKey.OP_READ); if (selectionKey.isValid()) { - NonblockingSaslHandler saslHandler = new NonblockingSaslHandler(selectionKey, connection, - saslServerFactory, saslProcessorFactory, inputProtocolFactory_, outputProtocolFactory_, - eventHandler_); + NonblockingSaslHandler saslHandler = + new NonblockingSaslHandler( + selectionKey, + connection, + saslServerFactory, + saslProcessorFactory, + inputProtocolFactory_, + outputProtocolFactory_, + eventHandler_); selectionKey.attach(saslHandler); } } catch (IOException e) { @@ -407,7 +409,7 @@ public class TSaslNonblockingServer extends TServer { * @return true if the incoming connection is accepted by network thread pool. */ boolean acceptNewConnection(TNonblockingTransport connection) { - return networkThreads.get((accepted ++) % networkThreads.size()).accept(connection); + return networkThreads.get((accepted++) % networkThreads.size()).accept(connection); } public void start() { @@ -441,12 +443,14 @@ public class TSaslNonblockingServer extends TServer { } public Args saslThreads(int authenticationThreads) { - this.saslThreads = authenticationThreads <= 0 ? DEFAULT_AUTHENTICATION_THREADS : authenticationThreads; + this.saslThreads = + authenticationThreads <= 0 ? DEFAULT_AUTHENTICATION_THREADS : authenticationThreads; return this; } public Args processingThreads(int processingThreads) { - this.processingThreads = processingThreads <= 0 ? DEFAULT_PROCESSING_THREADS : processingThreads; + this.processingThreads = + processingThreads <= 0 ? DEFAULT_PROCESSING_THREADS : processingThreads; return this; } @@ -463,8 +467,12 @@ public class TSaslNonblockingServer extends TServer { return this; } - public Args addSaslMechanism(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { + public Args addSaslMechanism( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { saslServerFactory.addSaslMechanism(mechanism, protocol, serverName, props, cbh); return this; } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TServer.java b/lib/java/src/main/java/org/apache/thrift/server/TServer.java index bac06b26b..1a4f1983e 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TServer.java @@ -26,10 +26,7 @@ import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TTransportFactory; -/** - * Generic interface for a Thrift server. - * - */ +/** Generic interface for a Thrift server. */ public abstract class TServer { public static class Args extends AbstractServerArgs<Args> { @@ -38,7 +35,7 @@ public abstract class TServer { } } - public static abstract class AbstractServerArgs<T extends AbstractServerArgs<T>> { + public abstract static class AbstractServerArgs<T extends AbstractServerArgs<T>> { final TServerTransport serverTransport; TProcessorFactory processorFactory; TTransportFactory inputTransportFactory = new TTransportFactory(); @@ -93,34 +90,22 @@ public abstract class TServer { } } - /** - * Core processor - */ + /** Core processor */ protected TProcessorFactory processorFactory_; - /** - * Server transport - */ + /** Server transport */ protected TServerTransport serverTransport_; - /** - * Input Transport Factory - */ + /** Input Transport Factory */ protected TTransportFactory inputTransportFactory_; - /** - * Output Transport Factory - */ + /** Output Transport Factory */ protected TTransportFactory outputTransportFactory_; - /** - * Input Protocol Factory - */ + /** Input Protocol Factory */ protected TProtocolFactory inputProtocolFactory_; - /** - * Output Protocol Factory - */ + /** Output Protocol Factory */ protected TProtocolFactory outputProtocolFactory_; private volatile boolean isServing; @@ -140,14 +125,12 @@ public abstract class TServer { outputProtocolFactory_ = args.outputProtocolFactory; } - /** - * The run method fires up the server and gets things going. - */ + /** The run method fires up the server and gets things going. */ public abstract void serve(); /** - * Stop the server. This is optional on a per-implementation basis. Not - * all servers are required to be cleanly stoppable. + * Stop the server. This is optional on a per-implementation basis. Not all servers are required + * to be cleanly stoppable. */ public void stop() {} diff --git a/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java b/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java index 3bd795986..4ff043a58 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java @@ -23,41 +23,27 @@ import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TTransport; /** - * Interface that can handle events from the server core. To - * use this you should subclass it and implement the methods that you care - * about. Your subclass can also store local data that you may care about, - * such as additional "arguments" to these methods (stored in the object - * instance's state). + * Interface that can handle events from the server core. To use this you should subclass it and + * implement the methods that you care about. Your subclass can also store local data that you may + * care about, such as additional "arguments" to these methods (stored in the object instance's + * state). * - * TODO: It seems this is a custom code entry point created for some resource management purpose in hive. - * But when looking into hive code, we see that the argments of TProtocol and TTransport are never used. - * We probably should remove these arguments from all the methods. + * <p>TODO: It seems this is a custom code entry point created for some resource management purpose + * in hive. But when looking into hive code, we see that the argments of TProtocol and TTransport + * are never used. We probably should remove these arguments from all the methods. */ public interface TServerEventHandler { - /** - * Called before the server begins. - */ + /** Called before the server begins. */ void preServe(); - /** - * Called when a new client has connected and is about to being processing. - */ - ServerContext createContext(TProtocol input, - TProtocol output); + /** Called when a new client has connected and is about to being processing. */ + ServerContext createContext(TProtocol input, TProtocol output); - /** - * Called when a client has finished request-handling to delete server - * context. - */ - void deleteContext(ServerContext serverContext, - TProtocol input, - TProtocol output); - - /** - * Called when a client is about to call the processor. - */ - void processContext(ServerContext serverContext, - TTransport inputTransport, TTransport outputTransport); + /** Called when a client has finished request-handling to delete server context. */ + void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output); + /** Called when a client is about to call the processor. */ + void processContext( + ServerContext serverContext, TTransport inputTransport, TTransport outputTransport); } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TServlet.java b/lib/java/src/main/java/org/apache/thrift/server/TServlet.java index c1ab9df55..0f233fac4 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TServlet.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TServlet.java @@ -6,12 +6,10 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Map; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -19,9 +17,7 @@ import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransport; -/** - * Servlet implementation class ThriftServer - */ +/** Servlet implementation class ThriftServer */ public class TServlet extends HttpServlet { private final TProcessor processor; @@ -32,10 +28,10 @@ public class TServlet extends HttpServlet { private final Collection<Map.Entry<String, String>> customHeaders; - /** - * @see HttpServlet#HttpServlet() - */ - public TServlet(TProcessor processor, TProtocolFactory inProtocolFactory, + /** @see HttpServlet#HttpServlet() */ + public TServlet( + TProcessor processor, + TProtocolFactory inProtocolFactory, TProtocolFactory outProtocolFactory) { super(); this.processor = processor; @@ -44,17 +40,12 @@ public class TServlet extends HttpServlet { this.customHeaders = new ArrayList<Map.Entry<String, String>>(); } - /** - * @see HttpServlet#HttpServlet() - */ + /** @see HttpServlet#HttpServlet() */ public TServlet(TProcessor processor, TProtocolFactory protocolFactory) { this(processor, protocolFactory, protocolFactory); } - /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -87,29 +78,27 @@ public class TServlet extends HttpServlet { } } - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void addCustomHeader(final String key, final String value) { - this.customHeaders.add(new Map.Entry<String, String>() { - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - public String setValue(String value) { - return null; - } - }); + this.customHeaders.add( + new Map.Entry<String, String>() { + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + public String setValue(String value) { + return null; + } + }); } public void setCustomHeaders(Collection<Map.Entry<String, String>> headers) { diff --git a/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java b/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java index 70cc3d776..3530d6d8c 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java @@ -27,10 +27,7 @@ import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Simple singlethreaded server for testing. - * - */ +/** Simple singlethreaded server for testing. */ public class TSimpleServer extends TServer { private static final Logger LOGGER = LoggerFactory.getLogger(TSimpleServer.class.getName()); @@ -104,7 +101,6 @@ public class TSimpleServer extends TServer { if (outputTransport != null) { outputTransport.close(); } - } setServing(false); } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java b/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java index e19041568..cc5843869 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java @@ -27,7 +27,6 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -38,8 +37,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Server which uses Java's built in ThreadPool management to spawn off - * a worker pool that deals with client connections in blocking way. + * Server which uses Java's built in ThreadPool management to spawn off a worker pool that deals + * with client connections in blocking way. */ public class TThreadPoolServer extends TServer { private static final Logger LOGGER = LoggerFactory.getLogger(TThreadPoolServer.class); @@ -94,19 +93,26 @@ public class TThreadPoolServer extends TServer { stopTimeoutUnit = args.stopTimeoutUnit; stopTimeoutVal = args.stopTimeoutVal; - executorService_ = args.executorService != null ? - args.executorService : createDefaultExecutorService(args); + executorService_ = + args.executorService != null ? args.executorService : createDefaultExecutorService(args); } private static ExecutorService createDefaultExecutorService(Args args) { - return new ThreadPoolExecutor(args.minWorkerThreads, args.maxWorkerThreads, 60L, TimeUnit.SECONDS, - new SynchronousQueue<>(), new ThreadFactory() { + return new ThreadPoolExecutor( + args.minWorkerThreads, + args.maxWorkerThreads, + 60L, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + new ThreadFactory() { final AtomicLong count = new AtomicLong(); + @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); - thread.setName(String.format("TThreadPoolServer WorkerProcess-%d", count.getAndIncrement())); + thread.setName( + String.format("TThreadPoolServer WorkerProcess-%d", count.getAndIncrement())); return thread; } }); @@ -157,7 +163,8 @@ public class TThreadPoolServer extends TServer { executorService_.execute(new WorkerProcess(client)); } catch (RejectedExecutionException ree) { if (!stopped_) { - LOGGER.warn("ThreadPool is saturated with incoming requests. Closing latest connection."); + LOGGER.warn( + "ThreadPool is saturated with incoming requests. Closing latest connection."); } client.close(); } @@ -195,9 +202,7 @@ public class TThreadPoolServer extends TServer { private class WorkerProcess implements Runnable { - /** - * Client that this services. - */ + /** Client that this services. */ private TTransport client_; /** @@ -209,9 +214,7 @@ public class TThreadPoolServer extends TServer { client_ = client; } - /** - * Loops on processing a client forever - */ + /** Loops on processing a client forever */ public void run() { TProcessor processor = null; TTransport inputTransport = null; @@ -257,7 +260,10 @@ public class TThreadPoolServer extends TServer { // Ignore err-logging all transport-level/type exceptions if (!isIgnorableException(x)) { // Log the exception at error level and continue - LOGGER.error((x instanceof TException ? "Thrift " : "") + "Error occurred during processing of message.", x); + LOGGER.error( + (x instanceof TException ? "Thrift " : "") + + "Error occurred during processing of message.", + x); } } finally { if (eventHandler.isPresent()) { @@ -285,7 +291,7 @@ public class TThreadPoolServer extends TServer { } if (tTransportException != null) { - switch(tTransportException.getType()) { + switch (tTransportException.getType()) { case TTransportException.END_OF_FILE: case TTransportException.TIMED_OUT: return true; diff --git a/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java b/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java index 095aacbc5..0a4d8575f 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java @@ -19,12 +19,6 @@ package org.apache.thrift.server; -import org.apache.thrift.transport.TNonblockingServerTransport; -import org.apache.thrift.transport.TNonblockingTransport; -import org.apache.thrift.transport.TTransportException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; @@ -44,58 +38,61 @@ import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import org.apache.thrift.transport.TNonblockingServerTransport; +import org.apache.thrift.transport.TNonblockingTransport; +import org.apache.thrift.transport.TTransportException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * A Half-Sync/Half-Async server with a separate pool of threads to handle - * non-blocking I/O. Accepts are handled on a single thread, and a configurable - * number of nonblocking selector threads manage reading and writing of client - * connections. A synchronous worker thread pool handles processing of requests. + * A Half-Sync/Half-Async server with a separate pool of threads to handle non-blocking I/O. Accepts + * are handled on a single thread, and a configurable number of nonblocking selector threads manage + * reading and writing of client connections. A synchronous worker thread pool handles processing of + * requests. * - * Performs better than TNonblockingServer/THsHaServer in multi-core - * environments when the the bottleneck is CPU on the single selector thread - * handling I/O. In addition, because the accept handling is decoupled from - * reads/writes and invocation, the server has better ability to handle back- - * pressure from new connections (e.g. stop accepting when busy). + * <p>Performs better than TNonblockingServer/THsHaServer in multi-core environments when the the + * bottleneck is CPU on the single selector thread handling I/O. In addition, because the accept + * handling is decoupled from reads/writes and invocation, the server has better ability to handle + * back- pressure from new connections (e.g. stop accepting when busy). * - * Like TNonblockingServer, it relies on the use of TFramedTransport. + * <p>Like TNonblockingServer, it relies on the use of TFramedTransport. */ public class TThreadedSelectorServer extends AbstractNonblockingServer { - private static final Logger LOGGER = LoggerFactory.getLogger(TThreadedSelectorServer.class.getName()); + private static final Logger LOGGER = + LoggerFactory.getLogger(TThreadedSelectorServer.class.getName()); public static class Args extends AbstractNonblockingServerArgs<Args> { /** The number of threads for selecting on already-accepted connections */ public int selectorThreads = 2; /** - * The size of the executor service (if none is specified) that will handle - * invocations. This may be set to 0, in which case invocations will be - * handled directly on the selector threads (as is in TNonblockingServer) + * The size of the executor service (if none is specified) that will handle invocations. This + * may be set to 0, in which case invocations will be handled directly on the selector threads + * (as is in TNonblockingServer) */ private int workerThreads = 5; /** Time to wait for server to stop gracefully */ private int stopTimeoutVal = 60; + private TimeUnit stopTimeoutUnit = TimeUnit.SECONDS; /** The ExecutorService for handling dispatched requests */ private ExecutorService executorService = null; /** - * The size of the blocking queue per selector thread for passing accepted - * connections to the selector thread + * The size of the blocking queue per selector thread for passing accepted connections to the + * selector thread */ private int acceptQueueSizePerThread = 4; - /** - * Determines the strategy for handling new accepted connections. - */ + /** Determines the strategy for handling new accepted connections. */ public static enum AcceptPolicy { /** - * Require accepted connection registration to be handled by the executor. - * If the worker pool is saturated, further accepts will be closed - * immediately. Slightly increases latency due to an extra scheduling. + * Require accepted connection registration to be handled by the executor. If the worker pool + * is saturated, further accepts will be closed immediately. Slightly increases latency due to + * an extra scheduling. */ FAIR_ACCEPT, /** - * Handle the accepts as fast as possible, disregarding the status of the - * executor service. + * Handle the accepts as fast as possible, disregarding the status of the executor service. */ FAST_ACCEPT } @@ -195,9 +192,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { private final Args args; - /** - * Create the server with the specified Args configuration - */ + /** Create the server with the specified Args configuration */ public TThreadedSelectorServer(Args args) { super(args); args.validate(); @@ -208,8 +203,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Start the accept and selector threads running to deal with clients. * - * @return true if everything went ok, false if we couldn't start for some - * reason. + * @return true if everything went ok, false if we couldn't start for some reason. */ @Override protected boolean startThreads() { @@ -217,8 +211,10 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { for (int i = 0; i < args.selectorThreads; ++i) { selectorThreads.add(new SelectorThread(args.acceptQueueSizePerThread)); } - acceptThread = new AcceptThread((TNonblockingServerTransport) serverTransport_, - createSelectorThreadLoadBalancer(selectorThreads)); + acceptThread = + new AcceptThread( + (TNonblockingServerTransport) serverTransport_, + createSelectorThreadLoadBalancer(selectorThreads)); for (SelectorThread thread : selectorThreads) { thread.start(); } @@ -230,9 +226,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * Joins the accept and selector threads and shuts down the executor service. - */ + /** Joins the accept and selector threads and shuts down the executor service. */ @Override protected void waitForShutdown() { try { @@ -252,9 +246,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * Stop serving and shut everything down. - */ + /** Stop serving and shut everything down. */ @Override public void stop() { stopped_ = true; @@ -267,8 +259,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } if (selectorThreads != null) { for (SelectorThread thread : selectorThreads) { - if (thread != null) - thread.wakeupSelector(); + if (thread != null) thread.wakeupSelector(); } } } @@ -296,9 +287,9 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * We override the standard invoke method here to queue the invocation for - * invoker service instead of immediately invoking. If there is no thread - * pool, handle the invocation inline on this thread + * We override the standard invoke method here to queue the invocation for invoker service instead + * of immediately invoking. If there is no thread pool, handle the invocation inline on this + * thread */ @Override protected boolean requestInvoke(FrameBuffer frameBuffer) { @@ -322,9 +313,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { return new Invocation(frameBuffer); } - /** - * Helper to create the invoker if one is not specified - */ + /** Helper to create the invoker if one is not specified */ protected static ExecutorService createDefaultExecutor(Args options) { return (options.workerThreads > 0) ? Executors.newFixedThreadPool(options.workerThreads) : null; } @@ -338,8 +327,8 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * The thread that selects on the server transport (listen socket) and accepts - * new connections to hand off to the IO selector threads + * The thread that selects on the server transport (listen socket) and accepts new connections to + * hand off to the IO selector threads */ protected class AcceptThread extends Thread { @@ -354,8 +343,9 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { * * @throws IOException */ - public AcceptThread(TNonblockingServerTransport serverTransport, - SelectorThreadLoadBalancer threadChooser) throws IOException { + public AcceptThread( + TNonblockingServerTransport serverTransport, SelectorThreadLoadBalancer threadChooser) + throws IOException { this.serverTransport = serverTransport; this.threadChooser = threadChooser; this.acceptSelector = SelectorProvider.provider().openSelector(); @@ -363,9 +353,9 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * The work loop. Selects on the server transport and accepts. If there was - * a server transport that had blocking accepts, and returned on blocking - * client transports, that should be used instead + * The work loop. Selects on the server transport and accepts. If there was a server transport + * that had blocking accepts, and returned on blocking client transports, that should be used + * instead */ public void run() { try { @@ -389,16 +379,14 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * If the selector is blocked, wake it up. - */ + /** If the selector is blocked, wake it up. */ public void wakeupSelector() { acceptSelector.wakeup(); } /** - * Select and process IO events appropriately: If there are connections to - * be accepted, accept them. + * Select and process IO events appropriately: If there are connections to be accepted, accept + * them. */ private void select() { try { @@ -427,9 +415,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * Accept a new connection. - */ + /** Accept a new connection. */ private void handleAccept() { final TNonblockingTransport client = doAccept(); if (client != null) { @@ -441,11 +427,12 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } else { // FAIR_ACCEPT try { - invoker.submit(new Runnable() { - public void run() { - doAddAccept(targetThread, client); - } - }); + invoker.submit( + new Runnable() { + public void run() { + doAddAccept(targetThread, client); + } + }); } catch (RejectedExecutionException rx) { LOGGER.warn("ExecutorService rejected accept registration!", rx); // close immediately @@ -472,10 +459,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } // AcceptThread - /** - * The SelectorThread(s) will be doing all the selecting on accepted active - * connections. - */ + /** The SelectorThread(s) will be doing all the selecting on accepted active connections. */ protected class SelectorThread extends AbstractSelectThread { // Accepted connections added by the accept thread. @@ -487,8 +471,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with an unbounded queue for incoming accepts. * - * @throws IOException - * if a selector cannot be created + * @throws IOException if a selector cannot be created */ public SelectorThread() throws IOException { this(new LinkedBlockingQueue<TNonblockingTransport>()); @@ -497,8 +480,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with an bounded queue for incoming accepts. * - * @throws IOException - * if a selector cannot be created + * @throws IOException if a selector cannot be created */ public SelectorThread(int maxPendingAccepts) throws IOException { this(createDefaultAcceptQueue(maxPendingAccepts)); @@ -507,22 +489,19 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with a specified queue for connections. * - * @param acceptedQueue - * The BlockingQueue implementation for holding incoming accepted - * connections. - * @throws IOException - * if a selector cannot be created. + * @param acceptedQueue The BlockingQueue implementation for holding incoming accepted + * connections. + * @throws IOException if a selector cannot be created. */ public SelectorThread(BlockingQueue<TNonblockingTransport> acceptedQueue) throws IOException { this.acceptedQueue = acceptedQueue; } /** - * Hands off an accepted connection to be handled by this thread. This - * method will block if the queue for new connections is at capacity. + * Hands off an accepted connection to be handled by this thread. This method will block if the + * queue for new connections is at capacity. * - * @param accepted - * The connection that has been accepted. + * @param accepted The connection that has been accepted. * @return true if the connection has been successfully added. */ public boolean addAcceptedConnection(TNonblockingTransport accepted) { @@ -537,8 +516,8 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * The work loop. Handles selecting (read/write IO), dispatching, and - * managing the selection preferences of all existing connections. + * The work loop. Handles selecting (read/write IO), dispatching, and managing the selection + * preferences of all existing connections. */ public void run() { try { @@ -564,10 +543,10 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * Select and process IO events appropriately: If there are existing - * connections with data waiting to be read, read it, buffering until a - * whole frame has been read. If there are any pending responses, buffer - * them until their target client is available, and then send the data. + * Select and process IO events appropriately: If there are existing connections with data + * waiting to be read, read it, buffering until a whole frame has been read. If there are any + * pending responses, buffer them until their target client is available, and then send the + * data. */ private void select() { try { @@ -602,8 +581,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * Do select and judge epoll bug happen. - * See : https://issues.apache.org/jira/browse/THRIFT-4251 + * Do select and judge epoll bug happen. See : https://issues.apache.org/jira/browse/THRIFT-4251 */ private void doSelect() throws IOException { long beforeSelect = System.currentTimeMillis(); @@ -620,12 +598,12 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { if (selectedTime >= MONITOR_PERIOD) { jvmBug = 0; } else if (jvmBug > SELECTOR_AUTO_REBUILD_THRESHOLD) { - LOGGER.warn("In {} ms happen {} times jvm bug; rebuilding selector.", MONITOR_PERIOD, jvmBug); + LOGGER.warn( + "In {} ms happen {} times jvm bug; rebuilding selector.", MONITOR_PERIOD, jvmBug); rebuildSelector(); selector.selectNow(); jvmBug = 0; } - } /** @@ -646,8 +624,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } for (SelectionKey key : oldSelector.selectedKeys()) { - if (!key.isValid() && key.readyOps() == 0) - continue; + if (!key.isValid() && key.readyOps() == 0) continue; SelectableChannel channel = key.channel(); Object attachment = key.attachment(); @@ -660,7 +637,6 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } catch (ClosedChannelException e) { LOGGER.error("Register new selector key error.", e); } - } selector = newSelector; @@ -683,12 +659,14 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - protected FrameBuffer createFrameBuffer(final TNonblockingTransport trans, + protected FrameBuffer createFrameBuffer( + final TNonblockingTransport trans, final SelectionKey selectionKey, - final AbstractSelectThread selectThread) throws TTransportException { - return processorFactory_.isAsyncProcessor() ? - new AsyncFrameBuffer(trans, selectionKey, selectThread) : - new FrameBuffer(trans, selectionKey, selectThread); + final AbstractSelectThread selectThread) + throws TTransportException { + return processorFactory_.isAsyncProcessor() + ? new AsyncFrameBuffer(trans, selectionKey, selectThread) + : new FrameBuffer(trans, selectionKey, selectThread); } private void registerAccepted(TNonblockingTransport accepted) { @@ -710,17 +688,15 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } // SelectorThread /** - * Creates a SelectorThreadLoadBalancer to be used by the accept thread for - * assigning newly accepted connections across the threads. + * Creates a SelectorThreadLoadBalancer to be used by the accept thread for assigning newly + * accepted connections across the threads. */ - protected SelectorThreadLoadBalancer createSelectorThreadLoadBalancer(Collection<? extends SelectorThread> threads) { + protected SelectorThreadLoadBalancer createSelectorThreadLoadBalancer( + Collection<? extends SelectorThread> threads) { return new SelectorThreadLoadBalancer(threads); } - /** - * A round robin load balancer for choosing selector threads for new - * connections. - */ + /** A round robin load balancer for choosing selector threads for new connections. */ protected static class SelectorThreadLoadBalancer { private final Collection<? extends SelectorThread> threads; private Iterator<? extends SelectorThread> nextThreadIterator; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java index b355d11ca..b1c815f88 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java @@ -21,11 +21,10 @@ package org.apache.thrift.transport; import java.util.Arrays; /** - * Helper class that wraps a byte[] so that it can expand and be reused. Users - * should call resizeIfNecessary to make sure the buffer has suitable capacity, - * and then use the array as needed. Note that the internal array will grow at a - * rate slightly faster than the requested capacity with the (untested) - * objective of avoiding expensive buffer allocations and copies. + * Helper class that wraps a byte[] so that it can expand and be reused. Users should call + * resizeIfNecessary to make sure the buffer has suitable capacity, and then use the array as + * needed. Note that the internal array will grow at a rate slightly faster than the requested + * capacity with the (untested) objective of avoiding expensive buffer allocations and copies. */ public class AutoExpandingBuffer { private byte[] array; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java index 6fd4075b9..d59c657db 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java @@ -20,9 +20,7 @@ package org.apache.thrift.transport; import org.apache.thrift.TConfiguration; -/** - * TTransport for reading from an AutoExpandingBuffer. - */ +/** TTransport for reading from an AutoExpandingBuffer. */ public class AutoExpandingBufferReadTransport extends TEndpointTransport { private final AutoExpandingBuffer buf; @@ -30,7 +28,8 @@ public class AutoExpandingBufferReadTransport extends TEndpointTransport { private int pos = 0; private int limit = 0; - public AutoExpandingBufferReadTransport(TConfiguration config, int initialCapacity) throws TTransportException { + public AutoExpandingBufferReadTransport(TConfiguration config, int initialCapacity) + throws TTransportException { super(config); this.buf = new AutoExpandingBuffer(initialCapacity); } @@ -46,7 +45,9 @@ public class AutoExpandingBufferReadTransport extends TEndpointTransport { public void close() {} @Override - public boolean isOpen() { return true; } + public boolean isOpen() { + return true; + } @Override public void open() throws TTransportException {} @@ -54,7 +55,7 @@ public class AutoExpandingBufferReadTransport extends TEndpointTransport { @Override public final int read(byte[] target, int off, int len) throws TTransportException { int amtToRead = Math.min(len, getBytesRemainingInBuffer()); - if(amtToRead > 0){ + if (amtToRead > 0) { System.arraycopy(buf.array(), pos, target, off, amtToRead); consumeBuffer(amtToRead); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java index 84b28b4c4..741d629ae 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java @@ -20,9 +20,7 @@ package org.apache.thrift.transport; import org.apache.thrift.TConfiguration; -/** - * TTransport for writing to an AutoExpandingBuffer. - */ +/** TTransport for writing to an AutoExpandingBuffer. */ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport { private final AutoExpandingBuffer buf; @@ -31,17 +29,18 @@ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport /** * Constructor. + * * @param config the configuration to use. Currently used for defining the maximum message size. * @param initialCapacity the initial capacity of the buffer - * @param frontReserve space, if any, to reserve at the beginning such - * that the first write is after this reserve. - * This allows framed transport to reserve space - * for the frame buffer length. + * @param frontReserve space, if any, to reserve at the beginning such that the first write is + * after this reserve. This allows framed transport to reserve space for the frame buffer + * length. * @throws IllegalArgumentException if initialCapacity is less than one * @throws IllegalArgumentException if frontReserve is less than zero * @throws IllegalArgumentException if frontReserve is greater than initialCapacity */ - public AutoExpandingBufferWriteTransport(TConfiguration config, int initialCapacity, int frontReserve) throws TTransportException { + public AutoExpandingBufferWriteTransport( + TConfiguration config, int initialCapacity, int frontReserve) throws TTransportException { super(config); if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity"); @@ -58,7 +57,9 @@ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport public void close() {} @Override - public boolean isOpen() {return true;} + public boolean isOpen() { + return true; + } @Override public void open() throws TTransportException {} @@ -79,9 +80,7 @@ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport return buf; } - /** - * @return length of the buffer, including any front reserve - */ + /** @return length of the buffer, including any front reserve */ public int getLength() { return pos; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java b/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java index 72d10c53d..fa296e7c4 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java @@ -1,14 +1,11 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; +import org.apache.thrift.TConfiguration; -/** - * ByteBuffer-backed implementation of TTransport. - */ +/** ByteBuffer-backed implementation of TTransport. */ public final class TByteBuffer extends TEndpointTransport { private final ByteBuffer byteBuffer; @@ -30,12 +27,10 @@ public final class TByteBuffer extends TEndpointTransport { } @Override - public void open() { - } + public void open() {} @Override - public void close() { - } + public void close() {} @Override public int read(byte[] buf, int off, int len) throws TTransportException { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java b/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java index b5ae6eff4..52a5cf709 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport; -/** - * End of file, especially, the underlying socket is closed. - */ +/** End of file, especially, the underlying socket is closed. */ public class TEOFException extends TTransportException { public TEOFException(String message) { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java index f33b8b72d..72bf95391 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java @@ -18,88 +18,93 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.util.Objects; +import org.apache.thrift.TConfiguration; -public abstract class TEndpointTransport extends TTransport{ - - protected long getMaxMessageSize() { return getConfiguration().getMaxMessageSize(); } - - public int getMaxFrameSize() { return getConfiguration().getMaxFrameSize(); } +public abstract class TEndpointTransport extends TTransport { - public void setMaxFrameSize(int maxFrameSize) { getConfiguration().setMaxFrameSize(maxFrameSize); } + protected long getMaxMessageSize() { + return getConfiguration().getMaxMessageSize(); + } - protected long knownMessageSize; - protected long remainingMessageSize; + public int getMaxFrameSize() { + return getConfiguration().getMaxFrameSize(); + } - private TConfiguration _configuration; + public void setMaxFrameSize(int maxFrameSize) { + getConfiguration().setMaxFrameSize(maxFrameSize); + } - public TConfiguration getConfiguration() { - return _configuration; - } + protected long knownMessageSize; + protected long remainingMessageSize; - public TEndpointTransport(TConfiguration config) throws TTransportException { - _configuration = Objects.isNull(config) ? new TConfiguration() : config; + private TConfiguration _configuration; - resetConsumedMessageSize(-1); - } + public TConfiguration getConfiguration() { + return _configuration; + } - /** - * Resets RemainingMessageSize to the configured maximum - * @param newSize - */ - protected void resetConsumedMessageSize(long newSize) throws TTransportException { - // full reset - if (newSize < 0) - { - knownMessageSize = getMaxMessageSize(); - remainingMessageSize = getMaxMessageSize(); - return; - } - - // update only: message size can shrink, but not grow - if (newSize > knownMessageSize) - throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); - - knownMessageSize = newSize; - remainingMessageSize = newSize; - } + public TEndpointTransport(TConfiguration config) throws TTransportException { + _configuration = Objects.isNull(config) ? new TConfiguration() : config; - /** - * Updates RemainingMessageSize to reflect then known real message size (e.g. framed transport). - * Will throw if we already consumed too many bytes or if the new size is larger than allowed. - * @param size - */ - public void updateKnownMessageSize(long size) throws TTransportException { - long consumed = knownMessageSize - remainingMessageSize; - resetConsumedMessageSize(size == 0 ? -1 : size); - countConsumedMessageBytes(consumed); - } + resetConsumedMessageSize(-1); + } - /** - * Throws if there are not enough bytes in the input stream to satisfy a read of numBytes bytes of data - * @param numBytes - */ - public void checkReadBytesAvailable(long numBytes) throws TTransportException { - if (remainingMessageSize < numBytes) - throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); + /** + * Resets RemainingMessageSize to the configured maximum + * + * @param newSize + */ + protected void resetConsumedMessageSize(long newSize) throws TTransportException { + // full reset + if (newSize < 0) { + knownMessageSize = getMaxMessageSize(); + remainingMessageSize = getMaxMessageSize(); + return; } - /** - * Consumes numBytes from the RemainingMessageSize. - * @param numBytes - */ - protected void countConsumedMessageBytes(long numBytes) throws TTransportException { - if (remainingMessageSize >= numBytes) - { - remainingMessageSize -= numBytes; - } - else - { - remainingMessageSize = 0; - throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); - } + // update only: message size can shrink, but not grow + if (newSize > knownMessageSize) + throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); + + knownMessageSize = newSize; + remainingMessageSize = newSize; + } + + /** + * Updates RemainingMessageSize to reflect then known real message size (e.g. framed transport). + * Will throw if we already consumed too many bytes or if the new size is larger than allowed. + * + * @param size + */ + public void updateKnownMessageSize(long size) throws TTransportException { + long consumed = knownMessageSize - remainingMessageSize; + resetConsumedMessageSize(size == 0 ? -1 : size); + countConsumedMessageBytes(consumed); + } + + /** + * Throws if there are not enough bytes in the input stream to satisfy a read of numBytes bytes of + * data + * + * @param numBytes + */ + public void checkReadBytesAvailable(long numBytes) throws TTransportException { + if (remainingMessageSize < numBytes) + throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); + } + + /** + * Consumes numBytes from the RemainingMessageSize. + * + * @param numBytes + */ + protected void countConsumedMessageBytes(long numBytes) throws TTransportException { + if (remainingMessageSize >= numBytes) { + remainingMessageSize -= numBytes; + } else { + remainingMessageSize = 0; + throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); } - + } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java b/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java index e36a5f384..e447aca0f 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java @@ -19,14 +19,14 @@ package org.apache.thrift.transport; -import org.apache.thrift.TProcessor; import org.apache.thrift.TException; +import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; /** - * FileProcessor: helps in processing files generated by TFileTransport. - * Port of original cpp implementation + * FileProcessor: helps in processing files generated by TFileTransport. Port of original cpp + * implementation */ public class TFileProcessor { @@ -36,20 +36,23 @@ public class TFileProcessor { private TFileTransport inputTransport_; private TTransport outputTransport_; - public TFileProcessor(TProcessor processor, TProtocolFactory protocolFactory, - TFileTransport inputTransport, - TTransport outputTransport) { + public TFileProcessor( + TProcessor processor, + TProtocolFactory protocolFactory, + TFileTransport inputTransport, + TTransport outputTransport) { processor_ = processor; inputProtocolFactory_ = outputProtocolFactory_ = protocolFactory; inputTransport_ = inputTransport; outputTransport_ = outputTransport; } - public TFileProcessor(TProcessor processor, - TProtocolFactory inputProtocolFactory, - TProtocolFactory outputProtocolFactory, - TFileTransport inputTransport, - TTransport outputTransport) { + public TFileProcessor( + TProcessor processor, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + TFileTransport inputTransport, + TTransport outputTransport) { processor_ = processor; inputProtocolFactory_ = inputProtocolFactory; outputProtocolFactory_ = outputProtocolFactory; @@ -71,8 +74,7 @@ public class TFileProcessor { } catch (TTransportException e) { // if we are processing the last chunk - we could have just hit EOF // on EOF - trap the error and stop processing. - if(e.getType() != TTransportException.END_OF_FILE) - throw e; + if (e.getType() != TTransportException.END_OF_FILE) throw e; else { return; } @@ -81,20 +83,18 @@ public class TFileProcessor { /** * Process from start to last chunk both inclusive where chunks begin from 0 - + * * @param startChunkNum first chunk to be processed * @param endChunkNum last chunk to be processed * @throws TException if endChunkNum is less than startChunkNum. */ public void processChunk(int startChunkNum, int endChunkNum) throws TException { int numChunks = inputTransport_.getNumChunks(); - if(endChunkNum < 0) - endChunkNum += numChunks; + if (endChunkNum < 0) endChunkNum += numChunks; - if(startChunkNum < 0) - startChunkNum += numChunks; + if (startChunkNum < 0) startChunkNum += numChunks; - if(endChunkNum < startChunkNum) + if (endChunkNum < startChunkNum) throw new TException("endChunkNum " + endChunkNum + " is less than " + startChunkNum); inputTransport_.seekToChunk(startChunkNum); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java index 61b68d279..713d52103 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java @@ -21,22 +21,21 @@ package org.apache.thrift.transport; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; import java.util.Random; - import org.apache.thrift.TConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * FileTransport implementation of the TTransport interface. - * Currently this is a straightforward port of the cpp implementation + * FileTransport implementation of the TTransport interface. Currently this is a straightforward + * port of the cpp implementation * - * It may make better sense to provide a basic stream access on top of the framed file format - * The FileTransport can then be a user of this framed file format with some additional logic - * for chunking. + * <p>It may make better sense to provide a basic stream access on top of the framed file format The + * FileTransport can then be a user of this framed file format with some additional logic for + * chunking. */ public class TFileTransport extends TTransport { @@ -46,15 +45,16 @@ public class TFileTransport extends TTransport { public void trunc() { pos = count = 0; } + public TruncableBufferedInputStream(InputStream in) { super(in); } + public TruncableBufferedInputStream(InputStream in, int size) { super(in, size); } } - public static class Event { private byte[] buf_; private int nread_; @@ -70,64 +70,81 @@ public class TFileTransport extends TTransport { nread_ = navailable_ = 0; } - public byte[] getBuf() { return buf_;} - public int getSize() { return buf_.length; } + public byte[] getBuf() { + return buf_; + } + public int getSize() { + return buf_.length; + } - public void setAvailable(int sz) { nread_ = 0; navailable_=sz;} - public int getRemaining() { return (navailable_ - nread_); } + public void setAvailable(int sz) { + nread_ = 0; + navailable_ = sz; + } + + public int getRemaining() { + return (navailable_ - nread_); + } public int emit(byte[] buf, int offset, int ndesired) { - if((ndesired == 0) || (ndesired > getRemaining())) - ndesired = getRemaining(); + if ((ndesired == 0) || (ndesired > getRemaining())) ndesired = getRemaining(); - if(ndesired <= 0) - return (ndesired); + if (ndesired <= 0) return (ndesired); System.arraycopy(buf_, nread_, buf, offset, ndesired); nread_ += ndesired; - return(ndesired); + return (ndesired); } } - public static class ChunkState { - /** - * Chunk Size. Must be same across all implementations - */ + public static class ChunkState { + /** Chunk Size. Must be same across all implementations */ public static final int DEFAULT_CHUNK_SIZE = 16 * 1024 * 1024; private int chunk_size_ = DEFAULT_CHUNK_SIZE; private long offset_ = 0; public ChunkState() {} - public ChunkState(int chunk_size) { chunk_size_ = chunk_size; } - public void skip(int size) {offset_ += size; } - public void seek(long offset) {offset_ = offset;} + public ChunkState(int chunk_size) { + chunk_size_ = chunk_size; + } - public int getChunkSize() { return chunk_size_;} - public int getChunkNum() { return ((int)(offset_/chunk_size_));} - public int getRemaining() { return (chunk_size_ - ((int)(offset_ % chunk_size_)));} - public long getOffset() { return (offset_);} + public void skip(int size) { + offset_ += size; + } + + public void seek(long offset) { + offset_ = offset; + } + + public int getChunkSize() { + return chunk_size_; + } + + public int getChunkNum() { + return ((int) (offset_ / chunk_size_)); + } + + public int getRemaining() { + return (chunk_size_ - ((int) (offset_ % chunk_size_))); + } + + public long getOffset() { + return (offset_); + } } public enum TailPolicy { - NOWAIT(0, 0), - WAIT_FOREVER(500, -1); + WAIT_FOREVER(500, -1); - /** - * Time in milliseconds to sleep before next read - * If 0, no sleep - */ + /** Time in milliseconds to sleep before next read If 0, no sleep */ public final int timeout_; - /** - * Number of retries before giving up - * if 0, no retries - * if -1, retry forever - */ + /** Number of retries before giving up if 0, no retries if -1, retry forever */ public final int retries_; /** @@ -136,48 +153,31 @@ public class TFileTransport extends TTransport { * @param timeout sleep time for this particular policy * @param retries number of retries */ - TailPolicy(int timeout, int retries) { timeout_ = timeout; retries_ = retries; } } - /** - * Current tailing policy - */ + /** Current tailing policy */ TailPolicy currentPolicy_ = TailPolicy.NOWAIT; - - /** - * Underlying file being read - */ + /** Underlying file being read */ protected TSeekableFile inputFile_ = null; - /** - * Underlying outputStream - */ + /** Underlying outputStream */ protected OutputStream outputStream_ = null; - - /** - * Event currently read in - */ + /** Event currently read in */ Event currentEvent_ = null; - /** - * InputStream currently being used for reading - */ + /** InputStream currently being used for reading */ InputStream inputStream_ = null; - /** - * current Chunk state - */ + /** current Chunk state */ ChunkState cs = null; - /** - * is read only? - */ + /** is read only? */ private boolean readOnly_ = false; /** @@ -201,7 +201,6 @@ public class TFileTransport extends TTransport { return (old); } - /** * Initialize read input stream * @@ -210,8 +209,8 @@ public class TFileTransport extends TTransport { private InputStream createInputStream() throws TTransportException { InputStream is; try { - if(inputStream_ != null) { - ((TruncableBufferedInputStream)inputStream_).trunc(); + if (inputStream_ != null) { + ((TruncableBufferedInputStream) inputStream_).trunc(); is = inputStream_; } else { is = new TruncableBufferedInputStream(inputFile_.getInputStream()); @@ -219,7 +218,7 @@ public class TFileTransport extends TTransport { } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } - return(is); + return (is); } /** @@ -229,18 +228,17 @@ public class TFileTransport extends TTransport { * @param buf Buffer to read into * @param off Offset in buffer to read into * @param len Number of bytes to read - * @param tp policy to use if we hit EOF - * + * @param tp policy to use if we hit EOF * @return number of bytes read */ - private int tailRead(InputStream is, byte[] buf, - int off, int len, TailPolicy tp) throws TTransportException { + private int tailRead(InputStream is, byte[] buf, int off, int len, TailPolicy tp) + throws TTransportException { int orig_len = len; try { int retries = 0; - while(len > 0) { + while (len > 0) { int cnt = is.read(buf, off, len); - if(cnt > 0) { + if (cnt > 0) { off += cnt; len -= cnt; retries = 0; @@ -249,40 +247,40 @@ public class TFileTransport extends TTransport { // EOF retries++; - if((tp.retries_ != -1) && tp.retries_ < retries) - return (orig_len - len); + if ((tp.retries_ != -1) && tp.retries_ < retries) return (orig_len - len); - if(tp.timeout_ > 0) { - try {Thread.sleep(tp.timeout_);} catch(InterruptedException e) {} + if (tp.timeout_ > 0) { + try { + Thread.sleep(tp.timeout_); + } catch (InterruptedException e) { + } } } else { // either non-zero or -1 is what the contract says! - throw new - TTransportException("Unexpected return from InputStream.read = " - + cnt); + throw new TTransportException("Unexpected return from InputStream.read = " + cnt); } } } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } - return(orig_len - len); + return (orig_len - len); } /** * Event is corrupted. Do recovery * - * @return true if recovery could be performed and we can read more data - * false is returned only when nothing more can be read + * @return true if recovery could be performed and we can read more data false is returned only + * when nothing more can be read */ private boolean performRecovery() throws TTransportException { int numChunks = getNumChunks(); int curChunk = cs.getChunkNum(); - if(curChunk >= (numChunks-1)) { + if (curChunk >= (numChunks - 1)) { return false; } - seekToChunk(curChunk+1); + seekToChunk(curChunk + 1); return true; } @@ -301,27 +299,27 @@ public class TFileTransport extends TTransport { do { // corner case. read to end of chunk nrequested = cs.getRemaining(); - if(nrequested < 4) { + if (nrequested < 4) { nread = tailRead(inputStream_, ebytes, 0, nrequested, currentPolicy_); - if(nread != nrequested) { - return(false); + if (nread != nrequested) { + return (false); } } // assuming serialized on little endian machine nread = tailRead(inputStream_, ebytes, 0, 4, currentPolicy_); - if(nread != 4) { - return(false); + if (nread != 4) { + return (false); } - esize=0; - for(int i=3; i>=0; i--) { - int val = (0x000000ff & (int)ebytes[i]); - esize |= (val << (i*8)); + esize = 0; + for (int i = 3; i >= 0; i--) { + int val = (0x000000ff & (int) ebytes[i]); + esize |= (val << (i * 8)); } // check if event is corrupted and do recovery as required - if(esize > cs.getRemaining()) { + if (esize > cs.getRemaining()) { throw new TTransportException("FileTransport error: bad event size"); /* if(performRecovery()) { @@ -334,17 +332,16 @@ public class TFileTransport extends TTransport { } while (esize == 0); // reset existing event or get a larger one - if(currentEvent_.getSize() < esize) - currentEvent_ = new Event(new byte [esize]); + if (currentEvent_.getSize() < esize) currentEvent_ = new Event(new byte[esize]); // populate the event byte[] buf = currentEvent_.getBuf(); nread = tailRead(inputStream_, buf, 0, esize, currentPolicy_); - if(nread != esize) { - return(false); + if (nread != esize) { + return (false); } currentEvent_.setAvailable(esize); - return(true); + return (true); } /** @@ -356,37 +353,31 @@ public class TFileTransport extends TTransport { return ((inputStream_ != null) && (readOnly_ || (outputStream_ != null))); } - /** - * Diverging from the cpp model and sticking to the TSocket model - * Files are not opened in ctor - but in explicit open call + * Diverging from the cpp model and sticking to the TSocket model Files are not opened in ctor - + * but in explicit open call */ public void open() throws TTransportException { - if (isOpen()) - throw new TTransportException(TTransportException.ALREADY_OPEN); + if (isOpen()) throw new TTransportException(TTransportException.ALREADY_OPEN); try { inputStream_ = createInputStream(); cs = new ChunkState(); - currentEvent_ = new Event(new byte [256]); + currentEvent_ = new Event(new byte[256]); - if(!readOnly_) - outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream()); + if (!readOnly_) outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream()); } catch (IOException iox) { throw new TTransportException(TTransportException.NOT_OPEN, iox); } } - /** - * Closes the transport. - */ + /** Closes the transport. */ public void close() { if (inputFile_ != null) { try { inputFile_.close(); } catch (IOException iox) { - LOGGER.warn("WARNING: Error closing input file: " + - iox.getMessage()); + LOGGER.warn("WARNING: Error closing input file: " + iox.getMessage()); } inputFile_ = null; } @@ -394,14 +385,12 @@ public class TFileTransport extends TTransport { try { outputStream_.close(); } catch (IOException iox) { - LOGGER.warn("WARNING: Error closing output stream: " + - iox.getMessage()); + LOGGER.warn("WARNING: Error closing output stream: " + iox.getMessage()); } outputStream_ = null; } } - /** * File Transport ctor * @@ -425,30 +414,26 @@ public class TFileTransport extends TTransport { readOnly_ = readOnly; } - /** - * Cloned from TTransport.java:readAll(). Only difference is throwing an EOF exception - * where one is detected. + * Cloned from TTransport.java:readAll(). Only difference is throwing an EOF exception where one + * is detected. */ - public int readAll(byte[] buf, int off, int len) - throws TTransportException { + public int readAll(byte[] buf, int off, int len) throws TTransportException { int got = 0; int ret = 0; while (got < len) { - ret = read(buf, off+got, len-got); + ret = read(buf, off + got, len - got); if (ret < 0) { throw new TTransportException("Error in reading from file"); } - if(ret == 0) { - throw new TTransportException(TTransportException.END_OF_FILE, - "End of File reached"); + if (ret == 0) { + throw new TTransportException(TTransportException.END_OF_FILE, "End of File reached"); } got += ret; } return got; } - /** * Reads up to len bytes into buffer buf, starting at offset off. * @@ -459,13 +444,11 @@ public class TFileTransport extends TTransport { * @throws TTransportException if there was an error reading data */ public int read(byte[] buf, int off, int len) throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before reading"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before reading"); - if(currentEvent_.getRemaining() == 0) { - if(!readEvent()) - return(0); + if (currentEvent_.getRemaining() == 0) { + if (!readEvent()) return (0); } int nread = currentEvent_.emit(buf, off, len); @@ -473,15 +456,12 @@ public class TFileTransport extends TTransport { } public int getNumChunks() throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before getNumChunks"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getNumChunks"); try { long len = inputFile_.length(); - if(len == 0) - return 0; - else - return (((int)(len/cs.getChunkSize())) + 1); + if (len == 0) return 0; + else return (((int) (len / cs.getChunkSize())) + 1); } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); @@ -489,18 +469,14 @@ public class TFileTransport extends TTransport { } public int getCurChunk() throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before getCurChunk"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getCurChunk"); return (cs.getChunkNum()); - } - public void seekToChunk(int chunk) throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before seeking"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking"); int numChunks = getNumChunks(); @@ -519,45 +495,47 @@ public class TFileTransport extends TTransport { chunk = 0; } - long eofOffset=0; + long eofOffset = 0; boolean seekToEnd = (chunk >= numChunks); - if(seekToEnd) { + if (seekToEnd) { chunk = chunk - 1; - try { eofOffset = inputFile_.length(); } - catch (IOException iox) {throw new TTransportException(iox.getMessage(), - iox);} + try { + eofOffset = inputFile_.length(); + } catch (IOException iox) { + throw new TTransportException(iox.getMessage(), iox); + } } - if(chunk*cs.getChunkSize() != cs.getOffset()) { - try { inputFile_.seek((long)chunk*cs.getChunkSize()); } - catch (IOException iox) { - throw new TTransportException("Seek to chunk " + - chunk + " " +iox.getMessage(), iox); + if (chunk * cs.getChunkSize() != cs.getOffset()) { + try { + inputFile_.seek((long) chunk * cs.getChunkSize()); + } catch (IOException iox) { + throw new TTransportException("Seek to chunk " + chunk + " " + iox.getMessage(), iox); } - cs.seek((long)chunk*cs.getChunkSize()); + cs.seek((long) chunk * cs.getChunkSize()); currentEvent_.setAvailable(0); inputStream_ = createInputStream(); } - if(seekToEnd) { + if (seekToEnd) { // waiting forever here - otherwise we can hit EOF and end up // having consumed partial data from the data stream. TailPolicy old = setTailPolicy(TailPolicy.WAIT_FOREVER); - while(cs.getOffset() < eofOffset) { readEvent(); } + while (cs.getOffset() < eofOffset) { + readEvent(); + } currentEvent_.setAvailable(0); setTailPolicy(old); } } public void seekToEnd() throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before seeking"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking"); seekToChunk(getNumChunks()); } - /** * Writes up to len bytes from the buffer. * @@ -579,36 +557,30 @@ public class TFileTransport extends TTransport { throw new TTransportException("Not Supported"); } - @Override public TConfiguration getConfiguration() { return null; } @Override - public void updateKnownMessageSize(long size) throws TTransportException { - - } + public void updateKnownMessageSize(long size) throws TTransportException {} @Override - public void checkReadBytesAvailable(long numBytes) throws TTransportException { - - } + public void checkReadBytesAvailable(long numBytes) throws TTransportException {} - /** - * test program - * - */ + /** test program */ public static void main(String[] args) throws Exception { int num_chunks = 10; - if((args.length < 1) || args[0].equals("--help") - || args[0].equals("-h") || args[0].equals("-?")) { + if ((args.length < 1) + || args[0].equals("--help") + || args[0].equals("-h") + || args[0].equals("-?")) { printUsage(); } - if(args.length > 1) { + if (args.length > 1) { try { num_chunks = Integer.parseInt(args[1]); } catch (Exception e) { @@ -619,15 +591,15 @@ public class TFileTransport extends TTransport { TFileTransport t = new TFileTransport(args[0], true); t.open(); - LOGGER.info("NumChunks="+t.getNumChunks()); + LOGGER.info("NumChunks=" + t.getNumChunks()); Random r = new Random(); - for(int j=0; j<num_chunks; j++) { + for (int j = 0; j < num_chunks; j++) { byte[] buf = new byte[4096]; - int cnum = r.nextInt(t.getNumChunks()-1); - LOGGER.info("Reading chunk "+cnum); + int cnum = r.nextInt(t.getNumChunks() - 1); + LOGGER.info("Reading chunk " + cnum); t.seekToChunk(cnum); - for(int i=0; i<4096; i++) { + for (int i = 0; i < 4096; i++) { t.read(buf, 0, 4096); } } @@ -638,5 +610,4 @@ public class TFileTransport extends TTransport { LOGGER.error(" (Opens and reads num_chunks chunks from file randomly)"); System.exit(1); } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java b/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java index 574682248..e514dd54e 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java @@ -28,7 +28,6 @@ import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; - import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; @@ -40,32 +39,26 @@ import org.apache.http.entity.ByteArrayEntity; import org.apache.thrift.TConfiguration; /** - * HTTP implementation of the TTransport interface. Used for working with a - * Thrift web services implementation (using for example TServlet). + * HTTP implementation of the TTransport interface. Used for working with a Thrift web services + * implementation (using for example TServlet). * - * This class offers two implementations of the HTTP transport. - * One uses HttpURLConnection instances, the other HttpClient from Apache - * Http Components. - * The chosen implementation depends on the constructor used to - * create the THttpClient instance. - * Using the THttpClient(String url) constructor or passing null as the - * HttpClient to THttpClient(String url, HttpClient client) will create an - * instance which will use HttpURLConnection. + * <p>This class offers two implementations of the HTTP transport. One uses HttpURLConnection + * instances, the other HttpClient from Apache Http Components. The chosen implementation depends on + * the constructor used to create the THttpClient instance. Using the THttpClient(String url) + * constructor or passing null as the HttpClient to THttpClient(String url, HttpClient client) will + * create an instance which will use HttpURLConnection. * - * When using HttpClient, the following configuration leads to 5-15% - * better performance than the HttpURLConnection implementation: + * <p>When using HttpClient, the following configuration leads to 5-15% better performance than the + * HttpURLConnection implementation: * - * http.protocol.version=HttpVersion.HTTP_1_1 - * http.protocol.content-charset=UTF-8 - * http.protocol.expect-continue=false - * http.connection.stalecheck=false + * <p>http.protocol.version=HttpVersion.HTTP_1_1 http.protocol.content-charset=UTF-8 + * http.protocol.expect-continue=false http.connection.stalecheck=false * - * Also note that under high load, the HttpURLConnection implementation - * may exhaust the open file descriptor limit. + * <p>Also note that under high load, the HttpURLConnection implementation may exhaust the open file + * descriptor limit. * * @see <a href="https://issues.apache.org/jira/browse/THRIFT-970">THRIFT-970</a> */ - public class THttpClient extends TEndpointTransport { private final URL url_; @@ -78,13 +71,14 @@ public class THttpClient extends TEndpointTransport { private int readTimeout_ = 0; - private Map<String,String> customHeaders_ = null; + private Map<String, String> customHeaders_ = null; private final HttpHost host; private final HttpClient client; - private static final Map<String, String> DEFAULT_HEADERS = Collections.unmodifiableMap(getDefaultHeaders()); + private static final Map<String, String> DEFAULT_HEADERS = + Collections.unmodifiableMap(getDefaultHeaders()); public static class Factory extends TTransportFactory { @@ -137,12 +131,17 @@ public class THttpClient extends TEndpointTransport { } } - public THttpClient(TConfiguration config, String url, HttpClient client) throws TTransportException { + public THttpClient(TConfiguration config, String url, HttpClient client) + throws TTransportException { super(config); try { url_ = new URL(url); this.client = client; - this.host = new HttpHost(url_.getHost(), -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), url_.getProtocol()); + this.host = + new HttpHost( + url_.getHost(), + -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), + url_.getProtocol()); } catch (IOException iox) { throw new TTransportException(iox); } @@ -153,7 +152,11 @@ public class THttpClient extends TEndpointTransport { try { url_ = new URL(url); this.client = client; - this.host = new HttpHost(url_.getHost(), -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), url_.getProtocol()); + this.host = + new HttpHost( + url_.getHost(), + -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), + url_.getProtocol()); } catch (IOException iox) { throw new TTransportException(iox); } @@ -167,7 +170,7 @@ public class THttpClient extends TEndpointTransport { readTimeout_ = timeout; } - public void setCustomHeaders(Map<String,String> headers) { + public void setCustomHeaders(Map<String, String> headers) { customHeaders_ = new HashMap<>(headers); } @@ -226,7 +229,8 @@ public class THttpClient extends TEndpointTransport { private RequestConfig getRequestConfig() { RequestConfig requestConfig = RequestConfig.DEFAULT; if (connectTimeout_ > 0) { - requestConfig = RequestConfig.copy(requestConfig).setConnectionRequestTimeout(connectTimeout_).build(); + requestConfig = + RequestConfig.copy(requestConfig).setConnectionRequestTimeout(connectTimeout_).build(); } if (readTimeout_ > 0) { requestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(readTimeout_).build(); @@ -243,19 +247,19 @@ public class THttpClient extends TEndpointTransport { } /** - * copy from org.apache.http.util.EntityUtils#consume. Android has it's own httpcore - * that doesn't have a consume. + * copy from org.apache.http.util.EntityUtils#consume. Android has it's own httpcore that doesn't + * have a consume. */ private static void consume(final HttpEntity entity) throws IOException { - if (entity == null) { - return; - } - if (entity.isStreaming()) { - InputStream instream = entity.getContent(); - if (instream != null) { - instream.close(); - } + if (entity == null) { + return; + } + if (entity.isStreaming()) { + InputStream instream = entity.getContent(); + if (instream != null) { + instream.close(); } + } } private void flushUsingHttpClient() throws TTransportException { @@ -311,12 +315,10 @@ public class THttpClient extends TEndpointTransport { } /** - * Read the responses into a byte array so we can release the connection - * early. This implies that the whole content will have to be read in - * memory, and that momentarily we might use up twice the memory (while the - * thrift struct is being read up the chain). - * Proceeding differently might lead to exhaustion of connections and thus - * to app failure. + * Read the responses into a byte array so we can release the connection early. This implies that + * the whole content will have to be read in memory, and that momentarily we might use up twice + * the memory (while the thrift struct is being read up the chain). Proceeding differently might + * lead to exhaustion of connections and thus to app failure. * * @param is input stream * @return read bytes @@ -348,7 +350,7 @@ public class THttpClient extends TEndpointTransport { try { // Create connection object - HttpURLConnection connection = (HttpURLConnection)url_.openConnection(); + HttpURLConnection connection = (HttpURLConnection) url_.openConnection(); // Timeouts, only if explicitly set if (connectTimeout_ > 0) { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java index d5b459c13..edfd1f414 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java @@ -19,21 +19,18 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketTimeoutException; +import org.apache.thrift.TConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * This is the most commonly used base transport. It takes an InputStream or - * an OutputStream or both and uses it/them to perform transport operations. - * This allows for compatibility with all the nice constructs Java already - * has to provide a variety of types of streams. - * + * This is the most commonly used base transport. It takes an InputStream or an OutputStream or both + * and uses it/them to perform transport operations. This allows for compatibility with all the nice + * constructs Java already has to provide a variety of types of streams. */ public class TIOStreamTransport extends TEndpointTransport { @@ -46,16 +43,16 @@ public class TIOStreamTransport extends TEndpointTransport { protected OutputStream outputStream_ = null; /** - * Subclasses can invoke the default constructor and then assign the input - * streams in the open method. + * Subclasses can invoke the default constructor and then assign the input streams in the open + * method. */ protected TIOStreamTransport(TConfiguration config) throws TTransportException { super(config); } /** - * Subclasses can invoke the default constructor and then assign the input - * streams in the open method. + * Subclasses can invoke the default constructor and then assign the input streams in the open + * method. */ protected TIOStreamTransport() throws TTransportException { super(new TConfiguration()); @@ -109,7 +106,8 @@ public class TIOStreamTransport extends TEndpointTransport { * @param is Input stream to read from * @param os Output stream to read from */ - public TIOStreamTransport(TConfiguration config, InputStream is, OutputStream os) throws TTransportException { + public TIOStreamTransport(TConfiguration config, InputStream is, OutputStream os) + throws TTransportException { super(config); inputStream_ = is; outputStream_ = os; @@ -127,22 +125,15 @@ public class TIOStreamTransport extends TEndpointTransport { outputStream_ = os; } - /** - * - * @return false after close is called. - */ + /** @return false after close is called. */ public boolean isOpen() { return inputStream_ != null || outputStream_ != null; } - /** - * The streams must already be open. This method does nothing. - */ + /** The streams must already be open. This method does nothing. */ public void open() throws TTransportException {} - /** - * Closes both the input and output streams. - */ + /** Closes both the input and output streams. */ public void close() { try { if (inputStream_ != null) { @@ -165,12 +156,11 @@ public class TIOStreamTransport extends TEndpointTransport { } } - /** - * Reads from the underlying input stream if not null. - */ + /** Reads from the underlying input stream if not null. */ public int read(byte[] buf, int off, int len) throws TTransportException { if (inputStream_ == null) { - throw new TTransportException(TTransportException.NOT_OPEN, "Cannot read from null inputStream"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot read from null inputStream"); } int bytesRead; try { @@ -186,12 +176,11 @@ public class TIOStreamTransport extends TEndpointTransport { return bytesRead; } - /** - * Writes to the underlying output stream if not null. - */ + /** Writes to the underlying output stream if not null. */ public void write(byte[] buf, int off, int len) throws TTransportException { if (outputStream_ == null) { - throw new TTransportException(TTransportException.NOT_OPEN, "Cannot write to null outputStream"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot write to null outputStream"); } try { outputStream_.write(buf, off, len); @@ -200,9 +189,7 @@ public class TIOStreamTransport extends TEndpointTransport { } } - /** - * Flushes the underlying output stream if not null. - */ + /** Flushes the underlying output stream if not null. */ public void flush() throws TTransportException { if (outputStream_ == null) { throw new TTransportException(TTransportException.NOT_OPEN, "Cannot flush null outputStream"); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java index d9a3cc928..9ce1b2122 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java @@ -19,19 +19,15 @@ package org.apache.thrift.transport; +import java.nio.charset.Charset; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; -import java.nio.charset.Charset; - -/** - * Memory buffer-based implementation of the TTransport interface. - */ +/** Memory buffer-based implementation of the TTransport interface. */ public class TMemoryBuffer extends TEndpointTransport { /** - * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The - * internal buffer will grow as necessary to accommodate the size of the data - * being written to it. + * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The internal buffer will + * grow as necessary to accommodate the size of the data being written to it. * * @param size the initial size of the buffer * @throws TTransportException on error initializing the underlying transport. @@ -43,9 +39,8 @@ public class TMemoryBuffer extends TEndpointTransport { } /** - * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The - * internal buffer will grow as necessary to accommodate the size of the data - * being written to it. + * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The internal buffer will + * grow as necessary to accommodate the size of the data being written to it. * * @param config the configuration to use. * @param size the initial size of the buffer @@ -91,8 +86,8 @@ public class TMemoryBuffer extends TEndpointTransport { } /** - * Output the contents of the memory buffer as a String, using the supplied - * encoding + * Output the contents of the memory buffer as a String, using the supplied encoding + * * @param charset the encoding to use * @return the contents of the memory buffer as a String */ @@ -104,7 +99,7 @@ public class TMemoryBuffer extends TEndpointTransport { StringBuilder buf = new StringBuilder(); byte[] bytes = arr_.toByteArray(); for (int i = 0; i < bytes.length; i++) { - buf.append(pos_ == i ? "==>" : "" ).append(Integer.toHexString(bytes[i] & 0xff)).append(" "); + buf.append(pos_ == i ? "==>" : "").append(Integer.toHexString(bytes[i] & 0xff)).append(" "); } return buf.toString(); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java index 6cb06fc37..375e2b72a 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java @@ -38,7 +38,8 @@ public final class TMemoryInputTransport extends TEndpointTransport { this(new TConfiguration(), buf); } - public TMemoryInputTransport(TConfiguration _configuration, byte[] buf) throws TTransportException { + public TMemoryInputTransport(TConfiguration _configuration, byte[] buf) + throws TTransportException { this(_configuration, buf, 0, buf.length); } @@ -46,7 +47,8 @@ public final class TMemoryInputTransport extends TEndpointTransport { this(new TConfiguration(), buf, offset, length); } - public TMemoryInputTransport(TConfiguration _configuration, byte[] buf, int offset, int length) throws TTransportException { + public TMemoryInputTransport(TConfiguration _configuration, byte[] buf, int offset, int length) + throws TTransportException { super(_configuration); reset(buf, offset, length); updateKnownMessageSize(length); @@ -120,5 +122,4 @@ public final class TMemoryInputTransport extends TEndpointTransport { public void consumeBuffer(int len) { pos_ += len; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java index 0172ca816..2e38588e5 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java @@ -20,13 +20,10 @@ package org.apache.thrift.transport; import java.nio.ByteBuffer; - import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; -/** - * In memory transport with separate buffers for input and output. - */ +/** In memory transport with separate buffers for input and output. */ public class TMemoryTransport extends TEndpointTransport { private final ByteBuffer inputBuffer; @@ -51,9 +48,7 @@ public class TMemoryTransport extends TEndpointTransport { return true; } - /** - * Opening on an in memory transport should have no effect. - */ + /** Opening on an in memory transport should have no effect. */ @Override public void open() { // Do nothing. @@ -69,7 +64,8 @@ public class TMemoryTransport extends TEndpointTransport { checkReadBytesAvailable(len); int remaining = inputBuffer.remaining(); if (remaining < len) { - throw new TTransportException(TTransportException.END_OF_FILE, + throw new TTransportException( + TTransportException.END_OF_FILE, "There's only " + remaining + "bytes, but it asks for " + len); } inputBuffer.get(buf, off, len); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java index 535fd6f51..998379746 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.transport; import java.io.IOException; @@ -29,72 +28,69 @@ import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; - import org.apache.thrift.TConfiguration; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Wrapper around ServerSocketChannel - */ +/** Wrapper around ServerSocketChannel */ public class TNonblockingServerSocket extends TNonblockingServerTransport { - private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingServerSocket.class.getName()); + private static final Logger LOGGER = + LoggerFactory.getLogger(TNonblockingServerSocket.class.getName()); - /** - * This channel is where all the nonblocking magic happens. - */ + /** This channel is where all the nonblocking magic happens. */ private ServerSocketChannel serverSocketChannel = null; - /** - * Underlying ServerSocket object - */ + /** Underlying ServerSocket object */ private ServerSocket serverSocket_ = null; - /** - * Timeout for client sockets from accept - */ + /** Timeout for client sockets from accept */ private int clientTimeout_ = 0; - /** - * Limit for client sockets request size - */ + /** Limit for client sockets request size */ private int maxFrameSize_ = 0; - public static class NonblockingAbstractServerSocketArgs extends - AbstractServerTransportArgs<NonblockingAbstractServerSocketArgs> {} + public static class NonblockingAbstractServerSocketArgs + extends AbstractServerTransportArgs<NonblockingAbstractServerSocketArgs> {} - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TNonblockingServerSocket(int port) throws TTransportException { this(port, 0); } - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TNonblockingServerSocket(int port, int clientTimeout) throws TTransportException { this(port, clientTimeout, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } - public TNonblockingServerSocket(int port, int clientTimeout, int maxFrameSize) throws TTransportException { - this(new NonblockingAbstractServerSocketArgs().port(port).clientTimeout(clientTimeout).maxFrameSize(maxFrameSize)); + public TNonblockingServerSocket(int port, int clientTimeout, int maxFrameSize) + throws TTransportException { + this( + new NonblockingAbstractServerSocketArgs() + .port(port) + .clientTimeout(clientTimeout) + .maxFrameSize(maxFrameSize)); } public TNonblockingServerSocket(InetSocketAddress bindAddr) throws TTransportException { this(bindAddr, 0); } - public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout) throws TTransportException { + public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout) + throws TTransportException { this(bindAddr, clientTimeout, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } - public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout, int maxFrameSize) throws TTransportException { - this(new NonblockingAbstractServerSocketArgs().bindAddr(bindAddr).clientTimeout(clientTimeout).maxFrameSize(maxFrameSize)); + public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout, int maxFrameSize) + throws TTransportException { + this( + new NonblockingAbstractServerSocketArgs() + .bindAddr(bindAddr) + .clientTimeout(clientTimeout) + .maxFrameSize(maxFrameSize)); } - public TNonblockingServerSocket(NonblockingAbstractServerSocketArgs args) throws TTransportException { + public TNonblockingServerSocket(NonblockingAbstractServerSocketArgs args) + throws TTransportException { clientTimeout_ = args.clientTimeout; maxFrameSize_ = args.maxFrameSize; try { @@ -109,7 +105,8 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { serverSocket_.bind(args.bindAddr, args.backlog); } catch (IOException ioe) { serverSocket_ = null; - throw new TTransportException("Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); + throw new TTransportException( + "Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); } } @@ -173,8 +170,7 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { } public int getPort() { - if (serverSocket_ == null) - return -1; + if (serverSocket_ == null) return -1; return serverSocket_.getLocalPort(); } @@ -182,5 +178,4 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { ServerSocketChannel getServerSocketChannel() { return serverSocketChannel; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java index 53d084281..8dfdefb9b 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java @@ -17,20 +17,16 @@ * under the License. */ - package org.apache.thrift.transport; import java.nio.channels.Selector; -/** - * Server transport that can be operated in a nonblocking fashion. - */ +/** Server transport that can be operated in a nonblocking fashion. */ public abstract class TNonblockingServerTransport extends TServerTransport { public abstract void registerSelector(Selector selector); /** - * * @return an incoming connection or null if there is none. * @throws TTransportException on error during this operation. */ diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java index 13c858648..0f4076c8d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.transport; import java.io.IOException; @@ -29,21 +28,16 @@ import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; - import org.apache.thrift.TConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Transport for use with async client. - */ +/** Transport for use with async client. */ public class TNonblockingSocket extends TNonblockingTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingSocket.class.getName()); - /** - * Host and port if passed in, used for lazy non-blocking connect. - */ + /** Host and port if passed in, used for lazy non-blocking connect. */ private final SocketAddress socketAddress_; private final SocketChannel socketChannel_; @@ -54,11 +48,13 @@ public class TNonblockingSocket extends TNonblockingTransport { /** * Create a new nonblocking socket transport that will be connected to host:port. + * * @param host * @param port * @throws IOException */ - public TNonblockingSocket(String host, int port, int timeout) throws IOException, TTransportException { + public TNonblockingSocket(String host, int port, int timeout) + throws IOException, TTransportException { this(SocketChannel.open(), timeout, new InetSocketAddress(host, port)); } @@ -74,12 +70,13 @@ public class TNonblockingSocket extends TNonblockingTransport { } private TNonblockingSocket(SocketChannel socketChannel, int timeout, SocketAddress socketAddress) - throws IOException, TTransportException { + throws IOException, TTransportException { this(new TConfiguration(), socketChannel, timeout, socketAddress); } - private TNonblockingSocket(TConfiguration config, SocketChannel socketChannel, int timeout, SocketAddress socketAddress) - throws IOException, TTransportException { + private TNonblockingSocket( + TConfiguration config, SocketChannel socketChannel, int timeout, SocketAddress socketAddress) + throws IOException, TTransportException { super(config); socketChannel_ = socketChannel; socketAddress_ = socketAddress; @@ -96,8 +93,8 @@ public class TNonblockingSocket extends TNonblockingTransport { } /** - * Register the new SocketChannel with our Selector, indicating - * we'd like to be notified when it's ready for I/O. + * Register the new SocketChannel with our Selector, indicating we'd like to be notified when it's + * ready for I/O. * * @param selector * @return the selection key for this socket. @@ -107,7 +104,8 @@ public class TNonblockingSocket extends TNonblockingTransport { } /** - * Sets the socket timeout, although this implementation never uses blocking operations so it is unused. + * Sets the socket timeout, although this implementation never uses blocking operations so it is + * unused. * * @param timeout Milliseconds timeout */ @@ -119,31 +117,23 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Returns a reference to the underlying SocketChannel. - */ + /** Returns a reference to the underlying SocketChannel. */ public SocketChannel getSocketChannel() { return socketChannel_; } - /** - * Checks whether the socket is connected. - */ + /** Checks whether the socket is connected. */ public boolean isOpen() { // isConnected() does not return false after close(), but isOpen() does return socketChannel_.isOpen() && socketChannel_.isConnected(); } - /** - * Do not call, the implementation provides its own lazy non-blocking connect. - */ + /** Do not call, the implementation provides its own lazy non-blocking connect. */ public void open() throws TTransportException { throw new RuntimeException("open() is not implemented for TNonblockingSocket"); } - /** - * Perform a nonblocking read into buffer. - */ + /** Perform a nonblocking read into buffer. */ public int read(ByteBuffer buffer) throws TTransportException { try { return socketChannel_.read(buffer); @@ -152,13 +142,11 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Reads from the underlying input stream if not null. - */ + /** Reads from the underlying input stream if not null. */ public int read(byte[] buf, int off, int len) throws TTransportException { if ((socketChannel_.validOps() & SelectionKey.OP_READ) != SelectionKey.OP_READ) { - throw new TTransportException(TTransportException.NOT_OPEN, - "Cannot read from write-only socket channel"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot read from write-only socket channel"); } try { return socketChannel_.read(ByteBuffer.wrap(buf, off, len)); @@ -167,9 +155,7 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Perform a nonblocking write of the data in buffer; - */ + /** Perform a nonblocking write of the data in buffer; */ public int write(ByteBuffer buffer) throws TTransportException { try { return socketChannel_.write(buffer); @@ -178,27 +164,21 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Writes to the underlying output stream if not null. - */ + /** Writes to the underlying output stream if not null. */ public void write(byte[] buf, int off, int len) throws TTransportException { if ((socketChannel_.validOps() & SelectionKey.OP_WRITE) != SelectionKey.OP_WRITE) { - throw new TTransportException(TTransportException.NOT_OPEN, - "Cannot write to write-only socket channel"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot write to write-only socket channel"); } write(ByteBuffer.wrap(buf, off, len)); } - /** - * Noop. - */ + /** Noop. */ public void flush() throws TTransportException { // Not supported by SocketChannel. } - /** - * Closes the socket. - */ + /** Closes the socket. */ public void close() { try { socketChannel_.close(); @@ -219,7 +199,10 @@ public class TNonblockingSocket extends TNonblockingTransport { @Override public String toString() { - return "[remote: " + socketChannel_.socket().getRemoteSocketAddress() + - ", local: " + socketChannel_.socket().getLocalAddress() + "]" ; + return "[remote: " + + socketChannel_.socket().getRemoteSocketAddress() + + ", local: " + + socketChannel_.socket().getLocalAddress() + + "]"; } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java index 30ec9d25c..ab3028ca1 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java @@ -19,12 +19,11 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; +import org.apache.thrift.TConfiguration; public abstract class TNonblockingTransport extends TEndpointTransport { @@ -34,16 +33,18 @@ public abstract class TNonblockingTransport extends TEndpointTransport { /** * Non-blocking connection initialization. + * * @see java.nio.channels.SocketChannel#connect(SocketAddress remote) */ public abstract boolean startConnect() throws IOException; /** * Non-blocking connection completion. + * * @see java.nio.channels.SocketChannel#finishConnect() */ public abstract boolean finishConnect() throws IOException; - public abstract SelectionKey registerSelector(Selector selector, int interests) throws IOException; - + public abstract SelectionKey registerSelector(Selector selector, int interests) + throws IOException; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java b/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java index 3389e4d2a..917f4c95d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java @@ -21,14 +21,13 @@ package org.apache.thrift.transport; import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.net.InetAddress; -import java.net.URL; import java.net.MalformedURLException; +import java.net.URL; import java.security.KeyStore; import java.util.Arrays; - import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocket; @@ -36,28 +35,22 @@ import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A Factory for providing and setting up Client and Server SSL wrapped - * TSocket and TServerSocket + * A Factory for providing and setting up Client and Server SSL wrapped TSocket and TServerSocket */ public class TSSLTransportFactory { - private static final Logger LOGGER = - LoggerFactory.getLogger(TSSLTransportFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TSSLTransportFactory.class); /** - * Get a SSL wrapped TServerSocket bound to the specified port. In this - * configuration the default settings are used. Default settings are retrieved - * from System properties that are set. + * Get a SSL wrapped TServerSocket bound to the specified port. In this configuration the default + * settings are used. Default settings are retrieved from System properties that are set. * - * Example system properties: - * -Djavax.net.ssl.trustStore=<truststore location> - * -Djavax.net.ssl.trustStorePassword=password - * -Djavax.net.ssl.keyStore=<keystore location> + * <p>Example system properties: -Djavax.net.ssl.trustStore=<truststore location> + * -Djavax.net.ssl.trustStorePassword=password -Djavax.net.ssl.keyStore=<keystore location> * -Djavax.net.ssl.keyStorePassword=password * * @param port @@ -76,7 +69,8 @@ public class TSSLTransportFactory { * @return A SSL wrapped TServerSocket * @throws TTransportException */ - public static TServerSocket getServerSocket(int port, int clientTimeout) throws TTransportException { + public static TServerSocket getServerSocket(int port, int clientTimeout) + throws TTransportException { return getServerSocket(port, clientTimeout, false, null); } @@ -89,15 +83,17 @@ public class TSSLTransportFactory { * @return A SSL wrapped TServerSocket * @throws TTransportException */ - public static TServerSocket getServerSocket(int port, int clientTimeout, boolean clientAuth, InetAddress ifAddress) throws TTransportException { + public static TServerSocket getServerSocket( + int port, int clientTimeout, boolean clientAuth, InetAddress ifAddress) + throws TTransportException { SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); return createServer(factory, port, clientTimeout, clientAuth, ifAddress, null); } /** - * Get a configured SSL wrapped TServerSocket bound to the specified port and interface. - * Here the TSSLTransportParameters are used to set the values for the algorithms, keystore, - * truststore and other settings + * Get a configured SSL wrapped TServerSocket bound to the specified port and interface. Here the + * TSSLTransportParameters are used to set the values for the algorithms, keystore, truststore and + * other settings * * @param port * @param clientTimeout @@ -106,35 +102,47 @@ public class TSSLTransportFactory { * @return A SSL wrapped TServerSocket * @throws TTransportException */ - public static TServerSocket getServerSocket(int port, int clientTimeout, InetAddress ifAddress, TSSLTransportParameters params) throws TTransportException { + public static TServerSocket getServerSocket( + int port, int clientTimeout, InetAddress ifAddress, TSSLTransportParameters params) + throws TTransportException { if (params == null || !(params.isKeyStoreSet || params.isTrustStoreSet)) { - throw new TTransportException("Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); + throw new TTransportException( + "Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); } SSLContext ctx = createSSLContext(params); - return createServer(ctx.getServerSocketFactory(), port, clientTimeout, params.clientAuth, ifAddress, params); + return createServer( + ctx.getServerSocketFactory(), port, clientTimeout, params.clientAuth, ifAddress, params); } - private static TServerSocket createServer(SSLServerSocketFactory factory, int port, int timeout, boolean clientAuth, - InetAddress ifAddress, TSSLTransportParameters params) throws TTransportException { + private static TServerSocket createServer( + SSLServerSocketFactory factory, + int port, + int timeout, + boolean clientAuth, + InetAddress ifAddress, + TSSLTransportParameters params) + throws TTransportException { try { - SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(port, 100, ifAddress); + SSLServerSocket serverSocket = + (SSLServerSocket) factory.createServerSocket(port, 100, ifAddress); serverSocket.setSoTimeout(timeout); serverSocket.setNeedClientAuth(clientAuth); if (params != null && params.cipherSuites != null) { serverSocket.setEnabledCipherSuites(params.cipherSuites); } - return new TServerSocket(new TServerSocket.ServerSocketTransportArgs(). - serverSocket(serverSocket).clientTimeout(timeout)); + return new TServerSocket( + new TServerSocket.ServerSocketTransportArgs() + .serverSocket(serverSocket) + .clientTimeout(timeout)); } catch (Exception e) { throw new TTransportException("Could not bind to port " + port, e); } } /** - * Get a default SSL wrapped TSocket connected to the specified host and port. All - * the client methods return a bound connection. So there is no need to call open() on the - * TTransport. + * Get a default SSL wrapped TSocket connected to the specified host and port. All the client + * methods return a bound connection. So there is no need to call open() on the TTransport. * * @param host * @param port @@ -142,7 +150,8 @@ public class TSSLTransportFactory { * @return A SSL wrapped TSocket * @throws TTransportException */ - public static TSocket getClientSocket(String host, int port, int timeout) throws TTransportException { + public static TSocket getClientSocket(String host, int port, int timeout) + throws TTransportException { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); return createClient(factory, host, port, timeout); } @@ -160,8 +169,8 @@ public class TSSLTransportFactory { } /** - * Get a custom configured SSL wrapped TSocket. The SSL settings are obtained from the - * passed in TSSLTransportParameters. + * Get a custom configured SSL wrapped TSocket. The SSL settings are obtained from the passed in + * TSSLTransportParameters. * * @param host * @param port @@ -170,16 +179,21 @@ public class TSSLTransportFactory { * @return A SSL wrapped TSocket * @throws TTransportException */ - public static TSocket getClientSocket(String host, int port, int timeout, TSSLTransportParameters params) throws TTransportException { + public static TSocket getClientSocket( + String host, int port, int timeout, TSSLTransportParameters params) + throws TTransportException { if (params == null || !(params.isKeyStoreSet || params.isTrustStoreSet)) { - throw new TTransportException(TTransportException.NOT_OPEN, "Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); + throw new TTransportException( + TTransportException.NOT_OPEN, + "Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); } SSLContext ctx = createSSLContext(params); return createClient(ctx.getSocketFactory(), host, port, timeout); } - private static SSLContext createSSLContext(TSSLTransportParameters params) throws TTransportException { + private static SSLContext createSSLContext(TSSLTransportParameters params) + throws TTransportException { SSLContext ctx; InputStream in = null; InputStream is = null; @@ -197,8 +211,7 @@ public class TSSLTransportFactory { } else { in = getStoreAsStream(params.trustStore); } - ts.load(in, - (params.trustPass != null ? params.trustPass.toCharArray() : null)); + ts.load(in, (params.trustPass != null ? params.trustPass.toCharArray() : null)); tmf.init(ts); } @@ -206,9 +219,9 @@ public class TSSLTransportFactory { kmf = KeyManagerFactory.getInstance(params.keyManagerType); KeyStore ks = KeyStore.getInstance(params.keyStoreType); if (params.keyStoreStream != null) { - is = params.keyStoreStream; + is = params.keyStoreStream; } else { - is = getStoreAsStream(params.keyStore); + is = getStoreAsStream(params.keyStore); } ks.load(is, params.keyPass.toCharArray()); kmf.init(ks, params.keyPass.toCharArray()); @@ -216,16 +229,15 @@ public class TSSLTransportFactory { if (params.isKeyStoreSet && params.isTrustStoreSet) { ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - } - else if (params.isKeyStoreSet) { + } else if (params.isKeyStoreSet) { ctx.init(kmf.getKeyManagers(), null, null); - } - else { + } else { ctx.init(null, tmf.getTrustManagers(), null); } } catch (Exception e) { - throw new TTransportException(TTransportException.NOT_OPEN, "Error creating the transport", e); + throw new TTransportException( + TTransportException.NOT_OPEN, "Error creating the transport", e); } finally { if (in != null) { try { @@ -249,7 +261,7 @@ public class TSSLTransportFactory { private static InputStream getStoreAsStream(String store) throws IOException { try { return new FileInputStream(store); - } catch(FileNotFoundException e) { + } catch (FileNotFoundException e) { } InputStream storeStream = null; @@ -258,7 +270,7 @@ public class TSSLTransportFactory { if (storeStream != null) { return storeStream; } - } catch(MalformedURLException e) { + } catch (MalformedURLException e) { } storeStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(store); @@ -270,7 +282,8 @@ public class TSSLTransportFactory { } } - private static TSocket createClient(SSLSocketFactory factory, String host, int port, int timeout) throws TTransportException { + private static TSocket createClient(SSLSocketFactory factory, String host, int port, int timeout) + throws TTransportException { try { SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(timeout); @@ -278,14 +291,12 @@ public class TSSLTransportFactory { } catch (TTransportException tte) { throw tte; } catch (Exception e) { - throw new TTransportException(TTransportException.NOT_OPEN, "Could not connect to " + host + " on port " + port, e); + throw new TTransportException( + TTransportException.NOT_OPEN, "Could not connect to " + host + " on port " + port, e); } } - - /** - * A Class to hold all the SSL parameters - */ + /** A Class to hold all the SSL parameters */ public static class TSSLTransportParameters { protected String protocol = "TLS"; protected String keyStore; @@ -316,8 +327,8 @@ public class TSSLTransportFactory { } /** - * Create parameters specifying the protocol, cipher suites and if client authentication - * is required + * Create parameters specifying the protocol, cipher suites and if client authentication is + * required * * @param protocol The specific protocol (TLS/SSL) can be specified with versions * @param cipherSuites @@ -327,7 +338,8 @@ public class TSSLTransportFactory { if (protocol != null) { this.protocol = protocol; } - this.cipherSuites = cipherSuites != null ? Arrays.copyOf(cipherSuites, cipherSuites.length) : null; + this.cipherSuites = + cipherSuites != null ? Arrays.copyOf(cipherSuites, cipherSuites.length) : null; this.clientAuth = clientAuth; } @@ -339,7 +351,8 @@ public class TSSLTransportFactory { * @param keyManagerType The default is X509 * @param keyStoreType The default is JKS */ - public void setKeyStore(String keyStore, String keyPass, String keyManagerType, String keyStoreType) { + public void setKeyStore( + String keyStore, String keyPass, String keyManagerType, String keyStoreType) { this.keyStore = keyStore; this.keyPass = keyPass; if (keyManagerType != null) { @@ -359,9 +372,10 @@ public class TSSLTransportFactory { * @param keyManagerType The default is X509 * @param keyStoreType The default is JKS */ - public void setKeyStore(InputStream keyStoreStream, String keyPass, String keyManagerType, String keyStoreType) { - this.keyStoreStream = keyStoreStream; - setKeyStore("", keyPass, keyManagerType, keyStoreType); + public void setKeyStore( + InputStream keyStoreStream, String keyPass, String keyManagerType, String keyStoreType) { + this.keyStoreStream = keyStoreStream; + setKeyStore("", keyPass, keyManagerType, keyStoreType); } /** @@ -392,7 +406,8 @@ public class TSSLTransportFactory { * @param trustManagerType The default is X509 * @param trustStoreType The default is JKS */ - public void setTrustStore(String trustStore, String trustPass, String trustManagerType, String trustStoreType) { + public void setTrustStore( + String trustStore, String trustPass, String trustManagerType, String trustStoreType) { this.trustStore = trustStore; this.trustPass = trustPass; if (trustManagerType != null) { @@ -412,7 +427,11 @@ public class TSSLTransportFactory { * @param trustManagerType The default is X509 * @param trustStoreType The default is JKS */ - public void setTrustStore(InputStream trustStoreStream, String trustPass, String trustManagerType, String trustStoreType) { + public void setTrustStore( + InputStream trustStoreStream, + String trustPass, + String trustManagerType, + String trustStoreType) { this.trustStoreStream = trustStoreStream; setTrustStore("", trustPass, trustManagerType, trustStoreType); } @@ -444,6 +463,6 @@ public class TSSLTransportFactory { */ public void requireClientAuth(boolean clientAuth) { this.clientAuth = clientAuth; - } - } + } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java index e5ca41831..19cc41ec0 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java @@ -21,71 +21,69 @@ package org.apache.thrift.transport; import java.nio.charset.StandardCharsets; import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; - import org.apache.thrift.transport.sasl.NegotiationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Wraps another Thrift <code>TTransport</code>, but performs SASL client - * negotiation on the call to <code>open()</code>. This class will wrap ensuing - * communication over it, if a SASL QOP is negotiated with the other party. + * Wraps another Thrift <code>TTransport</code>, but performs SASL client negotiation on the call to + * <code>open()</code>. This class will wrap ensuing communication over it, if a SASL QOP is + * negotiated with the other party. */ public class TSaslClientTransport extends TSaslTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslClientTransport.class); - /** - * The name of the mechanism this client supports. - */ + /** The name of the mechanism this client supports. */ private final String mechanism; /** * Uses the given <code>SaslClient</code>. * - * @param saslClient - * The <code>SaslClient</code> to use for the subsequent SASL - * negotiation. - * @param transport - * Transport underlying this one. + * @param saslClient The <code>SaslClient</code> to use for the subsequent SASL negotiation. + * @param transport Transport underlying this one. */ - public TSaslClientTransport(SaslClient saslClient, TTransport transport) throws TTransportException { + public TSaslClientTransport(SaslClient saslClient, TTransport transport) + throws TTransportException { super(saslClient, transport); mechanism = saslClient.getMechanismName(); } /** - * Creates a <code>SaslClient</code> using the given SASL-specific parameters. - * See the Java documentation for <code>Sasl.createSaslClient</code> for the - * details of the parameters. + * Creates a <code>SaslClient</code> using the given SASL-specific parameters. See the Java + * documentation for <code>Sasl.createSaslClient</code> for the details of the parameters. * - * @param transport - * The underlying Thrift transport. + * @param transport The underlying Thrift transport. * @throws SaslException */ - public TSaslClientTransport(String mechanism, String authorizationId, String protocol, - String serverName, Map<String, String> props, CallbackHandler cbh, TTransport transport) - throws SaslException, TTransportException { - super(Sasl.createSaslClient(new String[] { mechanism }, authorizationId, protocol, serverName, - props, cbh), transport); + public TSaslClientTransport( + String mechanism, + String authorizationId, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh, + TTransport transport) + throws SaslException, TTransportException { + super( + Sasl.createSaslClient( + new String[] {mechanism}, authorizationId, protocol, serverName, props, cbh), + transport); this.mechanism = mechanism; } - @Override protected SaslRole getRole() { return SaslRole.CLIENT; } /** - * Performs the client side of the initial portion of the Thrift SASL - * protocol. Generates and sends the initial response to the server, including - * which mechanism this client wants to use. + * Performs the client side of the initial portion of the Thrift SASL protocol. Generates and + * sends the initial response to the server, including which mechanism this client wants to use. */ @Override protected void handleSaslStartMessage() throws TTransportException, SaslException { @@ -95,15 +93,17 @@ public class TSaslClientTransport extends TSaslTransport { if (saslClient.hasInitialResponse()) initialResponse = saslClient.evaluateChallenge(initialResponse); - LOGGER.debug("Sending mechanism name {} and initial response of length {}", mechanism, + LOGGER.debug( + "Sending mechanism name {} and initial response of length {}", + mechanism, initialResponse.length); byte[] mechanismBytes = mechanism.getBytes(StandardCharsets.UTF_8); - sendSaslMessage(NegotiationStatus.START, - mechanismBytes); + sendSaslMessage(NegotiationStatus.START, mechanismBytes); // Send initial response - sendSaslMessage(saslClient.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, - initialResponse); + sendSaslMessage( + saslClient.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, + initialResponse); underlyingTransport.flush(); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java index 9111712a4..42a838c0a 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java @@ -25,71 +25,76 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - import org.apache.thrift.transport.sasl.NegotiationStatus; import org.apache.thrift.transport.sasl.TSaslServerDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Wraps another Thrift <code>TTransport</code>, but performs SASL server - * negotiation on the call to <code>open()</code>. This class will wrap ensuing - * communication over it, if a SASL QOP is negotiated with the other party. + * Wraps another Thrift <code>TTransport</code>, but performs SASL server negotiation on the call to + * <code>open()</code>. This class will wrap ensuing communication over it, if a SASL QOP is + * negotiated with the other party. */ public class TSaslServerTransport extends TSaslTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslServerTransport.class); /** - * Mapping from SASL mechanism name -> all the parameters required to - * instantiate a SASL server. + * Mapping from SASL mechanism name -> all the parameters required to instantiate a SASL server. */ - private Map<String, TSaslServerDefinition> serverDefinitionMap = new HashMap<String, TSaslServerDefinition>(); + private Map<String, TSaslServerDefinition> serverDefinitionMap = + new HashMap<String, TSaslServerDefinition>(); /** - * Uses the given underlying transport. Assumes that addServerDefinition is - * called later. + * Uses the given underlying transport. Assumes that addServerDefinition is called later. * - * @param transport - * Transport underlying this one. + * @param transport Transport underlying this one. */ public TSaslServerTransport(TTransport transport) throws TTransportException { super(transport); } /** - * Creates a <code>SaslServer</code> using the given SASL-specific parameters. - * See the Java documentation for <code>Sasl.createSaslServer</code> for the - * details of the parameters. + * Creates a <code>SaslServer</code> using the given SASL-specific parameters. See the Java + * documentation for <code>Sasl.createSaslServer</code> for the details of the parameters. * - * @param transport - * The underlying Thrift transport. + * @param transport The underlying Thrift transport. */ - public TSaslServerTransport(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh, TTransport transport) throws TTransportException { + public TSaslServerTransport( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh, + TTransport transport) + throws TTransportException { super(transport); addServerDefinition(mechanism, protocol, serverName, props, cbh); } - private TSaslServerTransport(Map<String, TSaslServerDefinition> serverDefinitionMap, TTransport transport) throws TTransportException { + private TSaslServerTransport( + Map<String, TSaslServerDefinition> serverDefinitionMap, TTransport transport) + throws TTransportException { super(transport); this.serverDefinitionMap.putAll(serverDefinitionMap); } /** - * Add a supported server definition to this transport. See the Java - * documentation for <code>Sasl.createSaslServer</code> for the details of the - * parameters. + * Add a supported server definition to this transport. See the Java documentation for <code> + * Sasl.createSaslServer</code> for the details of the parameters. */ - public void addServerDefinition(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { - serverDefinitionMap.put(mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, - props, cbh)); + public void addServerDefinition( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { + serverDefinitionMap.put( + mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, props, cbh)); } @Override @@ -98,10 +103,9 @@ public class TSaslServerTransport extends TSaslTransport { } /** - * Performs the server side of the initial portion of the Thrift SASL protocol. - * Receives the initial response from the client, creates a SASL server using - * the mechanism requested by the client (if this server supports it), and - * sends the first challenge back to the client. + * Performs the server side of the initial portion of the Thrift SASL protocol. Receives the + * initial response from the client, creates a SASL server using the mechanism requested by the + * client (if this server supports it), and sends the first challenge back to the client. */ @Override protected void handleSaslStartMessage() throws TTransportException, SaslException { @@ -109,7 +113,8 @@ public class TSaslServerTransport extends TSaslTransport { LOGGER.debug("Received start message with status {}", message.status); if (message.status != NegotiationStatus.START) { - throw sendAndThrowMessage(NegotiationStatus.ERROR, "Expecting START status, received " + message.status); + throw sendAndThrowMessage( + NegotiationStatus.ERROR, "Expecting START status, received " + message.status); } // Get the mechanism name. @@ -118,75 +123,80 @@ public class TSaslServerTransport extends TSaslTransport { LOGGER.debug("Received mechanism name '{}'", mechanismName); if (serverDefinition == null) { - throw sendAndThrowMessage(NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName); + throw sendAndThrowMessage( + NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName); } - SaslServer saslServer = Sasl.createSaslServer(serverDefinition.mechanism, - serverDefinition.protocol, serverDefinition.serverName, serverDefinition.props, - serverDefinition.cbh); + SaslServer saslServer = + Sasl.createSaslServer( + serverDefinition.mechanism, + serverDefinition.protocol, + serverDefinition.serverName, + serverDefinition.props, + serverDefinition.cbh); setSaslServer(saslServer); } /** - * <code>TTransportFactory</code> to create - * <code>TSaslServerTransports</code>. Ensures that a given - * underlying <code>TTransport</code> instance receives the same - * <code>TSaslServerTransport</code>. This is kind of an awful hack to work - * around the fact that Thrift is designed assuming that - * <code>TTransport</code> instances are stateless, and thus the existing - * <code>TServers</code> use different <code>TTransport</code> instances for - * input and output. + * <code>TTransportFactory</code> to create <code>TSaslServerTransports</code>. Ensures that a + * given underlying <code>TTransport</code> instance receives the same <code>TSaslServerTransport + * </code>. This is kind of an awful hack to work around the fact that Thrift is designed assuming + * that <code>TTransport</code> instances are stateless, and thus the existing <code>TServers + * </code> use different <code>TTransport</code> instances for input and output. */ public static class Factory extends TTransportFactory { /** - * This is the implementation of the awful hack described above. - * <code>WeakHashMap</code> is used to ensure that we don't leak memory. + * This is the implementation of the awful hack described above. <code>WeakHashMap</code> is + * used to ensure that we don't leak memory. */ private static Map<TTransport, WeakReference<TSaslServerTransport>> transportMap = - Collections.synchronizedMap(new WeakHashMap<TTransport, WeakReference<TSaslServerTransport>>()); + Collections.synchronizedMap( + new WeakHashMap<TTransport, WeakReference<TSaslServerTransport>>()); /** - * Mapping from SASL mechanism name -> all the parameters required to - * instantiate a SASL server. + * Mapping from SASL mechanism name -> all the parameters required to instantiate a SASL server. */ - private Map<String, TSaslServerDefinition> serverDefinitionMap = new HashMap<String, TSaslServerDefinition>(); + private Map<String, TSaslServerDefinition> serverDefinitionMap = + new HashMap<String, TSaslServerDefinition>(); - /** - * Create a new Factory. Assumes that <code>addServerDefinition</code> will - * be called later. - */ + /** Create a new Factory. Assumes that <code>addServerDefinition</code> will be called later. */ public Factory() { super(); } /** - * Create a new <code>Factory</code>, initially with the single server - * definition given. You may still call <code>addServerDefinition</code> - * later. See the Java documentation for <code>Sasl.createSaslServer</code> - * for the details of the parameters. + * Create a new <code>Factory</code>, initially with the single server definition given. You may + * still call <code>addServerDefinition</code> later. See the Java documentation for <code> + * Sasl.createSaslServer</code> for the details of the parameters. */ - public Factory(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { + public Factory( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { super(); addServerDefinition(mechanism, protocol, serverName, props, cbh); } /** - * Add a supported server definition to the transports created by this - * factory. See the Java documentation for - * <code>Sasl.createSaslServer</code> for the details of the parameters. + * Add a supported server definition to the transports created by this factory. See the Java + * documentation for <code>Sasl.createSaslServer</code> for the details of the parameters. */ - public void addServerDefinition(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { - serverDefinitionMap.put(mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, - props, cbh)); + public void addServerDefinition( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { + serverDefinitionMap.put( + mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, props, cbh)); } /** - * Get a new <code>TSaslServerTransport</code> instance, or reuse the - * existing one if a <code>TSaslServerTransport</code> has already been - * created before using the given <code>TTransport</code> as an underlying - * transport. This ensures that a given underlying transport instance + * Get a new <code>TSaslServerTransport</code> instance, or reuse the existing one if a <code> + * TSaslServerTransport</code> has already been created before using the given <code>TTransport + * </code> as an underlying transport. This ensures that a given underlying transport instance * receives the same <code>TSaslServerTransport</code>. */ @Override @@ -194,7 +204,9 @@ public class TSaslServerTransport extends TSaslTransport { WeakReference<TSaslServerTransport> ret = transportMap.get(base); if (ret == null || ret.get() == null) { LOGGER.debug("transport map does not contain key", base); - ret = new WeakReference<TSaslServerTransport>(new TSaslServerTransport(serverDefinitionMap, base)); + ret = + new WeakReference<TSaslServerTransport>( + new TSaslServerTransport(serverDefinitionMap, base)); try { ret.get().open(); } catch (TTransportException e) { @@ -202,7 +214,7 @@ public class TSaslServerTransport extends TSaslTransport { throw new RuntimeException(e); } transportMap.put(base, ret); // No need for putIfAbsent(). - // Concurrent calls to getTransport() will pass in different TTransports. + // Concurrent calls to getTransport() will pass in different TTransports. } else { LOGGER.debug("transport map does contain key {}", base); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java index b22469d2b..0a280d6b3 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java @@ -21,12 +21,10 @@ package org.apache.thrift.transport; import java.nio.charset.StandardCharsets; import java.util.Objects; - import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - import org.apache.thrift.EncodingUtils; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; @@ -36,8 +34,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A superclass for SASL client/server thrift transports. A subclass need only - * implement the <code>open</code> method. + * A superclass for SASL client/server thrift transports. A subclass need only implement the <code> + * open</code> method. */ abstract class TSaslTransport extends TEndpointTransport { @@ -50,44 +48,39 @@ abstract class TSaslTransport extends TEndpointTransport { protected static final int PAYLOAD_LENGTH_BYTES = 4; protected static enum SaslRole { - SERVER, CLIENT; + SERVER, + CLIENT; } - /** - * Transport underlying this one. - */ + /** Transport underlying this one. */ protected TTransport underlyingTransport; - /** - * Either a SASL client or a SASL server. - */ + /** Either a SASL client or a SASL server. */ private SaslParticipant sasl; /** - * Whether or not we should wrap/unwrap reads/writes. Determined by whether or - * not a QOP is negotiated during the SASL handshake. + * Whether or not we should wrap/unwrap reads/writes. Determined by whether or not a QOP is + * negotiated during the SASL handshake. */ private boolean shouldWrap = false; - /** - * Buffer for input. - */ + /** Buffer for input. */ private TMemoryInputTransport readBuffer; - /** - * Buffer for output. - */ + /** Buffer for output. */ private final TByteArrayOutputStream writeBuffer = new TByteArrayOutputStream(1024); /** - * Create a TSaslTransport. It's assumed that setSaslServer will be called - * later to initialize the SASL endpoint underlying this transport. + * Create a TSaslTransport. It's assumed that setSaslServer will be called later to initialize the + * SASL endpoint underlying this transport. * - * @param underlyingTransport - * The thrift transport which this transport is wrapping. + * @param underlyingTransport The thrift transport which this transport is wrapping. */ protected TSaslTransport(TTransport underlyingTransport) throws TTransportException { - super(Objects.isNull(underlyingTransport.getConfiguration()) ? new TConfiguration() : underlyingTransport.getConfiguration()); + super( + Objects.isNull(underlyingTransport.getConfiguration()) + ? new TConfiguration() + : underlyingTransport.getConfiguration()); this.underlyingTransport = underlyingTransport; this.readBuffer = new TMemoryInputTransport(underlyingTransport.getConfiguration()); } @@ -95,14 +88,16 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Create a TSaslTransport which acts as a client. * - * @param saslClient - * The <code>SaslClient</code> which this transport will use for SASL - * negotiation. - * @param underlyingTransport - * The thrift transport which this transport is wrapping. + * @param saslClient The <code>SaslClient</code> which this transport will use for SASL + * negotiation. + * @param underlyingTransport The thrift transport which this transport is wrapping. */ - protected TSaslTransport(SaslClient saslClient, TTransport underlyingTransport) throws TTransportException { - super(Objects.isNull(underlyingTransport.getConfiguration()) ? new TConfiguration() : underlyingTransport.getConfiguration()); + protected TSaslTransport(SaslClient saslClient, TTransport underlyingTransport) + throws TTransportException { + super( + Objects.isNull(underlyingTransport.getConfiguration()) + ? new TConfiguration() + : underlyingTransport.getConfiguration()); sasl = new SaslParticipant(saslClient); this.underlyingTransport = underlyingTransport; this.readBuffer = new TMemoryInputTransport(underlyingTransport.getConfiguration()); @@ -118,21 +113,22 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Send a complete Thrift SASL message. * - * @param status - * The status to send. - * @param payload - * The data to send as the payload of this message. + * @param status The status to send. + * @param payload The data to send as the payload of this message. * @throws TTransportException */ - protected void sendSaslMessage(NegotiationStatus status, byte[] payload) throws TTransportException { - if (payload == null) - payload = new byte[0]; + protected void sendSaslMessage(NegotiationStatus status, byte[] payload) + throws TTransportException { + if (payload == null) payload = new byte[0]; messageHeader[0] = status.getValue(); EncodingUtils.encodeBigEndian(payload.length, messageHeader, STATUS_BYTES); - LOGGER.debug("{}: Writing message with status {} and payload length {}", - getRole(), status, payload.length); + LOGGER.debug( + "{}: Writing message with status {} and payload length {}", + getRole(), + status, + payload.length); underlyingTransport.write(messageHeader); underlyingTransport.write(payload); @@ -143,9 +139,8 @@ abstract class TSaslTransport extends TEndpointTransport { * Read a complete Thrift SASL message. * * @return The SASL status and payload from this message. - * @throws TTransportException - * Thrown if there is a failure reading from the underlying - * transport, or if a status code of BAD or ERROR is encountered. + * @throws TTransportException Thrown if there is a failure reading from the underlying transport, + * or if a status code of BAD or ERROR is encountered. */ protected SaslResponse receiveSaslMessage() throws TTransportException { underlyingTransport.readAll(messageHeader, 0, messageHeader.length); @@ -160,7 +155,7 @@ abstract class TSaslTransport extends TEndpointTransport { int payloadBytes = EncodingUtils.decodeBigEndian(messageHeader, STATUS_BYTES); if (payloadBytes < 0 || payloadBytes > getConfiguration().getMaxMessageSize() /* 100 MB */) { throw sendAndThrowMessage( - NegotiationStatus.ERROR, "Invalid payload header length: " + payloadBytes); + NegotiationStatus.ERROR, "Invalid payload header length: " + payloadBytes); } byte[] payload = new byte[payloadBytes]; @@ -170,26 +165,26 @@ abstract class TSaslTransport extends TEndpointTransport { String remoteMessage = new String(payload, StandardCharsets.UTF_8); throw new TTransportException("Peer indicated failure: " + remoteMessage); } - LOGGER.debug("{}: Received message with status {} and payload length {}", - getRole(), status, payload.length); + LOGGER.debug( + "{}: Received message with status {} and payload length {}", + getRole(), + status, + payload.length); return new SaslResponse(status, payload); } /** - * Send a Thrift SASL message with the given status (usually BAD or ERROR) and - * string message, and then throw a TTransportException with the given - * message. + * Send a Thrift SASL message with the given status (usually BAD or ERROR) and string message, and + * then throw a TTransportException with the given message. * - * @param status - * The Thrift SASL status code to send. Usually BAD or ERROR. - * @param message - * The optional message to send to the other side. - * @throws TTransportException - * Always thrown with the message provided. - * @return always throws TTransportException but declares return type to allow - * throw sendAndThrowMessage(...) to inform compiler control flow + * @param status The Thrift SASL status code to send. Usually BAD or ERROR. + * @param message The optional message to send to the other side. + * @throws TTransportException Always thrown with the message provided. + * @return always throws TTransportException but declares return type to allow throw + * sendAndThrowMessage(...) to inform compiler control flow */ - protected TTransportException sendAndThrowMessage(NegotiationStatus status, String message) throws TTransportException { + protected TTransportException sendAndThrowMessage(NegotiationStatus status, String message) + throws TTransportException { try { sendSaslMessage(status, message.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { @@ -200,21 +195,20 @@ abstract class TSaslTransport extends TEndpointTransport { } /** - * Implemented by subclasses to start the Thrift SASL handshake process. When - * this method completes, the <code>SaslParticipant</code> in this class is - * assumed to be initialized. + * Implemented by subclasses to start the Thrift SASL handshake process. When this method + * completes, the <code>SaslParticipant</code> in this class is assumed to be initialized. * * @throws TTransportException * @throws SaslException */ - abstract protected void handleSaslStartMessage() throws TTransportException, SaslException; + protected abstract void handleSaslStartMessage() throws TTransportException, SaslException; protected abstract SaslRole getRole(); /** - * Opens the underlying transport if it's not already open and then performs - * SASL negotiation. If a QOP is negotiated during this SASL handshake, it used - * for all communication on this transport after this call is complete. + * Opens the underlying transport if it's not already open and then performs SASL negotiation. If + * a QOP is negotiated during this SASL handshake, it used for all communication on this transport + * after this call is complete. */ @Override public void open() throws TTransportException { @@ -229,8 +223,7 @@ abstract class TSaslTransport extends TEndpointTransport { if (sasl != null && sasl.isComplete()) throw new TTransportException("SASL transport already open"); - if (!underlyingTransport.isOpen()) - underlyingTransport.open(); + if (!underlyingTransport.isOpen()) underlyingTransport.open(); try { // Negotiate a SASL mechanism. The client also sends its @@ -242,8 +235,8 @@ abstract class TSaslTransport extends TEndpointTransport { SaslResponse message = null; while (!sasl.isComplete()) { message = receiveSaslMessage(); - if (message.status != NegotiationStatus.COMPLETE && - message.status != NegotiationStatus.OK) { + if (message.status != NegotiationStatus.COMPLETE + && message.status != NegotiationStatus.OK) { throw new TTransportException("Expected COMPLETE or OK, got " + message.status); } @@ -251,14 +244,13 @@ abstract class TSaslTransport extends TEndpointTransport { // If we are the client, and the server indicates COMPLETE, we don't need to // send back any further response. - if (message.status == NegotiationStatus.COMPLETE && - getRole() == SaslRole.CLIENT) { + if (message.status == NegotiationStatus.COMPLETE && getRole() == SaslRole.CLIENT) { LOGGER.debug("{}: All done!", getRole()); continue; } - sendSaslMessage(sasl.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, - challenge); + sendSaslMessage( + sasl.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, challenge); } LOGGER.debug("{}: Main negotiation loop complete", getRole()); @@ -266,13 +258,12 @@ abstract class TSaslTransport extends TEndpointTransport { // complete yet, we need to wait for its response. This will occur // with ANONYMOUS auth, for example, where we send an initial response // and are immediately complete. - if (getRole() == SaslRole.CLIENT && - (message == null || message.status == NegotiationStatus.OK)) { + if (getRole() == SaslRole.CLIENT + && (message == null || message.status == NegotiationStatus.OK)) { LOGGER.debug("{}: SASL Client receiving last message", getRole()); message = receiveSaslMessage(); if (message.status != NegotiationStatus.COMPLETE) { - throw new TTransportException( - "Expected SASL COMPLETE, but got " + message.status); + throw new TTransportException("Expected SASL COMPLETE, but got " + message.status); } } } catch (SaslException e) { @@ -293,15 +284,14 @@ abstract class TSaslTransport extends TEndpointTransport { } String qop = (String) sasl.getNegotiatedProperty(Sasl.QOP); - if (qop != null && !qop.equalsIgnoreCase("auth")) - shouldWrap = true; + if (qop != null && !qop.equalsIgnoreCase("auth")) shouldWrap = true; } /** * Get the underlying <code>SaslClient</code>. * - * @return The <code>SaslClient</code>, or <code>null</code> if this transport - * is backed by a <code>SaslServer</code>. + * @return The <code>SaslClient</code>, or <code>null</code> if this transport is backed by a + * <code>SaslServer</code>. */ public SaslClient getSaslClient() { return sasl.saslClient; @@ -309,29 +299,28 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Get the underlying transport that Sasl is using. + * * @return The <code>TTransport</code> transport */ - public TTransport getUnderlyingTransport() { - return underlyingTransport; - } + public TTransport getUnderlyingTransport() { + return underlyingTransport; + } /** * Get the underlying <code>SaslServer</code>. * - * @return The <code>SaslServer</code>, or <code>null</code> if this transport - * is backed by a <code>SaslClient</code>. + * @return The <code>SaslServer</code>, or <code>null</code> if this transport is backed by a + * <code>SaslClient</code>. */ public SaslServer getSaslServer() { return sasl.saslServer; } /** - * Read a 4-byte word from the underlying transport and interpret it as an - * integer. + * Read a 4-byte word from the underlying transport and interpret it as an integer. * * @return The length prefix of the next SASL message to read. - * @throws TTransportException - * Thrown if reading from the underlying transport fails. + * @throws TTransportException Thrown if reading from the underlying transport fails. */ protected int readLength() throws TTransportException { byte[] lenBuf = new byte[4]; @@ -342,10 +331,8 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Write the given integer as 4 bytes to the underlying transport. * - * @param length - * The length prefix of the next SASL message to write. - * @throws TTransportException - * Thrown if writing to the underlying transport fails. + * @param length The length prefix of the next SASL message to write. + * @throws TTransportException Thrown if writing to the underlying transport fails. */ protected void writeLength(int length) throws TTransportException { byte[] lenBuf = new byte[4]; @@ -356,8 +343,8 @@ abstract class TSaslTransport extends TEndpointTransport { // Below is the SASL implementation of the TTransport interface. /** - * Closes the underlying transport and disposes of the SASL implementation - * underlying this transport. + * Closes the underlying transport and disposes of the SASL implementation underlying this + * transport. */ @Override public void close() { @@ -369,23 +356,19 @@ abstract class TSaslTransport extends TEndpointTransport { } } - /** - * True if the underlying transport is open and the SASL handshake is - * complete. - */ + /** True if the underlying transport is open and the SASL handshake is complete. */ @Override public boolean isOpen() { return underlyingTransport.isOpen() && sasl != null && sasl.isComplete(); } /** - * Read from the underlying transport. Unwraps the contents if a QOP was - * negotiated during the SASL handshake. + * Read from the underlying transport. Unwraps the contents if a QOP was negotiated during the + * SASL handshake. */ @Override public int read(byte[] buf, int off, int len) throws TTransportException { - if (!isOpen()) - throw new TTransportException("SASL authentication not complete"); + if (!isOpen()) throw new TTransportException("SASL authentication not complete"); int got = readBuffer.read(buf, off, len); if (got > 0) { @@ -409,13 +392,10 @@ abstract class TSaslTransport extends TEndpointTransport { } /** - * Read a single frame of data from the underlying transport, unwrapping if - * necessary. + * Read a single frame of data from the underlying transport, unwrapping if necessary. * - * @throws TTransportException - * Thrown if there's an error reading from the underlying transport. - * @throws SaslException - * Thrown if there's an error unwrapping the data. + * @throws TTransportException Thrown if there's an error reading from the underlying transport. + * @throws SaslException Thrown if there's an error unwrapping the data. */ private void readFrame() throws TTransportException, SaslException { int dataLength = readLength(); @@ -433,20 +413,17 @@ abstract class TSaslTransport extends TEndpointTransport { readBuffer.reset(buff); } - /** - * Write to the underlying transport. - */ + /** Write to the underlying transport. */ @Override public void write(byte[] buf, int off, int len) throws TTransportException { - if (!isOpen()) - throw new TTransportException("SASL authentication not complete"); + if (!isOpen()) throw new TTransportException("SASL authentication not complete"); writeBuffer.write(buf, off, len); } /** - * Flushes to the underlying transport. Wraps the contents if a QOP was - * negotiated during the SASL handshake. + * Flushes to the underlying transport. Wraps the contents if a QOP was negotiated during the SASL + * handshake. */ @Override public void flush() throws TTransportException { @@ -469,9 +446,7 @@ abstract class TSaslTransport extends TEndpointTransport { underlyingTransport.flush(); } - /** - * Used exclusively by readSaslMessage to return both a status and data. - */ + /** Used exclusively by readSaslMessage to return both a status and data. */ protected static class SaslResponse { public NegotiationStatus status; public byte[] payload; @@ -483,9 +458,8 @@ abstract class TSaslTransport extends TEndpointTransport { } /** - * Used to abstract over the <code>SaslServer</code> and - * <code>SaslClient</code> classes, which share a lot of their interface, but - * unfortunately don't share a common superclass. + * Used to abstract over the <code>SaslServer</code> and <code>SaslClient</code> classes, which + * share a lot of their interface, but unfortunately don't share a common superclass. */ private static class SaslParticipant { // One of these will always be null. @@ -509,38 +483,28 @@ abstract class TSaslTransport extends TEndpointTransport { } public boolean isComplete() { - if (saslClient != null) - return saslClient.isComplete(); - else - return saslServer.isComplete(); + if (saslClient != null) return saslClient.isComplete(); + else return saslServer.isComplete(); } public void dispose() throws SaslException { - if (saslClient != null) - saslClient.dispose(); - else - saslServer.dispose(); + if (saslClient != null) saslClient.dispose(); + else saslServer.dispose(); } public byte[] unwrap(byte[] buf, int off, int len) throws SaslException { - if (saslClient != null) - return saslClient.unwrap(buf, off, len); - else - return saslServer.unwrap(buf, off, len); + if (saslClient != null) return saslClient.unwrap(buf, off, len); + else return saslServer.unwrap(buf, off, len); } public byte[] wrap(byte[] buf, int off, int len) throws SaslException { - if (saslClient != null) - return saslClient.wrap(buf, off, len); - else - return saslServer.wrap(buf, off, len); + if (saslClient != null) return saslClient.wrap(buf, off, len); + else return saslServer.wrap(buf, off, len); } public Object getNegotiatedProperty(String propName) { - if (saslClient != null) - return saslClient.getNegotiatedProperty(propName); - else - return saslServer.getNegotiatedProperty(propName); + if (saslClient != null) return saslClient.getNegotiatedProperty(propName); + else return saslServer.getNegotiatedProperty(propName); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java b/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java index e02d36f6c..6200dadce 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java @@ -19,15 +19,19 @@ package org.apache.thrift.transport; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; public interface TSeekableFile { public InputStream getInputStream() throws IOException; + public OutputStream getOutputStream() throws IOException; + public void close() throws IOException; + public long length() throws IOException; + public void seek(long pos) throws IOException; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java index eb302fd26..e1056623e 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java @@ -19,34 +19,27 @@ package org.apache.thrift.transport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** - * Wrapper around ServerSocket for Thrift. - * - */ +/** Wrapper around ServerSocket for Thrift. */ public class TServerSocket extends TServerTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TServerSocket.class.getName()); - /** - * Underlying ServerSocket object - */ + /** Underlying ServerSocket object */ private ServerSocket serverSocket_ = null; - /** - * Timeout for client sockets from accept - */ + /** Timeout for client sockets from accept */ private int clientTimeout_ = 0; - public static class ServerSocketTransportArgs extends AbstractServerTransportArgs<ServerSocketTransportArgs> { + public static class ServerSocketTransportArgs + extends AbstractServerTransportArgs<ServerSocketTransportArgs> { ServerSocket serverSocket; public ServerSocketTransportArgs serverSocket(ServerSocket serverSocket) { @@ -55,30 +48,22 @@ public class TServerSocket extends TServerTransport { } } - /** - * Creates a server socket from underlying socket object - */ + /** Creates a server socket from underlying socket object */ public TServerSocket(ServerSocket serverSocket) throws TTransportException { this(serverSocket, 0); } - /** - * Creates a server socket from underlying socket object - */ + /** Creates a server socket from underlying socket object */ public TServerSocket(ServerSocket serverSocket, int clientTimeout) throws TTransportException { this(new ServerSocketTransportArgs().serverSocket(serverSocket).clientTimeout(clientTimeout)); } - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TServerSocket(int port) throws TTransportException { this(port, 0); } - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TServerSocket(int port, int clientTimeout) throws TTransportException { this(new InetSocketAddress(port), clientTimeout); } @@ -106,7 +91,8 @@ public class TServerSocket extends TServerTransport { serverSocket_.bind(args.bindAddr, args.backlog); } catch (IOException ioe) { close(); - throw new TTransportException("Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); + throw new TTransportException( + "Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java index 3a7b49a31..47fa2513c 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java @@ -21,16 +21,13 @@ package org.apache.thrift.transport; import java.io.Closeable; import java.net.InetSocketAddress; - import org.apache.thrift.TConfiguration; -/** - * Server transport. Object which provides client transports. - * - */ +/** Server transport. Object which provides client transports. */ public abstract class TServerTransport implements Closeable { - public static abstract class AbstractServerTransportArgs<T extends AbstractServerTransportArgs<T>> { + public abstract static class AbstractServerTransportArgs< + T extends AbstractServerTransportArgs<T>> { int backlog = 0; // A value of 0 means the default value will be used (currently set at 50) int clientTimeout = 0; InetSocketAddress bindAddr; @@ -65,9 +62,9 @@ public abstract class TServerTransport implements Closeable { public abstract void listen() throws TTransportException; /** - * Accept incoming connection on the server socket. When there is no incoming connection available: - * either it should block infinitely in a blocking implementation, either it should return null in - * a nonblocking implementation. + * Accept incoming connection on the server socket. When there is no incoming connection + * available: either it should block infinitely in a blocking implementation, either it should + * return null in a nonblocking implementation. * * @return new connection * @throws TTransportException if IO error. @@ -77,12 +74,10 @@ public abstract class TServerTransport implements Closeable { public abstract void close(); /** - * Optional method implementation. This signals to the server transport - * that it should break out of any accept() or listen() that it is currently - * blocked on. This method, if implemented, MUST be thread safe, as it may - * be called from a different thread context than the other TServerTransport - * methods. + * Optional method implementation. This signals to the server transport that it should break out + * of any accept() or listen() that it is currently blocked on. This method, if implemented, MUST + * be thread safe, as it may be called from a different thread context than the other + * TServerTransport methods. */ public void interrupt() {} - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java index c1bbd4853..9dfdb82d9 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java @@ -18,15 +18,11 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.IOException; import java.io.RandomAccessFile; +import org.apache.thrift.TConfiguration; - -/** - * Basic file support for the TTransport interface - */ +/** Basic file support for the TTransport interface */ public final class TSimpleFileTransport extends TEndpointTransport { private RandomAccessFile file = null; @@ -34,7 +30,6 @@ public final class TSimpleFileTransport extends TEndpointTransport { private boolean writable; private String path_; - /** * Create a transport backed by a simple file * @@ -44,9 +39,8 @@ public final class TSimpleFileTransport extends TEndpointTransport { * @param openFile true to open the file on construction * @throws TTransportException if file open fails */ - public TSimpleFileTransport(String path, boolean read, - boolean write, boolean openFile) - throws TTransportException { + public TSimpleFileTransport(String path, boolean read, boolean write, boolean openFile) + throws TTransportException { this(new TConfiguration(), path, read, write, openFile); } @@ -60,9 +54,9 @@ public final class TSimpleFileTransport extends TEndpointTransport { * @param openFile true to open the file on construction * @throws TTransportException if file open fails */ - public TSimpleFileTransport(TConfiguration config, String path, boolean read, - boolean write, boolean openFile) - throws TTransportException { + public TSimpleFileTransport( + TConfiguration config, String path, boolean read, boolean write, boolean openFile) + throws TTransportException { super(config); if (path.length() <= 0) { throw new TTransportException("No path specified"); @@ -79,22 +73,19 @@ public final class TSimpleFileTransport extends TEndpointTransport { } /** - * Create a transport backed by a simple file - * Implicitly opens file to conform to C++ behavior. + * Create a transport backed by a simple file Implicitly opens file to conform to C++ behavior. * * @param path the path to the file to open/create * @param read true to support read operations * @param write true to support write operations * @throws TTransportException if file open fails */ - public TSimpleFileTransport(String path, boolean read, boolean write) - throws TTransportException { + public TSimpleFileTransport(String path, boolean read, boolean write) throws TTransportException { this(path, read, write, true); } /** - * Create a transport backed by a simple read only disk file (implicitly opens - * file) + * Create a transport backed by a simple read only disk file (implicitly opens file) * * @param path the path to the file to open/create * @throws TTransportException if file open fails @@ -120,9 +111,9 @@ public final class TSimpleFileTransport extends TEndpointTransport { */ @Override public void open() throws TTransportException { - if (file == null){ + if (file == null) { try { - String access = "r"; //RandomAccessFile objects must be readable + String access = "r"; // RandomAccessFile objects must be readable if (writable) { access += "w"; } @@ -134,16 +125,14 @@ public final class TSimpleFileTransport extends TEndpointTransport { } } - /** - * Close file, subsequent read/write activity will throw exceptions - */ + /** Close file, subsequent read/write activity will throw exceptions */ @Override public void close() { if (file != null) { try { file.close(); } catch (Exception e) { - //Nothing to do + // Nothing to do } file = null; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java index aef2a3ff8..558c4fa7e 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java @@ -19,48 +19,34 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; +import org.apache.thrift.TConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** - * Socket implementation of the TTransport interface. To be commented soon! - * - */ +/** Socket implementation of the TTransport interface. To be commented soon! */ public class TSocket extends TIOStreamTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSocket.class.getName()); - /** - * Wrapped Socket object - */ + /** Wrapped Socket object */ private Socket socket_; - /** - * Remote host - */ + /** Remote host */ private String host_; - /** - * Remote port - */ + /** Remote port */ private int port_; - /** - * Socket timeout - read timeout on the socket - */ + /** Socket timeout - read timeout on the socket */ private int socketTimeout_; - /** - * Connection timeout - */ + /** Connection timeout */ private int connectTimeout_; /** @@ -92,10 +78,9 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * - * @param config check config + * @param config check config * @param host Remote host * @param port Remote port */ @@ -104,8 +89,7 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * * @param host Remote host * @param port Remote port @@ -115,11 +99,10 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * - * @param host Remote host - * @param port Remote port + * @param host Remote host + * @param port Remote port * @param timeout Socket timeout and connection timeout */ public TSocket(String host, int port, int timeout) throws TTransportException { @@ -127,30 +110,31 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * - * @param config check config - * @param host Remote host - * @param port Remote port + * @param config check config + * @param host Remote host + * @param port Remote port * @param timeout Socket timeout and connection timeout */ - public TSocket(TConfiguration config, String host, int port, int timeout) throws TTransportException { + public TSocket(TConfiguration config, String host, int port, int timeout) + throws TTransportException { this(config, host, port, timeout, timeout); } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port, with a specific connection timeout and a - * specific socket timeout. + * Creates a new unconnected socket that will connect to the given host on the given port, with a + * specific connection timeout and a specific socket timeout. * - * @param config check config - * @param host Remote host - * @param port Remote port - * @param socketTimeout Socket timeout - * @param connectTimeout Connection timeout + * @param config check config + * @param host Remote host + * @param port Remote port + * @param socketTimeout Socket timeout + * @param connectTimeout Connection timeout */ - public TSocket(TConfiguration config, String host, int port, int socketTimeout, int connectTimeout) throws TTransportException { + public TSocket( + TConfiguration config, String host, int port, int socketTimeout, int connectTimeout) + throws TTransportException { super(config); host_ = host; port_ = port; @@ -159,9 +143,7 @@ public class TSocket extends TIOStreamTransport { initSocket(); } - /** - * Initializes the socket object - */ + /** Initializes the socket object */ private void initSocket() { socket_ = new Socket(); try { @@ -207,9 +189,7 @@ public class TSocket extends TIOStreamTransport { } } - /** - * Returns a reference to the underlying socket. - */ + /** Returns a reference to the underlying socket. */ public Socket getSocket() { if (socket_ == null) { initSocket(); @@ -217,9 +197,7 @@ public class TSocket extends TIOStreamTransport { return socket_; } - /** - * Checks whether the socket is connected. - */ + /** Checks whether the socket is connected. */ public boolean isOpen() { if (socket_ == null) { return false; @@ -227,9 +205,7 @@ public class TSocket extends TIOStreamTransport { return socket_.isConnected(); } - /** - * Connects the socket, creating a new socket object if necessary. - */ + /** Connects the socket, creating a new socket object if necessary. */ public void open() throws TTransportException { if (isOpen()) { throw new TTransportException(TTransportException.ALREADY_OPEN, "Socket already connected."); @@ -256,9 +232,7 @@ public class TSocket extends TIOStreamTransport { } } - /** - * Closes the socket. - */ + /** Closes the socket. */ public void close() { // Close the underlying streams super.close(); @@ -273,5 +247,4 @@ public class TSocket extends TIOStreamTransport { socket_ = null; } } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java b/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java index 7a33af8ee..65c29a502 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java @@ -19,12 +19,12 @@ package org.apache.thrift.transport; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; import java.io.RandomAccessFile; -import java.io.FileInputStream; -import java.io.FileOutputStream; public class TStandardFile implements TSeekableFile { @@ -45,7 +45,7 @@ public class TStandardFile implements TSeekableFile { } public void close() throws IOException { - if(inputFile_ != null) { + if (inputFile_ != null) { inputFile_.close(); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java index afe9cfb88..dc771fc58 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java @@ -19,15 +19,13 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.Closeable; import java.nio.ByteBuffer; +import org.apache.thrift.TConfiguration; /** - * Generic class that encapsulates the I/O layer. This is basically a thin - * wrapper around the combined functionality of Java input/output streams. - * + * Generic class that encapsulates the I/O layer. This is basically a thin wrapper around the + * combined functionality of Java input/output streams. */ public abstract class TTransport implements Closeable { @@ -52,25 +50,20 @@ public abstract class TTransport implements Closeable { * * @throws TTransportException if the transport could not be opened */ - public abstract void open() - throws TTransportException; + public abstract void open() throws TTransportException; - /** - * Closes the transport. - */ + /** Closes the transport. */ public abstract void close(); /** - * Reads a sequence of bytes from this channel into the given buffer. An - * attempt is made to read up to the number of bytes remaining in the buffer, - * that is, dst.remaining(), at the moment this method is invoked. Upon return - * the buffer's position will move forward the number of bytes read; its limit - * will not have changed. Subclasses are encouraged to provide a more - * efficient implementation of this method. + * Reads a sequence of bytes from this channel into the given buffer. An attempt is made to read + * up to the number of bytes remaining in the buffer, that is, dst.remaining(), at the moment this + * method is invoked. Upon return the buffer's position will move forward the number of bytes + * read; its limit will not have changed. Subclasses are encouraged to provide a more efficient + * implementation of this method. * * @param dst The buffer into which bytes are to be transferred - * @return The number of bytes read, possibly zero, or -1 if the channel has - * reached end-of-stream + * @return The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream * @throws TTransportException if there was an error reading data */ public int read(ByteBuffer dst) throws TTransportException { @@ -89,8 +82,7 @@ public abstract class TTransport implements Closeable { * @return The number of bytes actually read * @throws TTransportException if there was an error reading data */ - public abstract int read(byte[] buf, int off, int len) - throws TTransportException; + public abstract int read(byte[] buf, int off, int len) throws TTransportException; /** * Guarantees that all of len bytes are actually read off the transport. @@ -101,12 +93,11 @@ public abstract class TTransport implements Closeable { * @return The number of bytes actually read, which must be equal to len * @throws TTransportException if there was an error reading data */ - public int readAll(byte[] buf, int off, int len) - throws TTransportException { + public int readAll(byte[] buf, int off, int len) throws TTransportException { int got = 0; int ret = 0; while (got < len) { - ret = read(buf, off+got, len-got); + ret = read(buf, off + got, len - got); if (ret <= 0) { throw new TTransportException( "Cannot read. Remote side has closed. Tried to read " @@ -138,15 +129,13 @@ public abstract class TTransport implements Closeable { * @param len The number of bytes to write * @throws TTransportException if there was an error writing data */ - public abstract void write(byte[] buf, int off, int len) - throws TTransportException; + public abstract void write(byte[] buf, int off, int len) throws TTransportException; /** - * Writes a sequence of bytes to the buffer. An attempt is made to write all - * remaining bytes in the buffer, that is, src.remaining(), at the moment this - * method is invoked. Upon return the buffer's position will updated; its limit - * will not have changed. Subclasses are encouraged to provide a more efficient - * implementation of this method. + * Writes a sequence of bytes to the buffer. An attempt is made to write all remaining bytes in + * the buffer, that is, src.remaining(), at the moment this method is invoked. Upon return the + * buffer's position will updated; its limit will not have changed. Subclasses are encouraged to + * provide a more efficient implementation of this method. * * @param src The buffer from which bytes are to be retrieved * @return The number of bytes written, possibly zero @@ -164,12 +153,12 @@ public abstract class TTransport implements Closeable { * * @throws TTransportException if there was an error writing out data. */ - public void flush() - throws TTransportException {} + public void flush() throws TTransportException {} /** - * Access the protocol's underlying buffer directly. If this is not a - * buffered transport, return null. + * Access the protocol's underlying buffer directly. If this is not a buffered transport, return + * null. + * * @return protocol's Underlying buffer */ public byte[] getBuffer() { @@ -177,20 +166,22 @@ public abstract class TTransport implements Closeable { } /** - * Return the index within the underlying buffer that specifies the next spot - * that should be read from. - * @return index within the underlying buffer that specifies the next spot - * that should be read from + * Return the index within the underlying buffer that specifies the next spot that should be read + * from. + * + * @return index within the underlying buffer that specifies the next spot that should be read + * from */ public int getBufferPosition() { return 0; } /** - * Get the number of bytes remaining in the underlying buffer. Returns -1 if - * this is a non-buffered transport. - * @return the number of bytes remaining in the underlying buffer. <br> Returns -1 if - * this is a non-buffered transport. + * Get the number of bytes remaining in the underlying buffer. Returns -1 if this is a + * non-buffered transport. + * + * @return the number of bytes remaining in the underlying buffer. <br> + * Returns -1 if this is a non-buffered transport. */ public int getBytesRemainingInBuffer() { return -1; @@ -198,6 +189,7 @@ public abstract class TTransport implements Closeable { /** * Consume len bytes from the underlying buffer. + * * @param len the number of bytes to consume from the underlying buffer. */ public void consumeBuffer(int len) {} diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java b/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java index b886bc269..cc7532f2a 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java @@ -21,10 +21,7 @@ package org.apache.thrift.transport; import org.apache.thrift.TException; -/** - * Transport exceptions. - * - */ +/** Transport exceptions. */ public class TTransportException extends TException { private static final long serialVersionUID = 1L; @@ -77,5 +74,4 @@ public class TTransportException extends TException { public int getType() { return type_; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java b/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java index e068b4beb..ded5be432 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java @@ -20,11 +20,9 @@ package org.apache.thrift.transport; /** - * Factory class used to create wrapped instance of Transports. - * This is used primarily in servers, which get Transports from - * a ServerTransport and then may want to mutate them (i.e. create - * a BufferedTransport from the underlying base transport) - * + * Factory class used to create wrapped instance of Transports. This is used primarily in servers, + * which get Transports from a ServerTransport and then may want to mutate them (i.e. create a + * BufferedTransport from the underlying base transport) */ public class TTransportFactory { @@ -37,5 +35,4 @@ public class TTransportFactory { public TTransport getTransport(TTransport trans) throws TTransportException { return trans; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java index 73b21aa3f..e0b5b90b5 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java @@ -18,8 +18,6 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,125 +26,129 @@ import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; +import org.apache.thrift.TConfiguration; -/** - * TZlibTransport deflates on write and inflates on read. - */ +/** TZlibTransport deflates on write and inflates on read. */ public class TZlibTransport extends TIOStreamTransport { - private TTransport transport_ = null; - - public static class Factory extends TTransportFactory { - public Factory() { - } - - @Override - public TTransport getTransport(TTransport base) throws TTransportException { - return new TZlibTransport(base); - } - } + private TTransport transport_ = null; - /** - * Constructs a new TZlibTransport instance. - * @param transport the underlying transport to read from and write to - */ - public TZlibTransport(TTransport transport) throws TTransportException { - this(transport, Deflater.BEST_COMPRESSION); - } - - /** - * Constructs a new TZlibTransport instance. - * @param transport the underlying transport to read from and write to - * @param compressionLevel 0 for no compression, 9 for maximum compression - */ - public TZlibTransport(TTransport transport, int compressionLevel) throws TTransportException { - super(Objects.isNull(transport.getConfiguration()) ? new TConfiguration() : transport.getConfiguration()); - transport_ = transport; - inputStream_ = new InflaterInputStream(new TTransportInputStream(transport_), new Inflater()); - outputStream_ = new DeflaterOutputStream(new TTransportOutputStream(transport_), new Deflater(compressionLevel, false), true); - } - - @Override - public boolean isOpen() { - return transport_.isOpen(); - } + public static class Factory extends TTransportFactory { + public Factory() {} @Override - public void open() throws TTransportException { - transport_.open(); + public TTransport getTransport(TTransport base) throws TTransportException { + return new TZlibTransport(base); } - - @Override - public void close() { - super.close(); - if (transport_.isOpen()) { - transport_.close(); - } + } + + /** + * Constructs a new TZlibTransport instance. + * + * @param transport the underlying transport to read from and write to + */ + public TZlibTransport(TTransport transport) throws TTransportException { + this(transport, Deflater.BEST_COMPRESSION); + } + + /** + * Constructs a new TZlibTransport instance. + * + * @param transport the underlying transport to read from and write to + * @param compressionLevel 0 for no compression, 9 for maximum compression + */ + public TZlibTransport(TTransport transport, int compressionLevel) throws TTransportException { + super( + Objects.isNull(transport.getConfiguration()) + ? new TConfiguration() + : transport.getConfiguration()); + transport_ = transport; + inputStream_ = new InflaterInputStream(new TTransportInputStream(transport_), new Inflater()); + outputStream_ = + new DeflaterOutputStream( + new TTransportOutputStream(transport_), new Deflater(compressionLevel, false), true); + } + + @Override + public boolean isOpen() { + return transport_.isOpen(); + } + + @Override + public void open() throws TTransportException { + transport_.open(); + } + + @Override + public void close() { + super.close(); + if (transport_.isOpen()) { + transport_.close(); } + } } class TTransportInputStream extends InputStream { - private TTransport transport = null; + private TTransport transport = null; - public TTransportInputStream(TTransport transport) { - this.transport = transport; - } + public TTransportInputStream(TTransport transport) { + this.transport = transport; + } - @Override - public int read() throws IOException { - try { - byte[] buf = new byte[1]; - transport.read(buf, 0, 1); - return buf[0]; - } catch (TTransportException e) { - throw new IOException(e); - } + @Override + public int read() throws IOException { + try { + byte[] buf = new byte[1]; + transport.read(buf, 0, 1); + return buf[0]; + } catch (TTransportException e) { + throw new IOException(e); } - - @Override - public int read(byte b[], int off, int len) throws IOException { - try { - return transport.read(b, off, len); - } catch (TTransportException e) { - throw new IOException(e); - } + } + + @Override + public int read(byte b[], int off, int len) throws IOException { + try { + return transport.read(b, off, len); + } catch (TTransportException e) { + throw new IOException(e); } + } } class TTransportOutputStream extends OutputStream { - private TTransport transport = null; + private TTransport transport = null; - public TTransportOutputStream(TTransport transport) { - this.transport = transport; - } + public TTransportOutputStream(TTransport transport) { + this.transport = transport; + } - @Override - public void write(final int b) throws IOException { - try { - transport.write(new byte[]{(byte) b}); - } catch (TTransportException e) { - throw new IOException(e); - } + @Override + public void write(final int b) throws IOException { + try { + transport.write(new byte[] {(byte) b}); + } catch (TTransportException e) { + throw new IOException(e); } - - @Override - public void write(byte b[], int off, int len) throws IOException { - try { - transport.write(b, off, len); - } catch (TTransportException e) { - throw new IOException(e); - } + } + + @Override + public void write(byte b[], int off, int len) throws IOException { + try { + transport.write(b, off, len); + } catch (TTransportException e) { + throw new IOException(e); } - - @Override - public void flush() throws IOException { - try { - transport.flush(); - } catch (TTransportException e) { - throw new IOException(e); - } + } + + @Override + public void flush() throws IOException { + try { + transport.flush(); + } catch (TTransportException e) { + throw new IOException(e); } + } } - diff --git a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java index 29bf39c14..45f4e97ee 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java @@ -18,20 +18,17 @@ */ package org.apache.thrift.transport.layered; - +import java.util.Objects; import org.apache.thrift.TConfiguration; import org.apache.thrift.transport.*; -import java.util.Objects; - /** - * This transport is wire compatible with {@link TFramedTransport}, but makes - * use of reusable, expanding read and write buffers in order to avoid - * allocating new byte[]s all the time. Since the buffers only expand, you - * should probably only use this transport if your messages are not too variably - * large, unless the persistent memory cost is not an issue. + * This transport is wire compatible with {@link TFramedTransport}, but makes use of reusable, + * expanding read and write buffers in order to avoid allocating new byte[]s all the time. Since the + * buffers only expand, you should probably only use this transport if your messages are not too + * variably large, unless the persistent memory cost is not an issue. * - * This implementation is NOT threadsafe. + * <p>This implementation is NOT threadsafe. */ public class TFastFramedTransport extends TLayeredTransport { @@ -54,15 +51,11 @@ public class TFastFramedTransport extends TLayeredTransport { @Override public TTransport getTransport(TTransport trans) throws TTransportException { - return new TFastFramedTransport(trans, - initialCapacity, - maxLength); + return new TFastFramedTransport(trans, initialCapacity, maxLength); } } - /** - * How big should the default read and write buffers be? - */ + /** How big should the default read and write buffers be? */ public static final int DEFAULT_BUF_CAPACITY = 1024; private final AutoExpandingBufferWriteTransport writeBuffer; @@ -72,8 +65,9 @@ public class TFastFramedTransport extends TLayeredTransport { private final int maxLength; /** - * Create a new {@link TFastFramedTransport}. Use the defaults - * for initial buffer size and max frame length. + * Create a new {@link TFastFramedTransport}. Use the defaults for initial buffer size and max + * frame length. + * * @param underlying Transport that real reads and writes will go through to. */ public TFastFramedTransport(TTransport underlying) throws TTransportException { @@ -81,31 +75,35 @@ public class TFastFramedTransport extends TLayeredTransport { } /** - * Create a new {@link TFastFramedTransport}. Use the specified - * initial buffer capacity and the default max frame length. + * Create a new {@link TFastFramedTransport}. Use the specified initial buffer capacity and the + * default max frame length. + * * @param underlying Transport that real reads and writes will go through to. - * @param initialBufferCapacity The initial size of the read and write buffers. - * In practice, it's not critical to set this unless you know in advance that - * your messages are going to be very large. + * @param initialBufferCapacity The initial size of the read and write buffers. In practice, it's + * not critical to set this unless you know in advance that your messages are going to be very + * large. */ - public TFastFramedTransport(TTransport underlying, int initialBufferCapacity) throws TTransportException { + public TFastFramedTransport(TTransport underlying, int initialBufferCapacity) + throws TTransportException { this(underlying, initialBufferCapacity, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } /** - * * @param underlying Transport that real reads and writes will go through to. - * @param initialBufferCapacity The initial size of the read and write buffers. - * In practice, it's not critical to set this unless you know in advance that - * your messages are going to be very large. (You can pass - * TFramedTransportWithReusableBuffer.DEFAULT_BUF_CAPACITY if you're only - * using this constructor because you want to set the maxLength.) - * @param maxLength The max frame size you are willing to read. You can use - * this parameter to limit how much memory can be allocated. + * @param initialBufferCapacity The initial size of the read and write buffers. In practice, it's + * not critical to set this unless you know in advance that your messages are going to be very + * large. (You can pass TFramedTransportWithReusableBuffer.DEFAULT_BUF_CAPACITY if you're only + * using this constructor because you want to set the maxLength.) + * @param maxLength The max frame size you are willing to read. You can use this parameter to + * limit how much memory can be allocated. */ - public TFastFramedTransport(TTransport underlying, int initialBufferCapacity, int maxLength) throws TTransportException { + public TFastFramedTransport(TTransport underlying, int initialBufferCapacity, int maxLength) + throws TTransportException { super(underlying); - TConfiguration config = Objects.isNull(underlying.getConfiguration()) ? new TConfiguration() : underlying.getConfiguration(); + TConfiguration config = + Objects.isNull(underlying.getConfiguration()) + ? new TConfiguration() + : underlying.getConfiguration(); this.maxLength = maxLength; config.setMaxFrameSize(maxLength); this.initialBufferCapacity = initialBufferCapacity; @@ -142,17 +140,19 @@ public class TFastFramedTransport extends TLayeredTransport { } private void readFrame() throws TTransportException { - getInnerTransport().readAll(i32buf , 0, 4); + getInnerTransport().readAll(i32buf, 0, 4); int size = TFramedTransport.decodeFrameSize(i32buf); if (size < 0) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); + throw new TTransportException( + TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); } if (size > getInnerTransport().getConfiguration().getMaxFrameSize()) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, + throw new TTransportException( + TTransportException.CORRUPTED_DATA, "Frame size (" + size + ") larger than max length (" + maxLength + ")!"); } @@ -169,9 +169,7 @@ public class TFastFramedTransport extends TLayeredTransport { readBuffer.consumeBuffer(len); } - /** - * Only clears the read buffer! - */ + /** Only clears the read buffer! */ public void clear() throws TTransportException { readBuffer = new AutoExpandingBufferReadTransport(getConfiguration(), initialBufferCapacity); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java index 10a9a1c17..6ba40187b 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java @@ -19,6 +19,7 @@ package org.apache.thrift.transport.layered; +import java.util.Objects; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; import org.apache.thrift.transport.TMemoryInputTransport; @@ -26,23 +27,16 @@ import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TTransportFactory; -import java.util.Objects; - /** - * TFramedTransport is a buffered TTransport that ensures a fully read message - * every time by preceding messages with a 4-byte frame size. + * TFramedTransport is a buffered TTransport that ensures a fully read message every time by + * preceding messages with a 4-byte frame size. */ public class TFramedTransport extends TLayeredTransport { - /** - * Buffer for output - */ - private final TByteArrayOutputStream writeBuffer_ = - new TByteArrayOutputStream(1024); + /** Buffer for output */ + private final TByteArrayOutputStream writeBuffer_ = new TByteArrayOutputStream(1024); - /** - * Buffer for input - */ + /** Buffer for input */ private final TMemoryInputTransport readBuffer_; public static class Factory extends TTransportFactory { @@ -63,21 +57,21 @@ public class TFramedTransport extends TLayeredTransport { } /** - * Something to fill in the first four bytes of the buffer - * to make room for the frame size. This allows the - * implementation to write once instead of twice. + * Something to fill in the first four bytes of the buffer to make room for the frame size. This + * allows the implementation to write once instead of twice. */ - private static final byte[] sizeFiller_ = new byte[] { 0x00, 0x00, 0x00, 0x00 }; + private static final byte[] sizeFiller_ = new byte[] {0x00, 0x00, 0x00, 0x00}; - /** - * Constructor wraps around another transport - */ + /** Constructor wraps around another transport */ public TFramedTransport(TTransport transport, int maxLength) throws TTransportException { super(transport); - TConfiguration _configuration = Objects.isNull(transport.getConfiguration()) ? new TConfiguration() : transport.getConfiguration(); + TConfiguration _configuration = + Objects.isNull(transport.getConfiguration()) + ? new TConfiguration() + : transport.getConfiguration(); _configuration.setMaxFrameSize(maxLength); writeBuffer_.write(sizeFiller_, 0, 4); - readBuffer_= new TMemoryInputTransport(_configuration, new byte[0]); + readBuffer_ = new TMemoryInputTransport(_configuration, new byte[0]); } public TFramedTransport(TTransport transport) throws TTransportException { @@ -140,13 +134,19 @@ public class TFramedTransport extends TLayeredTransport { if (size < 0) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); + throw new TTransportException( + TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); } if (size > getInnerTransport().getConfiguration().getMaxFrameSize()) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, - "Frame size (" + size + ") larger than max length (" + getInnerTransport().getConfiguration().getMaxFrameSize() + ")!"); + throw new TTransportException( + TTransportException.CORRUPTED_DATA, + "Frame size (" + + size + + ") larger than max length (" + + getInnerTransport().getConfiguration().getMaxFrameSize() + + ")!"); } byte[] buff = new byte[size]; @@ -161,27 +161,26 @@ public class TFramedTransport extends TLayeredTransport { @Override public void flush() throws TTransportException { byte[] buf = writeBuffer_.get(); - int len = writeBuffer_.len() - 4; // account for the prepended frame size + int len = writeBuffer_.len() - 4; // account for the prepended frame size writeBuffer_.reset(); - writeBuffer_.write(sizeFiller_, 0, 4); // make room for the next frame's size data + writeBuffer_.write(sizeFiller_, 0, 4); // make room for the next frame's size data - encodeFrameSize(len, buf); // this is the frame length without the filler - getInnerTransport().write(buf, 0, len + 4); // we have to write the frame size and frame data + encodeFrameSize(len, buf); // this is the frame length without the filler + getInnerTransport().write(buf, 0, len + 4); // we have to write the frame size and frame data getInnerTransport().flush(); } public static final void encodeFrameSize(final int frameSize, final byte[] buf) { - buf[0] = (byte)(0xff & (frameSize >> 24)); - buf[1] = (byte)(0xff & (frameSize >> 16)); - buf[2] = (byte)(0xff & (frameSize >> 8)); - buf[3] = (byte)(0xff & (frameSize)); + buf[0] = (byte) (0xff & (frameSize >> 24)); + buf[1] = (byte) (0xff & (frameSize >> 16)); + buf[2] = (byte) (0xff & (frameSize >> 8)); + buf[3] = (byte) (0xff & (frameSize)); } public static final int decodeFrameSize(final byte[] buf) { - return - ((buf[0] & 0xff) << 24) | - ((buf[1] & 0xff) << 16) | - ((buf[2] & 0xff) << 8) | - ((buf[3] & 0xff)); + return ((buf[0] & 0xff) << 24) + | ((buf[1] & 0xff) << 16) + | ((buf[2] & 0xff) << 8) + | ((buf[3] & 0xff)); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java index 69ec824ee..6e3d1964d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java @@ -18,35 +18,33 @@ */ package org.apache.thrift.transport.layered; +import java.util.Objects; import org.apache.thrift.TConfiguration; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; -import java.util.Objects; - -public abstract class TLayeredTransport extends TTransport{ +public abstract class TLayeredTransport extends TTransport { - private TTransport innerTransport; + private TTransport innerTransport; - public TConfiguration getConfiguration() { - return innerTransport.getConfiguration(); - } + public TConfiguration getConfiguration() { + return innerTransport.getConfiguration(); + } - public TLayeredTransport(TTransport transport) - { - Objects.requireNonNull(transport, "TTransport cannot be null."); - innerTransport = transport; - } + public TLayeredTransport(TTransport transport) { + Objects.requireNonNull(transport, "TTransport cannot be null."); + innerTransport = transport; + } - public void updateKnownMessageSize(long size) throws TTransportException { - innerTransport.updateKnownMessageSize(size); - } + public void updateKnownMessageSize(long size) throws TTransportException { + innerTransport.updateKnownMessageSize(size); + } - public void checkReadBytesAvailable(long numBytes) throws TTransportException { - innerTransport.checkReadBytesAvailable(numBytes); - } + public void checkReadBytesAvailable(long numBytes) throws TTransportException { + innerTransport.checkReadBytesAvailable(numBytes); + } - public TTransport getInnerTransport() { - return innerTransport; - } + public TTransport getInnerTransport() { + return innerTransport; + } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java index 2900df9c1..399ccc62d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * The header for data frame, it only contains a 4-byte payload size. - */ +/** The header for data frame, it only contains a 4-byte payload size. */ public class DataFrameHeaderReader extends FixedSizeHeaderReader { public static final int PAYLOAD_LENGTH_BYTES = 4; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java index e6900bbc6..cd5c002fa 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * Frames for thrift (serialized) messages. - */ +/** Frames for thrift (serialized) messages. */ public class DataFrameReader extends FrameReader<DataFrameHeaderReader> { public DataFrameReader() { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java index a2dd15a8c..b79537dd8 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java @@ -19,34 +19,43 @@ package org.apache.thrift.transport.sasl; -import java.nio.ByteBuffer; +import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; +import java.nio.ByteBuffer; import org.apache.thrift.EncodingUtils; import org.apache.thrift.utils.StringUtils; -import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; - /** - * Write frames of thrift messages. It expects an empty/null header to be provided with a payload - * to be written out. Non empty headers are considered as error. + * Write frames of thrift messages. It expects an empty/null header to be provided with a payload to + * be written out. Non empty headers are considered as error. */ public class DataFrameWriter extends FrameWriter { @Override public void withOnlyPayload(byte[] payload, int offset, int length) { if (!isComplete()) { - throw new IllegalStateException("Previsous write is not yet complete, with " + - frameBytes.remaining() + " bytes left."); + throw new IllegalStateException( + "Previsous write is not yet complete, with " + frameBytes.remaining() + " bytes left."); } frameBytes = buildFrameWithPayload(payload, offset, length); } @Override - protected ByteBuffer buildFrame(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength) { + protected ByteBuffer buildFrame( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength) { if (header != null && headerLength > 0) { - throw new IllegalArgumentException("Extra header [" + StringUtils.bytesToHexString(header) + - "] offset " + payloadOffset + " length " + payloadLength); + throw new IllegalArgumentException( + "Extra header [" + + StringUtils.bytesToHexString(header) + + "] offset " + + payloadOffset + + " length " + + payloadLength); } return buildFrameWithPayload(payload, payloadOffset, payloadLength); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java index 1cbc0ace0..4f90faf85 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java @@ -19,15 +19,12 @@ package org.apache.thrift.transport.sasl; +import java.nio.ByteBuffer; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.utils.StringUtils; -import java.nio.ByteBuffer; - -/** - * Headers' size should be predefined. - */ +/** Headers' size should be predefined. */ public abstract class FixedSizeHeaderReader implements FrameHeaderReader { protected final ByteBuffer byteBuffer = ByteBuffer.allocate(headerSize()); @@ -45,7 +42,9 @@ public abstract class FixedSizeHeaderReader implements FrameHeaderReader { @Override public byte[] toBytes() { if (!isComplete()) { - throw new IllegalStateException("Header is not yet complete " + StringUtils.bytesToHexString(byteBuffer.array(), 0, byteBuffer.position())); + throw new IllegalStateException( + "Header is not yet complete " + + StringUtils.bytesToHexString(byteBuffer.array(), 0, byteBuffer.position())); } return byteBuffer.array(); } @@ -60,9 +59,7 @@ public abstract class FixedSizeHeaderReader implements FrameHeaderReader { return true; } - /** - * @return Size of the header. - */ + /** @return Size of the header. */ protected abstract int headerSize(); /** diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java index f7c659315..d618346a4 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java @@ -36,20 +36,15 @@ public interface FrameHeaderReader { int payloadSize(); /** - * * @return The received bytes for the header. * @throws IllegalStateException if isComplete returns false. */ byte[] toBytes(); - /** - * @return true if this header has all its fields set. - */ + /** @return true if this header has all its fields set. */ boolean isComplete(); - /** - * Clear the header and make it available to read a new header. - */ + /** Clear the header and make it available to read a new header. */ void clear(); /** diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java index acb4b738d..1f5872c30 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java @@ -19,16 +19,15 @@ package org.apache.thrift.transport.sasl; +import java.nio.ByteBuffer; import org.apache.thrift.transport.TEOFException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; -import java.nio.ByteBuffer; - /** - * Read frames from a transport. Each frame has a header and a payload. A header will indicate - * the size of the payload and other informations about how to decode payload. - * Implementations should subclass it by providing a header reader implementation. + * Read frames from a transport. Each frame has a header and a payload. A header will indicate the + * size of the payload and other informations about how to decode payload. Implementations should + * subclass it by providing a header reader implementation. * * @param <T> Header type. */ @@ -70,7 +69,8 @@ public abstract class FrameReader<T extends FrameHeaderReader> { * @throws TSaslNegotiationException if fail to read back a validd sasl negotiation header. * @throws TTransportException if io error. */ - private boolean readHeader(TTransport transport) throws TSaslNegotiationException, TTransportException { + private boolean readHeader(TTransport transport) + throws TSaslNegotiationException, TTransportException { return header.read(transport); } @@ -86,49 +86,32 @@ public abstract class FrameReader<T extends FrameHeaderReader> { return payload.hasRemaining(); } - /** - * - * @return header of the frame - */ + /** @return header of the frame */ public T getHeader() { return header; } - /** - * - * @return number of bytes of the header - */ + /** @return number of bytes of the header */ public int getHeaderSize() { return header.toBytes().length; } - /** - * - * @return byte array of the payload - */ + /** @return byte array of the payload */ public byte[] getPayload() { return payload.array(); } - /** - * - * @return size of the payload - */ + /** @return size of the payload */ public int getPayloadSize() { return header.payloadSize(); } - /** - * - * @return true if the reader has fully read a frame - */ + /** @return true if the reader has fully read a frame */ public boolean isComplete() { return !(payload == null || payload.hasRemaining()); } - /** - * Reset the state of the reader so that it can be reused to read a new frame. - */ + /** Reset the state of the reader so that it can be reused to read a new frame. */ public void clear() { header.clear(); payload = null; @@ -144,8 +127,8 @@ public abstract class FrameReader<T extends FrameHeaderReader> { */ static int readAvailable(TTransport transport, ByteBuffer recipient) throws TTransportException { if (!recipient.hasRemaining()) { - throw new IllegalStateException("Trying to fill a full recipient with " + recipient.limit() - + " bytes"); + throw new IllegalStateException( + "Trying to fill a full recipient with " + recipient.limit() + " bytes"); } int currentPosition = recipient.position(); byte[] bytes = recipient.array(); @@ -153,8 +136,8 @@ public abstract class FrameReader<T extends FrameHeaderReader> { int expectedLength = recipient.remaining(); int got = transport.read(bytes, offset, expectedLength); if (got < 0) { - throw new TEOFException("Transport is closed, while trying to read " + expectedLength + - " bytes"); + throw new TEOFException( + "Transport is closed, while trying to read " + expectedLength + " bytes"); } recipient.position(currentPosition + got); return got; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java index 4357f13e1..bae6d4999 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java @@ -19,15 +19,11 @@ package org.apache.thrift.transport.sasl; -import java.io.IOException; import java.nio.ByteBuffer; - import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransportException; -/** - * Write frame (header and payload) to transport in a nonblocking way. - */ +/** Write frame (header and payload) to transport in a nonblocking way. */ public abstract class FrameWriter { protected ByteBuffer frameBytes; @@ -37,7 +33,7 @@ public abstract class FrameWriter { * returns true (last frame has been written out). * * @param header Some extra header bytes (without the 4 bytes for payload length), which will be - * the start of the frame. It can be empty, depending on the message format + * the start of the frame. It can be empty, depending on the message format * @param payload Payload as a byte array * @throws IllegalStateException if it is called when isComplete returns false * @throws IllegalArgumentException if header or payload is invalid @@ -65,18 +61,24 @@ public abstract class FrameWriter { * @throws IllegalStateException if preivous frame is not yet complete (isComplete returns fals) * @throws IllegalArgumentException if header or payload is invalid */ - public void withHeaderAndPayload(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength) { + public void withHeaderAndPayload( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength) { if (!isComplete()) { - throw new IllegalStateException("Previsous write is not yet complete, with " + - frameBytes.remaining() + " bytes left."); + throw new IllegalStateException( + "Previsous write is not yet complete, with " + frameBytes.remaining() + " bytes left."); } - frameBytes = buildFrame(header, headerOffset, headerLength, payload, payloadOffset, payloadLength); + frameBytes = + buildFrame(header, headerOffset, headerLength, payload, payloadOffset, payloadLength); } /** - * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects - * a header. + * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects a + * header. * * @param payload payload as a byte array */ @@ -85,8 +87,8 @@ public abstract class FrameWriter { } /** - * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects - * a header. + * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects a + * header. * * @param payload The underlying byte array as a recipient of the payload * @param offset The offset in the byte array starting from where the payload is located @@ -94,8 +96,13 @@ public abstract class FrameWriter { */ public abstract void withOnlyPayload(byte[] payload, int offset, int length); - protected abstract ByteBuffer buildFrame(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength); + protected abstract ByteBuffer buildFrame( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength); /** * Nonblocking write to the underlying transport. @@ -106,17 +113,12 @@ public abstract class FrameWriter { transport.write(frameBytes); } - /** - * - * @return true when no more data needs to be written out - */ + /** @return true when no more data needs to be written out */ public boolean isComplete() { return frameBytes == null || !frameBytes.hasRemaining(); } - /** - * Release the byte buffer. - */ + /** Release the byte buffer. */ public void clear() { frameBytes = null; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java index ad704a0a1..9b0ddcba0 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java @@ -19,20 +19,18 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; + import java.util.HashMap; import java.util.Map; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; - -/** - * Status bytes used during the initial Thrift SASL handshake. - */ +/** Status bytes used during the initial Thrift SASL handshake. */ public enum NegotiationStatus { - START((byte)0x01), - OK((byte)0x02), - BAD((byte)0x03), - ERROR((byte)0x04), - COMPLETE((byte)0x05); + START((byte) 0x01), + OK((byte) 0x02), + BAD((byte) 0x03), + ERROR((byte) 0x04), + COMPLETE((byte) 0x05); private static final Map<Byte, NegotiationStatus> reverseMap = new HashMap<>(); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java index d73c3ec18..2557a4285 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java @@ -19,11 +19,12 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.NegotiationStatus.COMPLETE; +import static org.apache.thrift.transport.sasl.NegotiationStatus.OK; + import java.nio.channels.SelectionKey; import java.nio.charset.StandardCharsets; - import javax.security.sasl.SaslServer; - import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -37,12 +38,7 @@ import org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.thrift.transport.sasl.NegotiationStatus.COMPLETE; -import static org.apache.thrift.transport.sasl.NegotiationStatus.OK; - -/** - * State machine managing one sasl connection in a nonblocking way. - */ +/** State machine managing one sasl connection in a nonblocking way. */ public class NonblockingSaslHandler { private static final Logger LOGGER = LoggerFactory.getLogger(NonblockingSaslHandler.class); @@ -86,10 +82,14 @@ public class NonblockingSaslHandler { // If sasl is negotiated for integrity/confidentiality protection private boolean dataProtected; - public NonblockingSaslHandler(SelectionKey selectionKey, TNonblockingTransport underlyingTransport, - TSaslServerFactory saslServerFactory, TSaslProcessorFactory processorFactory, - TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, - TServerEventHandler eventHandler) { + public NonblockingSaslHandler( + SelectionKey selectionKey, + TNonblockingTransport underlyingTransport, + TSaslServerFactory saslServerFactory, + TSaslProcessorFactory processorFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + TServerEventHandler eventHandler) { this.selectionKey = selectionKey; this.underlyingTransport = underlyingTransport; this.saslServerFactory = saslServerFactory; @@ -114,8 +114,8 @@ public class NonblockingSaslHandler { } /** - * Get next phase of the state machine. - * It is different from current phase iff current phase is done (and next phase not yet started). + * Get next phase of the state machine. It is different from current phase iff current phase is + * done (and next phase not yet started). * * @return next phase. */ @@ -123,26 +123,17 @@ public class NonblockingSaslHandler { return nextPhase; } - /** - * - * @return underlying nonblocking socket - */ + /** @return underlying nonblocking socket */ public TNonblockingTransport getUnderlyingTransport() { return underlyingTransport; } - /** - * - * @return SaslServer instance - */ + /** @return SaslServer instance */ public SaslServer getSaslServer() { return saslPeer.getSaslServer(); } - /** - * - * @return true if current phase is done. - */ + /** @return true if current phase is done. */ public boolean isCurrentPhaseDone() { return currentPhase != nextPhase; } @@ -178,8 +169,8 @@ public class NonblockingSaslHandler { private void handleOps(int interestOps) { if (currentPhase.selectionInterest != interestOps) { - throw new IllegalStateException("Current phase " + currentPhase + " but got interest " + - interestOps); + throw new IllegalStateException( + "Current phase " + currentPhase + " but got interest " + interestOps); } runCurrentPhase(); if (isCurrentPhaseDone() && nextPhase.selectionInterest == interestOps) { @@ -190,8 +181,8 @@ public class NonblockingSaslHandler { /** * When current phase is finished, it's expected to call this method first before running the - * state machine again. - * By calling this, "next phase" is marked as started (and not done), thus is ready to run. + * state machine again. By calling this, "next phase" is marked as started (and not done), thus is + * ready to run. * * @throws IllegalArgumentException if current phase is not yet done. */ @@ -207,8 +198,8 @@ public class NonblockingSaslHandler { } // If next phase's interest is not the same as current, nor the same as the selection key, // we need to change interest on the selector. - if (!(nextPhase.selectionInterest == currentPhase.selectionInterest || - nextPhase.selectionInterest == selectionKey.interestOps())) { + if (!(nextPhase.selectionInterest == currentPhase.selectionInterest + || nextPhase.selectionInterest == selectionKey.interestOps())) { changeSelectionInterest(nextPhase.selectionInterest); } currentPhase = nextPhase; @@ -222,8 +213,8 @@ public class NonblockingSaslHandler { private void failSaslNegotiation(TSaslNegotiationException e) { LOGGER.error("Sasl negotiation failed", e); String errorMsg = e.getDetails(); - saslChallenge.withHeaderAndPayload(new byte[]{e.getErrorType().code.getValue()}, - errorMsg.getBytes(StandardCharsets.UTF_8)); + saslChallenge.withHeaderAndPayload( + new byte[] {e.getErrorType().code.getValue()}, errorMsg.getBytes(StandardCharsets.UTF_8)); nextPhase = Phase.WRITING_FAILURE_MESSAGE; } @@ -233,10 +224,8 @@ public class NonblockingSaslHandler { } private void failIO(TTransportException e) { - StringBuilder errorMsg = new StringBuilder("IO failure ") - .append(e.getType()) - .append(" in ") - .append(currentPhase); + StringBuilder errorMsg = + new StringBuilder("IO failure ").append(e.getType()).append(" in ").append(currentPhase); if (e.getMessage() != null) { errorMsg.append(": ").append(e.getMessage()); } @@ -252,7 +241,8 @@ public class NonblockingSaslHandler { if (saslResponse.isComplete()) { SaslNegotiationHeaderReader startHeader = saslResponse.getHeader(); if (startHeader.getStatus() != NegotiationStatus.START) { - throw new TInvalidSaslFrameException("Expecting START status but got " + startHeader.getStatus()); + throw new TInvalidSaslFrameException( + "Expecting START status but got " + startHeader.getStatus()); } String mechanism = new String(saslResponse.getPayload(), StandardCharsets.UTF_8); saslPeer = saslServerFactory.getSaslPeer(mechanism); @@ -293,8 +283,10 @@ public class NonblockingSaslHandler { // Computation executions private void executeEvaluatingSaslResponse() { - if (!(saslResponse.getHeader().getStatus() == OK || saslResponse.getHeader().getStatus() == COMPLETE)) { - String error = "Expect status OK or COMPLETE, but got " + saslResponse.getHeader().getStatus(); + if (!(saslResponse.getHeader().getStatus() == OK + || saslResponse.getHeader().getStatus() == COMPLETE)) { + String error = + "Expect status OK or COMPLETE, but got " + saslResponse.getHeader().getStatus(); failSaslNegotiation(new TSaslNegotiationException(ErrorType.PROTOCOL_ERROR, error)); return; } @@ -304,10 +296,10 @@ public class NonblockingSaslHandler { byte[] newChallenge = saslPeer.evaluate(response); if (saslPeer.isAuthenticated()) { dataProtected = saslPeer.isDataProtected(); - saslChallenge.withHeaderAndPayload(new byte[]{COMPLETE.getValue()}, newChallenge); + saslChallenge.withHeaderAndPayload(new byte[] {COMPLETE.getValue()}, newChallenge); nextPhase = Phase.WRITING_SUCCESS_MESSAGE; } else { - saslChallenge.withHeaderAndPayload(new byte[]{OK.getValue()}, newChallenge); + saslChallenge.withHeaderAndPayload(new byte[] {OK.getValue()}, newChallenge); nextPhase = Phase.WRITING_SASL_CHALLENGE; } } catch (TSaslNegotiationException e) { @@ -344,7 +336,7 @@ public class NonblockingSaslHandler { byte[] outputPayload = saslPeer.wrap(rawOutput.get(), 0, rawOutput.len()); responseWriter.withOnlyPayload(outputPayload); } else { - responseWriter.withOnlyPayload(rawOutput.get(), 0 ,rawOutput.len()); + responseWriter.withOnlyPayload(rawOutput.get(), 0, rawOutput.len()); } nextPhase = Phase.WRITING_RESPONSE; } catch (TTransportException e) { @@ -406,8 +398,9 @@ public class NonblockingSaslHandler { } /** - * Release all the resources managed by this state machine (connection, selection and sasl server). - * To avoid being blocked, this should be invoked in the network thread that manages the selector. + * Release all the resources managed by this state machine (connection, selection and sasl + * server). To avoid being blocked, this should be invoked in the network thread that manages the + * selector. */ public void close() { underlyingTransport.close(); @@ -416,7 +409,8 @@ public class NonblockingSaslHandler { saslPeer.dispose(); } if (serverContextCreated) { - eventHandler.deleteContext(serverContext, + eventHandler.deleteContext( + serverContext, inputProtocolFactory.getProtocol(underlyingTransport), outputProtocolFactory.getProtocol(underlyingTransport)); } @@ -491,8 +485,7 @@ public class NonblockingSaslHandler { void unsafeRun(NonblockingSaslHandler statemachine) { // Do nothing. } - } - ; + }; // The interest on the selection key during the phase private int selectionInterest; @@ -511,8 +504,8 @@ public class NonblockingSaslHandler { */ void runStateMachine(NonblockingSaslHandler statemachine) { if (statemachine.currentPhase != this) { - throw new IllegalArgumentException("State machine is " + statemachine.currentPhase + - " but is expected to be " + this); + throw new IllegalArgumentException( + "State machine is " + statemachine.currentPhase + " but is expected to be " + this); } if (statemachine.isCurrentPhaseDone()) { throw new IllegalStateException("State machine should step into " + statemachine.nextPhase); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java index 01c172836..ede2177d5 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * Read frames for sasl negotiatiions. - */ +/** Read frames for sasl negotiatiions. */ public class SaslNegotiationFrameReader extends FrameReader<SaslNegotiationHeaderReader> { public SaslNegotiationFrameReader() { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java index 1e9ad1570..186d6d065 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java @@ -19,14 +19,13 @@ package org.apache.thrift.transport.sasl; -import java.nio.ByteBuffer; +import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.PAYLOAD_LENGTH_BYTES; +import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.STATUS_BYTES; +import java.nio.ByteBuffer; import org.apache.thrift.EncodingUtils; import org.apache.thrift.utils.StringUtils; -import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.PAYLOAD_LENGTH_BYTES; -import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.STATUS_BYTES; - /** * Writer for sasl negotiation frames. It expect a status byte as header with a payload to be * written out (any header whose size is not equal to 1 would be considered as error). @@ -41,11 +40,19 @@ public class SaslNegotiationFrameWriter extends FrameWriter { } @Override - protected ByteBuffer buildFrame(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength) { + protected ByteBuffer buildFrame( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength) { if (header == null || headerLength != STATUS_BYTES) { - throw new IllegalArgumentException("Header " + StringUtils.bytesToHexString(header) + - " does not have expected length " + STATUS_BYTES); + throw new IllegalArgumentException( + "Header " + + StringUtils.bytesToHexString(header) + + " does not have expected length " + + STATUS_BYTES); } byte[] bytes = new byte[HEADER_BYTES + payloadLength]; System.arraycopy(header, headerOffset, bytes, 0, STATUS_BYTES); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java index 2d76ddb29..554758572 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java @@ -42,7 +42,8 @@ public class SaslNegotiationHeaderReader extends FixedSizeHeaderReader { negotiationStatus = NegotiationStatus.byValue(byteBuffer.get(0)); payloadSize = byteBuffer.getInt(1); if (payloadSize < 0) { - throw new TSaslNegotiationException(PROTOCOL_ERROR, "Payload size is negative: " + payloadSize); + throw new TSaslNegotiationException( + PROTOCOL_ERROR, "Payload size is negative: " + payloadSize); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java index 8f8138044..9a9e733da 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java @@ -21,9 +21,7 @@ package org.apache.thrift.transport.sasl; import org.apache.thrift.transport.TTransportException; -/** - * A peer in a sasl negotiation. - */ +/** A peer in a sasl negotiation. */ public interface SaslPeer { /** @@ -35,9 +33,7 @@ public interface SaslPeer { */ byte[] evaluate(byte[] negotiationMessage) throws TSaslNegotiationException; - /** - * @return true if authentication is done. - */ + /** @return true if authentication is done. */ boolean isAuthenticated(); /** @@ -93,8 +89,6 @@ public interface SaslPeer { return unwrap(data, 0, data.length); } - /** - * Close this peer and release resources. - */ + /** Close this peer and release resources. */ void dispose(); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java index 31992e5fc..0264531d6 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java @@ -19,19 +19,16 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; + import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; - -/** - * Server side sasl peer, a wrapper around SaslServer to provide some handy methods. - */ +/** Server side sasl peer, a wrapper around SaslServer to provide some handy methods. */ public class ServerSaslPeer implements SaslPeer { private static final Logger LOGGER = LoggerFactory.getLogger(ServerSaslPeer.class); @@ -49,8 +46,8 @@ public class ServerSaslPeer implements SaslPeer { try { return saslServer.evaluateResponse(negotiationMessage); } catch (SaslException e) { - throw new TSaslNegotiationException(AUTHENTICATION_FAILURE, - "Authentication failed with " + saslServer.getMechanismName(), e); + throw new TSaslNegotiationException( + AUTHENTICATION_FAILURE, "Authentication failed with " + saslServer.getMechanismName(), e); } } @@ -104,5 +101,4 @@ public class ServerSaslPeer implements SaslPeer { SaslServer getSaslServer() { return saslServer; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java index ff57ea5c4..3ec88165c 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * Got an invalid frame that does not respect the thrift sasl protocol. - */ +/** Got an invalid frame that does not respect the thrift sasl protocol. */ public class TInvalidSaslFrameException extends TSaslNegotiationException { public TInvalidSaslFrameException(String message) { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java index 9b1fa060e..15c597e13 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java @@ -21,9 +21,7 @@ package org.apache.thrift.transport.sasl; import org.apache.thrift.transport.TTransportException; -/** - * Exception for sasl negotiation errors. - */ +/** Exception for sasl negotiation errors. */ public class TSaslNegotiationException extends TTransportException { private final ErrorType error; @@ -42,18 +40,16 @@ public class TSaslNegotiationException extends TTransportException { return error; } - /** - * @return Errory type plus the message. - */ + /** @return Errory type plus the message. */ public String getSummary() { return error.name() + ": " + getMessage(); } - /** - * @return Summary and eventually the cause's message. - */ + /** @return Summary and eventually the cause's message. */ public String getDetails() { - return getCause() == null ? getSummary() : getSummary() + "\nReason: " + getCause().getMessage(); + return getCause() == null + ? getSummary() + : getSummary() + "\nReason: " + getCause().getMessage(); } public enum ErrorType { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java index 5486641d8..6e8d9ef9f 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java @@ -19,12 +19,10 @@ package org.apache.thrift.transport.sasl; -import javax.security.auth.callback.CallbackHandler; import java.util.Map; +import javax.security.auth.callback.CallbackHandler; -/** - * Contains all the parameters used to define a SASL server implementation. - */ +/** Contains all the parameters used to define a SASL server implementation. */ public class TSaslServerDefinition { public final String mechanism; public final String protocol; @@ -32,8 +30,12 @@ public class TSaslServerDefinition { public final Map<String, String> props; public final CallbackHandler cbh; - public TSaslServerDefinition(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { + public TSaslServerDefinition( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { this.mechanism = mechanism; this.protocol = protocol; this.serverName = serverName; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java index 06cf534b6..ab0e24518 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java @@ -19,17 +19,16 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.MECHANISME_MISMATCH; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; + import java.util.HashMap; import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.MECHANISME_MISMATCH; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; - /** * Factory to create sasl server. Users can extend this class to customize the SaslServer creation. */ @@ -41,24 +40,31 @@ public class TSaslServerFactory { this.saslMechanisms = new HashMap<>(); } - public void addSaslMechanism(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { - TSaslServerDefinition definition = new TSaslServerDefinition(mechanism, protocol, serverName, - props, cbh); + public void addSaslMechanism( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { + TSaslServerDefinition definition = + new TSaslServerDefinition(mechanism, protocol, serverName, props, cbh); saslMechanisms.put(definition.mechanism, definition); } public ServerSaslPeer getSaslPeer(String mechanism) throws TSaslNegotiationException { if (!saslMechanisms.containsKey(mechanism)) { - throw new TSaslNegotiationException(MECHANISME_MISMATCH, "Unsupported mechanism " + mechanism); + throw new TSaslNegotiationException( + MECHANISME_MISMATCH, "Unsupported mechanism " + mechanism); } TSaslServerDefinition saslDef = saslMechanisms.get(mechanism); try { - SaslServer saslServer = Sasl.createSaslServer(saslDef.mechanism, saslDef.protocol, - saslDef.serverName, saslDef.props, saslDef.cbh); + SaslServer saslServer = + Sasl.createSaslServer( + saslDef.mechanism, saslDef.protocol, saslDef.serverName, saslDef.props, saslDef.cbh); return new ServerSaslPeer(saslServer); } catch (SaslException e) { - throw new TSaslNegotiationException(PROTOCOL_ERROR, "Fail to create sasl server " + mechanism, e); + throw new TSaslNegotiationException( + PROTOCOL_ERROR, "Fail to create sasl server " + mechanism, e); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java b/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java index b54388a5b..6cb507006 100644 --- a/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java +++ b/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java @@ -25,7 +25,9 @@ public final class StringUtils { // Utility class. } - private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + private static final char[] HEX_CHARS = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; /** * Stringify a byte array to the hex representation for each byte. @@ -56,7 +58,13 @@ public final class StringUtils { throw new IndexOutOfBoundsException("Negative start offset " + offset); } if (length > bytes.length - offset) { - throw new IndexOutOfBoundsException("Invalid range, bytes.length: " + bytes.length + " offset: " + offset + " length: " + length); + throw new IndexOutOfBoundsException( + "Invalid range, bytes.length: " + + bytes.length + + " offset: " + + offset + + " length: " + + length); } char[] chars = new char[length * 2]; for (int i = 0; i < length; i++) { |