text:
package io.netty.channel;

import io.netty.buffer.ByteBufAllocator;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.DefaultAttributeMap;
import io.netty.util.Recycler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ResourceLeakHint;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.internal.ThrowableUtils;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.net.SocketAddress;

abstract class AbstractChannelHandlerContext extends DefaultAttributeMap
        implements ChannelHandlerContext, ResourceLeakHint {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannelHandlerContext.class);
    volatile AbstractChannelHandlerContext next;
    volatile AbstractChannelHandlerContext prev;

    /**
     * {@link ChannelHandler#handlerAdded(ChannelHandlerContext)} was called.
     */
    private static final int ADDED = 1;
    /**
     * {@link ChannelHandler#handlerRemoved(ChannelHandlerContext)} was called.
     */
    private static final int REMOVED = 2;
    /**
     * Neither {@link ChannelHandler#handlerAdded(ChannelHandlerContext)}
     * nor {@link ChannelHandler#handlerRemoved(ChannelHandlerContext)} was called.
     */
    private static final int INIT = 0;

    private final boolean inbound;
    private final boolean outbound;
    private final DefaultChannelPipeline pipeline;
    private final String name;

    // Will be set to null if no child executor should be used, otherwise it will be set to the
    // child executor.
    final EventExecutor executor;
    private ChannelFuture succeededFuture;
    private int handlerState = INIT;

    // Lazily instantiated tasks used to trigger events to a handler with different executor.
    // There is no need to make this volatile as at worse it will just create a few more instances then needed.
    private Runnable invokeChannelReadCompleteTask;
    private Runnable invokeReadTask;
    private Runnable invokeChannelWritableStateChangedTask;
    private Runnable invokeFlushTask;

    AbstractChannelHandlerContext(DefaultChannelPipeline pipeline, EventExecutor executor, String name,
                                  boolean inbound, boolean outbound) {

        if (name == null) {
            throw new NullPointerException("name");
        }

        this.pipeline = pipeline;
        this.name = name;
        this.executor = executor;
        this.inbound = inbound;
        this.outbound = outbound;
    }

    @Override
    public Channel channel() {
        return pipeline.channel();
    }

    @Override
    public ChannelPipeline pipeline() {
        return pipeline;
    }

    @Override
    public ByteBufAllocator alloc() {
        return channel().config().getAllocator();
    }

    @Override
    public EventExecutor executor() {
        if (executor == null) {
            return channel().eventLoop();
        } else {
            return executor;
        }
    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public ChannelHandlerContext fireChannelRegistered() {
        invokeChannelRegistered(findContextInbound());
        return this;
    }

    static void invokeChannelRegistered(final AbstractChannelHandlerContext next) {
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelRegistered();
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelRegistered();
                }
            });
        }
    }

    private void invokeChannelRegistered() {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelRegistered(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelRegistered();
        }
    }

    @Override
    public ChannelHandlerContext fireChannelUnregistered() {
        invokeChannelUnregistered(findContextInbound());
        return this;
    }

    static void invokeChannelUnregistered(final AbstractChannelHandlerContext next) {
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelUnregistered();
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelUnregistered();
                }
            });
        }
    }

    private void invokeChannelUnregistered() {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelUnregistered(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelUnregistered();
        }
    }

    @Override
    public ChannelHandlerContext fireChannelActive() {
        final AbstractChannelHandlerContext next = findContextInbound();
        invokeChannelActive(next);
        return this;
    }

    static void invokeChannelActive(final AbstractChannelHandlerContext next) {
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelActive();
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelActive();
                }
            });
        }
    }

    private void invokeChannelActive() {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelActive(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelActive();
        }
    }

    @Override
    public ChannelHandlerContext fireChannelInactive() {
        invokeChannelInactive(findContextInbound());
        return this;
    }

    static void invokeChannelInactive(final AbstractChannelHandlerContext next) {
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelInactive();
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelInactive();
                }
            });
        }
    }

    private void invokeChannelInactive() {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelInactive(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelInactive();
        }
    }

    @Override
    public ChannelHandlerContext fireExceptionCaught(final Throwable cause) {
        invokeExceptionCaught(next, cause);
        return this;
    }

    static void invokeExceptionCaught(final AbstractChannelHandlerContext next, final Throwable cause) {
        ObjectUtil.checkNotNull(cause, "cause");
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeExceptionCaught(cause);
        } else {
            try {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        next.invokeExceptionCaught(cause);
                    }
                });
            } catch (Throwable t) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Failed to submit an exceptionCaught() event.", t);
                    logger.warn("The exceptionCaught() event that was failed to submit was:", cause);
                }
            }
        }
    }

    private void invokeExceptionCaught(final Throwable cause) {
        if (isAdded()) {
            try {
                handler().exceptionCaught(this, cause);
            } catch (Throwable error) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                        "An exception {}" +
                        "was thrown by a user handler's exceptionCaught() " +
                        "method while handling the following exception:",
                        ThrowableUtils.stackTraceToString(error), cause);
                } else if (logger.isWarnEnabled()) {
                    logger.warn(
                        "An exception '{}' [enable DEBUG level for full stacktrace] " +
                        "was thrown by a user handler's exceptionCaught() " +
                        "method while handling the following exception:", error, cause);
                }
            }
        } else {
            fireExceptionCaught(cause);
        }
    }

    @Override
    public ChannelHandlerContext fireUserEventTriggered(final Object event) {
        invokeUserEventTriggered(findContextInbound(), event);
        return this;
    }

    static void invokeUserEventTriggered(final AbstractChannelHandlerContext next, final Object event) {
        ObjectUtil.checkNotNull(event, "event");
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeUserEventTriggered(event);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeUserEventTriggered(event);
                }
            });
        }
    }

    private void invokeUserEventTriggered(Object event) {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).userEventTriggered(this, event);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireUserEventTriggered(event);
        }
    }

    @Override
    public ChannelHandlerContext fireChannelRead(final Object msg) {
        invokeChannelRead(findContextInbound(), msg);
        return this;
    }

    static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
        final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelRead(m);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelRead(m);
                }
            });
        }
    }

    private void invokeChannelRead(Object msg) {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelRead(this, msg);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelRead(msg);
        }
    }

    @Override
    public ChannelHandlerContext fireChannelReadComplete() {
        invokeChannelReadComplete(findContextInbound());
        return this;
    }

    static void invokeChannelReadComplete(final AbstractChannelHandlerContext next) {
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelReadComplete();
        } else {
            Runnable task = next.invokeChannelReadCompleteTask;
            if (task == null) {
                next.invokeChannelReadCompleteTask = task = new Runnable() {
                    @Override
                    public void run() {
                        next.invokeChannelReadComplete();
                    }
                };
            }
            executor.execute(task);
        }
    }

    private void invokeChannelReadComplete() {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelReadComplete(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelReadComplete();
        }
    }

    @Override
    public ChannelHandlerContext fireChannelWritabilityChanged() {
        invokeChannelWritabilityChanged(findContextInbound());
        return this;
    }

    static void invokeChannelWritabilityChanged(final AbstractChannelHandlerContext next) {
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelWritabilityChanged();
        } else {
            Runnable task = next.invokeChannelWritableStateChangedTask;
            if (task == null) {
                next.invokeChannelWritableStateChangedTask = task = new Runnable() {
                    @Override
                    public void run() {
                        next.invokeChannelWritabilityChanged();
                    }
                };
            }
            executor.execute(task);
        }
    }

    private void invokeChannelWritabilityChanged() {
        if (isAdded()) {
            try {
                ((ChannelInboundHandler) handler()).channelWritabilityChanged(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelWritabilityChanged();
        }
    }

    @Override
    public ChannelFuture bind(SocketAddress localAddress) {
        return bind(localAddress, newPromise());
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress) {
        return connect(remoteAddress, newPromise());
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
        return connect(remoteAddress, localAddress, newPromise());
    }

    @Override
    public ChannelFuture disconnect() {
        return disconnect(newPromise());
    }

    @Override
    public ChannelFuture close() {
        return close(newPromise());
    }

    @Override
    public ChannelFuture deregister() {
        return deregister(newPromise());
    }

    @Override
    public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) {
        if (localAddress == null) {
            throw new NullPointerException("localAddress");
        }
        if (!validatePromise(promise, false)) {
            // cancelled
            return promise;
        }

        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeBind(localAddress, promise);
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    next.invokeBind(localAddress, promise);
                }
            }, promise, null);
        }
        return promise;
    }

    private void invokeBind(SocketAddress localAddress, ChannelPromise promise) {
        if (isAdded()) {
            try {
                ((ChannelOutboundHandler) handler()).bind(this, localAddress, promise);
            } catch (Throwable t) {
                notifyOutboundHandlerException(t, promise);
            }
        } else {
            bind(localAddress, promise);
        }
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
        return connect(remoteAddress, null, promise);
    }

    @Override
    public ChannelFuture connect(
            final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {

        if (remoteAddress == null) {
            throw new NullPointerException("remoteAddress");
        }
        if (!validatePromise(promise, false)) {
            // cancelled
            return promise;
        }

        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeConnect(remoteAddress, localAddress, promise);
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    next.invokeConnect(remoteAddress, localAddress, promise);
                }
            }, promise, null);
        }
        return promise;
    }

    private void invokeConnect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
        if (isAdded()) {
            try {
                ((ChannelOutboundHandler) handler()).connect(this, remoteAddress, localAddress, promise);
            } catch (Throwable t) {
                notifyOutboundHandlerException(t, promise);
            }
        } else {
            connect(remoteAddress, localAddress, promise);
        }
    }

    @Override
    public ChannelFuture disconnect(final ChannelPromise promise) {
        if (!validatePromise(promise, false)) {
            // cancelled
            return promise;
        }

        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            // Translate disconnect to close if the channel has no notion of disconnect-reconnect.
            // So far, UDP/IP is the only transport that has such behavior.
            if (!channel().metadata().hasDisconnect()) {
                next.invokeClose(promise);
            } else {
                next.invokeDisconnect(promise);
            }
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    if (!channel().metadata().hasDisconnect()) {
                        next.invokeClose(promise);
                    } else {
                        next.invokeDisconnect(promise);
                    }
                }
            }, promise, null);
        }
        return promise;
    }

    private void invokeDisconnect(ChannelPromise promise) {
        if (isAdded()) {
            try {
                ((ChannelOutboundHandler) handler()).disconnect(this, promise);
            } catch (Throwable t) {
                notifyOutboundHandlerException(t, promise);
            }
        } else {
            disconnect(promise);
        }
    }

    @Override
    public ChannelFuture close(final ChannelPromise promise) {
        if (!validatePromise(promise, false)) {
            // cancelled
            return promise;
        }

        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeClose(promise);
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    next.invokeClose(promise);
                }
            }, promise, null);
        }

        return promise;
    }

    private void invokeClose(ChannelPromise promise) {
        if (isAdded()) {
            try {
                ((ChannelOutboundHandler) handler()).close(this, promise);
            } catch (Throwable t) {
                notifyOutboundHandlerException(t, promise);
            }
        } else {
            close(promise);
        }
    }

    @Override
    public ChannelFuture deregister(final ChannelPromise promise) {
        if (!validatePromise(promise, false)) {
            // cancelled
            return promise;
        }

        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeDeregister(promise);
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    next.invokeDeregister(promise);
                }
            }, promise, null);
        }

        return promise;
    }

    private void invokeDeregister(ChannelPromise promise) {
        if (isAdded()) {
            try {
                ((ChannelOutboundHandler) handler()).deregister(this, promise);
            } catch (Throwable t) {
                notifyOutboundHandlerException(t, promise);
            }
        } else {
            deregister(promise);
        }
    }

    @Override
    public ChannelHandlerContext read() {
        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeRead();
        } else {
            Runnable task = next.invokeReadTask;
            if (task == null) {
                next.invokeReadTask = task = new Runnable() {
                    @Override
                    public void run() {
                        next.invokeRead();
                    }
                };
            }
            executor.execute(task);
        }

        return this;
    }

    private void invokeRead() {
        if (isAdded()) {
            try {
                ((ChannelOutboundHandler) handler()).read(this);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            read();
        }
    }

    @Override
    public ChannelFuture write(Object msg) {
        return write(msg, newPromise());
    }

    @Override
    public ChannelFuture write(final Object msg, final ChannelPromise promise) {
        if (msg == null) {
            throw new NullPointerException("msg");
        }

        try {
            if (!validatePromise(promise, true)) {
                ReferenceCountUtil.release(msg);
                // cancelled
                return promise;
            }
        } catch (RuntimeException e) {
            ReferenceCountUtil.release(msg);
            throw e;
        }
        write(msg, false, promise);

        return promise;
    }

    private void invokeWrite(Object msg, ChannelPromise promise) {
        if (isAdded()) {
            invokeWrite0(msg, promise);
        } else {
            write(msg, promise);
        }
    }

    private void invokeWrite0(Object msg, ChannelPromise promise) {
        try {
            ((ChannelOutboundHandler) handler()).write(this, msg, promise);
        } catch (Throwable t) {
            notifyOutboundHandlerException(t, promise);
        }
    }

    @Override
    public ChannelHandlerContext flush() {
        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeFlush();
        } else {
            Runnable task = next.invokeFlushTask;
            if (task == null) {
                next.invokeFlushTask = task = new Runnable() {
                    @Override
                    public void run() {
                        next.invokeFlush();
                    }
                };
            }
            safeExecute(executor, task, channel().voidPromise(), null);
        }

        return this;
    }

    private void invokeFlush() {
        if (isAdded()) {
            invokeFlush0();
        } else {
            flush();
        }
    }

    private void invokeFlush0() {
        try {
            ((ChannelOutboundHandler) handler()).flush(this);
        } catch (Throwable t) {
            notifyHandlerException(t);
        }
    }

    @Override
    public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
        if (msg == null) {
            throw new NullPointerException("msg");
        }

        if (!validatePromise(promise, true)) {
            ReferenceCountUtil.release(msg);
            // cancelled
            return promise;
        }

        write(msg, true, promise);

        return promise;
    }

    private void invokeWriteAndFlush(Object msg, ChannelPromise promise) {
        if (isAdded()) {
            invokeWrite0(msg, promise);
            invokeFlush0();
        } else {
            writeAndFlush(msg, promise);
        }
    }

    private void write(Object msg, boolean flush, ChannelPromise promise) {
        AbstractChannelHandlerContext next = findContextOutbound();
        final Object m = pipeline.touch(msg, next);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            if (flush) {
                next.invokeWriteAndFlush(m, promise);
            } else {
                next.invokeWrite(m, promise);
            }
        } else {
            AbstractWriteTask task;
            if (flush) {
                task = WriteAndFlushTask.newInstance(next, m, promise);
            }  else {
                task = WriteTask.newInstance(next, m, promise);
            }
            safeExecute(executor, task, promise, m);
        }
    }

    @Override
    public ChannelFuture writeAndFlush(Object msg) {
        return writeAndFlush(msg, newPromise());
    }

    private static void notifyOutboundHandlerException(Throwable cause, ChannelPromise promise) {
        if (!promise.tryFailure(cause) && !(promise instanceof VoidChannelPromise)) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to fail the promise because it's done already: {}", promise, cause);
            }
        }
    }

    private void notifyHandlerException(Throwable cause) {
        if (inExceptionCaught(cause)) {
            if (logger.isWarnEnabled()) {
                logger.warn(
                        "An exception was thrown by a user handler " +
                                "while handling an exceptionCaught event", cause);
            }
            return;
        }

        invokeExceptionCaught(cause);
    }

    private static boolean inExceptionCaught(Throwable cause) {
        do {
            StackTraceElement[] trace = cause.getStackTrace();
            if (trace != null) {
                for (StackTraceElement t : trace) {
                    if (t == null) {
                        break;
                    }
                    if ("exceptionCaught".equals(t.getMethodName())) {
                        return true;
                    }
                }
            }

            cause = cause.getCause();
        } while (cause != null);

        return false;
    }

    @Override
    public ChannelPromise newPromise() {
        return new DefaultChannelPromise(channel(), executor());
    }

    @Override
    public ChannelProgressivePromise newProgressivePromise() {
        return new DefaultChannelProgressivePromise(channel(), executor());
    }

    @Override
    public ChannelFuture newSucceededFuture() {
        ChannelFuture succeededFuture = this.succeededFuture;
        if (succeededFuture == null) {
            this.succeededFuture = succeededFuture = new SucceededChannelFuture(channel(), executor());
        }
        return succeededFuture;
    }

    @Override
    public ChannelFuture newFailedFuture(Throwable cause) {
        return new FailedChannelFuture(channel(), executor(), cause);
    }

    private boolean validatePromise(ChannelPromise promise, boolean allowVoidPromise) {
        if (promise == null) {
            throw new NullPointerException("promise");
        }

        if (promise.isDone()) {
            // Check if the promise was cancelled and if so signal that the processing of the operation
            // should not be performed.
            //
            // See https://github.com/netty/netty/issues/2349
            if (promise.isCancelled()) {
                return false;
            }
            throw new IllegalArgumentException("promise already done: " + promise);
        }

        if (promise.channel() != channel()) {
            throw new IllegalArgumentException(String.format(
                    "promise.channel does not match: %s (expected: %s)", promise.channel(), channel()));
        }

        if (promise.getClass() == DefaultChannelPromise.class) {
            return true;
        }

        if (!allowVoidPromise && promise instanceof VoidChannelPromise) {
            throw new IllegalArgumentException(
                    StringUtil.simpleClassName(VoidChannelPromise.class) + " not allowed for this operation");
        }

        if (promise instanceof AbstractChannel.CloseFuture) {
            throw new IllegalArgumentException(
                    StringUtil.simpleClassName(AbstractChannel.CloseFuture.class) + " not allowed in a pipeline");
        }
        return true;
    }

    private AbstractChannelHandlerContext findContextInbound() {
        AbstractChannelHandlerContext ctx = this;
        do {
            ctx = ctx.next;
        } while (!ctx.inbound);
        return ctx;
    }

    private AbstractChannelHandlerContext findContextOutbound() {
        AbstractChannelHandlerContext ctx = this;
        do {
            ctx = ctx.prev;
        } while (!ctx.outbound);
        return ctx;
    }

    @Override
    public ChannelPromise voidPromise() {
        return channel().voidPromise();
    }

    final void setRemoved() {
        handlerState = REMOVED;
    }

    final void setAdded() {
        handlerState = ADDED;
    }

    /**
     * Makes best possible effort to detect if {@link ChannelHandler#handlerAdded(ChannelHandlerContext)} was called
     * yet. If not return {@code false} and if called or could not detect return {@code true}.
     *
     * If this method returns {@code true} we will not invoke the {@link ChannelHandler} but just forward the event.
     * This is needed as {@link DefaultChannelPipeline} may already put the {@link ChannelHandler} in the linked-list
     * but not called {@link }
     */
    private boolean isAdded() {
        return handlerState == ADDED;
    }

    @Override
    public boolean isRemoved() {
        return handlerState == REMOVED;
    }

    @Override
    public <T> Attribute<T> attr(AttributeKey<T> key) {
        return channel().attr(key);
    }

    @Override
    public <T> boolean hasAttr(AttributeKey<T> key) {
        return channel().hasAttr(key);
    }

    private static void safeExecute(EventExecutor executor, Runnable runnable, ChannelPromise promise, Object msg) {
        try {
            executor.execute(runnable);
        } catch (Throwable cause) {
            try {
                promise.setFailure(cause);
            } finally {
                if (msg != null) {
                    ReferenceCountUtil.release(msg);
                }
            }
        }
    }

    @Override
    public String toHintString() {
        return '\'' + name + "' will handle the message from this point.";
    }

    @Override
    public String toString() {
        return StringUtil.simpleClassName(ChannelHandlerContext.class) + '(' + name + ", " + channel() + ')';
    }

    abstract static class AbstractWriteTask implements Runnable {

        private static final boolean ESTIMATE_TASK_SIZE_ON_SUBMIT =
                SystemPropertyUtil.getBoolean("io.netty.transport.estimateSizeOnSubmit", true);

        // Assuming a 64-bit JVM, 16 bytes object header, 3 reference fields and one int field, plus alignment
        private static final int WRITE_TASK_OVERHEAD =
                SystemPropertyUtil.getInt("io.netty.transport.writeTaskSizeOverhead", 48);

        private final Recycler.Handle<AbstractWriteTask> handle;
        private AbstractChannelHandlerContext ctx;
        private Object msg;
        private ChannelPromise promise;
        private int size;

        @SuppressWarnings("unchecked")
        private AbstractWriteTask(Recycler.Handle<? extends AbstractWriteTask> handle) {
            this.handle = (Recycler.Handle<AbstractWriteTask>) handle;
        }

        protected static void init(AbstractWriteTask task, AbstractChannelHandlerContext ctx,
                                   Object msg, ChannelPromise promise) {
            task.ctx = ctx;
            task.msg = msg;
            task.promise = promise;

            if (ESTIMATE_TASK_SIZE_ON_SUBMIT) {
                ChannelOutboundBuffer buffer = ctx.channel().unsafe().outboundBuffer();

                // Check for null as it may be set to null if the channel is closed already
                if (buffer != null) {
                    task.size = ctx.pipeline.estimatorHandle().size(msg) + WRITE_TASK_OVERHEAD;
                    buffer.incrementPendingOutboundBytes(task.size);
                } else {
                    task.size = 0;
                }
            } else {
                task.size = 0;
            }
        }

        @Override
        public final void run() {
            try {
                ChannelOutboundBuffer buffer = ctx.channel().unsafe().outboundBuffer();
                // Check for null as it may be set to null if the channel is closed already
                if (ESTIMATE_TASK_SIZE_ON_SUBMIT && buffer != null) {
                    buffer.decrementPendingOutboundBytes(size);
                }
                write(ctx, msg, promise);
            } finally {
                // Set to null so the GC can collect them directly
                ctx = null;
                msg = null;
                promise = null;
                handle.recycle(this);
            }
        }

        protected void write(AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            ctx.invokeWrite(msg, promise);
        }
    }

    static final class WriteTask extends AbstractWriteTask implements SingleThreadEventLoop.NonWakeupRunnable {

        private static final Recycler<WriteTask> RECYCLER = new Recycler<WriteTask>() {
            @Override
            protected WriteTask newObject(Handle<WriteTask> handle) {
                return new WriteTask(handle);
            }
        };

        private static WriteTask newInstance(
                AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            WriteTask task = RECYCLER.get();
            init(task, ctx, msg, promise);
            return task;
        }

        private WriteTask(Recycler.Handle<WriteTask> handle) {
            super(handle);
        }
    }

    static final class WriteAndFlushTask extends AbstractWriteTask {

        private static final Recycler<WriteAndFlushTask> RECYCLER = new Recycler<WriteAndFlushTask>() {
            @Override
            protected WriteAndFlushTask newObject(Handle<WriteAndFlushTask> handle) {
                return new WriteAndFlushTask(handle);
            }
        };

        private static WriteAndFlushTask newInstance(
                AbstractChannelHandlerContext ctx, Object msg,  ChannelPromise promise) {
            WriteAndFlushTask task = RECYCLER.get();
            init(task, ctx, msg, promise);
            return task;
        }

        private WriteAndFlushTask(Recycler.Handle<WriteAndFlushTask> handle) {
            super(handle);
        }

        @Override
        public void write(AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            super.write(ctx, msg, promise);
            ctx.invokeFlush();
        }
    }
}


text:
/*globals window:false, async:false, Event:false*/
(function (window, async) {
  'use strict';
  var REFRESH_INTERVAL, Instance;
  REFRESH_INTERVAL = 100;

  Instance = function (component, element) {
    if (!component) throw new Error('undefined instance component.');
    if (!element) throw new Error('undefined instance element.');
    this.component = component;
    this.element = element;
    this.id = element.getAttribute('id');
    this.status = 'loaded';
    Instance.instances[this.id] = this;
  };

  Instance.prototype.canInstall = function () {
    return this.status === 'loaded' && this.component.parentsLoaded();
  };

  Instance.prototype.canConnect = function () {
    return this.status === 'installed' && this.component.requires.every(function (required) {
      var instance = Instance.instances[this.element.getAttribute(required.interfaceName)];
      return instance && instance.status !== 'loaded' && instance.status !== 'installing';
    }.bind(this)) && this.component.listens.every(function (required) {
      var instance = Instance.instances[this.element.getAttribute(required.eventName)];
      return instance && instance.status !== 'loaded' && instance.status !== 'installing';
    }.bind(this));
  };

  Instance.prototype.canStart = function () {
    return this.status === 'connected';
  };

  Instance.prototype.install = function (done) {
    if (!this.canInstall()) return;
    async.series([function (done) {
      this.status = 'installing';
      done();
    }.bind(this), function (done) {
      this.component.installInstance(this, done);
    }.bind(this), function (done) {
      this.status = 'installed';
      done();
    }.bind(this)], done);
  };

  Instance.prototype.connect = function (done) {
    if (!this.canConnect()) return;
    async.series([function (done) {
      this.status = 'connecting';
      done();
    }.bind(this), function (done) {
      this.component.connectInstance(this, done);
    }.bind(this), function (done) {
      this.status = 'connected';
      done();
    }.bind(this)], done);
  };

  Instance.prototype.start = function (done) {
    if (!this.canStart()) return;
    async.series([function (done) {
      this.status = 'starting';
      this.component.startInstance(this, done);
    }.bind(this), function (done) {
      this.status = 'started';
      done();
    }.bind(this)], done);
  };

  Instance.loadInstances = function () {
    var elements = document.querySelectorAll('component:not([instance-load])');
    Array.prototype.filter.call(elements, function (element) {
      var component;
      component = Component.components[element.getAttribute('type')];
      if (!component) return;
      element.setAttribute('instance-load', 'true');
      new Instance(component, element);
    });
  };

  Instance.installInstances = function () {
    for (var i in Instance.instances) {
      if (Instance.instances.hasOwnProperty(i)) Instance.instances[i].install();
    }
  };

  Instance.connectInstances = function () {
    for (var i in Instance.instances) {
      if (Instance.instances.hasOwnProperty(i)) Instance.instances[i].connect();
    }
  };

  Instance.startInstances = function () {
    for (var i in Instance.instances) {
      if (Instance.instances.hasOwnProperty(i)) Instance.instances[i].start();
    }
  };

  Instance.instances = {};
  window.setInterval(Instance.loadInstances, REFRESH_INTERVAL);
  window.setInterval(Instance.installInstances, REFRESH_INTERVAL);
  window.setInterval(Instance.connectInstances, REFRESH_INTERVAL);
  window.setInterval(Instance.startInstances, REFRESH_INTERVAL);
  window.Instance = Instance;
})(window, async);

redpajama_set_name: RedPajamaGithub


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="uk.co.pilllogger.activities.RestoreActivity">
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:orderInCategory="100"
          android:showAsAction="never"/>
</menu>


text:
package com.ekocaman.twittercrawlapp.backend.entity;

import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;

import java.util.Date;

@Entity
public class TweetEntity {

    @Id
    private Long id;

    private String text;
    private long userId;
    private String screenName;
    private Date creationDate;

    public TweetEntity() {

    }

    public TweetEntity(Long id, String text, long userId, String screenName, Date creationDate) {
        this.id = id;
        this.text = text;
        this.userId = userId;
        this.screenName = screenName;
        this.creationDate = creationDate;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getScreenName() {
        return screenName;
    }

    public void setScreenName(String screenName) {
        this.screenName = screenName;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    @Override
    public String toString() {
        return "TweetEntity{" +
                "id=" + id +
                ", text='" + text + '\'' +
                ", userId=" + userId +
                ", screenName='" + screenName + '\'' +
                ", creationDate=" + creationDate +
                '}';
    }
}


text: Config files such as .bashrc, .zshrc, .vimrc, Microsoft.PowerShell_profile.ps1


text:
/*
 * mime.h, part of "ksmtp" project.
 *
 *  Created on: 20.05.2015, 14:15
 *      Author: Vsevolod Lutovinov <klopp@yandex.ru>
 */

#ifndef MIME_H_
#define MIME_H_

#include "../klib/config.h"
#include "../stringlib/stringlib.h"
#include "../stringlib/b64.h"

int isUsAscii( const char * s );
int isUsAsciiCs( const char * charset );
string mimeFileName( const char * name, const char * charset );
const char * getMimeType( const char * filename, const char * ctype );
char * mimeMakeBoundary( char * boundary );

#endif /* MIME_H_ */


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.huang.rp.blog.post.dao.BlogPostsMapper" >
  <resultMap id="BaseResultMap" type="com.huang.rp.blog.post.domain.BlogPosts" >
    <id column="ID" property="id" jdbcType="BIGINT" />
    <result column="post_author" property="postAuthor" jdbcType="BIGINT" />
    <result column="post_date" property="postDate" jdbcType="TIMESTAMP" />
    <result column="post_date_gmt" property="postDateGmt" jdbcType="TIMESTAMP" />
    <result column="post_status" property="postStatus" jdbcType="VARCHAR" />
    <result column="comment_status" property="commentStatus" jdbcType="VARCHAR" />
    <result column="post_password" property="postPassword" jdbcType="VARCHAR" />
    <result column="post_name" property="postName" jdbcType="VARCHAR" />
    <result column="post_modified" property="postModified" jdbcType="TIMESTAMP" />
    <result column="post_modified_gmt" property="postModifiedGmt" jdbcType="TIMESTAMP" />
    <result column="post_parent" property="postParent" jdbcType="BIGINT" />
    <result column="menu_order" property="menuOrder" jdbcType="INTEGER" />
    <result column="post_type" property="postType" jdbcType="VARCHAR" />
    <result column="post_mime_type" property="postMimeType" jdbcType="VARCHAR" />
    <result column="has_code" property="hasCode" jdbcType="BIT" />
    <result column="has_pic" property="hasPic" jdbcType="BIT" />
    <result column="is_reprint" property="isReprint" jdbcType="BIT" />
    <result column="comment_count" property="commentCount" jdbcType="BIGINT" />
    <result column="read_count" property="readCount" jdbcType="BIGINT" />
  </resultMap>
  <resultMap id="ResultMapWithBLOBs" type="com.huang.rp.blog.post.domain.BlogPostsWithBLOBs" extends="BaseResultMap" >
    <result column="post_content" property="postContent" jdbcType="LONGVARCHAR" />
    <result column="post_title" property="postTitle" jdbcType="LONGVARCHAR" />
    <result column="post_excerpt" property="postExcerpt" jdbcType="LONGVARCHAR" />
    <result column="post_content_filtered" property="postContentFiltered" jdbcType="LONGVARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    ID, post_author, post_date, post_date_gmt, post_status, comment_status, post_password,
    post_name, post_modified, post_modified_gmt, post_parent, menu_order, post_type,
    post_mime_type, has_code, has_pic, is_reprint, comment_count, read_count
  </sql>
  <sql id="Blob_Column_List" >
    post_content, post_title, post_excerpt, post_content_filtered
  </sql>
  <select id="selectByExampleWithBLOBs" resultMap="ResultMapWithBLOBs" parameterType="com.huang.rp.blog.post.domain.BlogPostsExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from blog_posts
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.huang.rp.blog.post.domain.BlogPostsExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from blog_posts
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Long" >
    select
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from blog_posts
    where ID = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from blog_posts
    where ID = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.huang.rp.blog.post.domain.BlogPostsExample" >
    delete from blog_posts
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.huang.rp.blog.post.domain.BlogPostsWithBLOBs" >
    insert into blog_posts (ID, post_author, post_date,
      post_date_gmt, post_status, comment_status,
      post_password, post_name, post_modified,
      post_modified_gmt, post_parent, menu_order,
      post_type, post_mime_type, has_code,
      has_pic, is_reprint, comment_count,
      read_count, post_content, post_title,
      post_excerpt, post_content_filtered
      )
    values (#{id,jdbcType=BIGINT}, #{postAuthor,jdbcType=BIGINT}, #{postDate,jdbcType=TIMESTAMP},
      #{postDateGmt,jdbcType=TIMESTAMP}, #{postStatus,jdbcType=VARCHAR}, #{commentStatus,jdbcType=VARCHAR},
      #{postPassword,jdbcType=VARCHAR}, #{postName,jdbcType=VARCHAR}, #{postModified,jdbcType=TIMESTAMP},
      #{postModifiedGmt,jdbcType=TIMESTAMP}, #{postParent,jdbcType=BIGINT}, #{menuOrder,jdbcType=INTEGER},
      #{postType,jdbcType=VARCHAR}, #{postMimeType,jdbcType=VARCHAR}, #{hasCode,jdbcType=BIT},
      #{hasPic,jdbcType=BIT}, #{isReprint,jdbcType=BIT}, #{commentCount,jdbcType=BIGINT},
      #{readCount,jdbcType=BIGINT}, #{postContent,jdbcType=LONGVARCHAR}, #{postTitle,jdbcType=LONGVARCHAR},
      #{postExcerpt,jdbcType=LONGVARCHAR}, #{postContentFiltered,jdbcType=LONGVARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.huang.rp.blog.post.domain.BlogPostsWithBLOBs" >
    insert into blog_posts
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="postAuthor != null" >
        post_author,
      </if>
      <if test="postDate != null" >
        post_date,
      </if>
      <if test="postDateGmt != null" >
        post_date_gmt,
      </if>
      <if test="postStatus != null" >
        post_status,
      </if>
      <if test="commentStatus != null" >
        comment_status,
      </if>
      <if test="postPassword != null" >
        post_password,
      </if>
      <if test="postName != null" >
        post_name,
      </if>
      <if test="postModified != null" >
        post_modified,
      </if>
      <if test="postModifiedGmt != null" >
        post_modified_gmt,
      </if>
      <if test="postParent != null" >
        post_parent,
      </if>
      <if test="menuOrder != null" >
        menu_order,
      </if>
      <if test="postType != null" >
        post_type,
      </if>
      <if test="postMimeType != null" >
        post_mime_type,
      </if>
      <if test="hasCode != null" >
        has_code,
      </if>
      <if test="hasPic != null" >
        has_pic,
      </if>
      <if test="isReprint != null" >
        is_reprint,
      </if>
      <if test="commentCount != null" >
        comment_count,
      </if>
      <if test="readCount != null" >
        read_count,
      </if>
      <if test="postContent != null" >
        post_content,
      </if>
      <if test="postTitle != null" >
        post_title,
      </if>
      <if test="postExcerpt != null" >
        post_excerpt,
      </if>
      <if test="postContentFiltered != null" >
        post_content_filtered,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="postAuthor != null" >
        #{postAuthor,jdbcType=BIGINT},
      </if>
      <if test="postDate != null" >
        #{postDate,jdbcType=TIMESTAMP},
      </if>
      <if test="postDateGmt != null" >
        #{postDateGmt,jdbcType=TIMESTAMP},
      </if>
      <if test="postStatus != null" >
        #{postStatus,jdbcType=VARCHAR},
      </if>
      <if test="commentStatus != null" >
        #{commentStatus,jdbcType=VARCHAR},
      </if>
      <if test="postPassword != null" >
        #{postPassword,jdbcType=VARCHAR},
      </if>
      <if test="postName != null" >
        #{postName,jdbcType=VARCHAR},
      </if>
      <if test="postModified != null" >
        #{postModified,jdbcType=TIMESTAMP},
      </if>
      <if test="postModifiedGmt != null" >
        #{postModifiedGmt,jdbcType=TIMESTAMP},
      </if>
      <if test="postParent != null" >
        #{postParent,jdbcType=BIGINT},
      </if>
      <if test="menuOrder != null" >
        #{menuOrder,jdbcType=INTEGER},
      </if>
      <if test="postType != null" >
        #{postType,jdbcType=VARCHAR},
      </if>
      <if test="postMimeType != null" >
        #{postMimeType,jdbcType=VARCHAR},
      </if>
      <if test="hasCode != null" >
        #{hasCode,jdbcType=BIT},
      </if>
      <if test="hasPic != null" >
        #{hasPic,jdbcType=BIT},
      </if>
      <if test="isReprint != null" >
        #{isReprint,jdbcType=BIT},
      </if>
      <if test="commentCount != null" >
        #{commentCount,jdbcType=BIGINT},
      </if>
      <if test="readCount != null" >
        #{readCount,jdbcType=BIGINT},
      </if>
      <if test="postContent != null" >
        #{postContent,jdbcType=LONGVARCHAR},
      </if>
      <if test="postTitle != null" >
        #{postTitle,jdbcType=LONGVARCHAR},
      </if>
      <if test="postExcerpt != null" >
        #{postExcerpt,jdbcType=LONGVARCHAR},
      </if>
      <if test="postContentFiltered != null" >
        #{postContentFiltered,jdbcType=LONGVARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.huang.rp.blog.post.domain.BlogPostsExample" resultType="java.lang.Integer" >
    select count(*) from blog_posts
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update blog_posts
    <set >
      <if test="record.id != null" >
        ID = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.postAuthor != null" >
        post_author = #{record.postAuthor,jdbcType=BIGINT},
      </if>
      <if test="record.postDate != null" >
        post_date = #{record.postDate,jdbcType=TIMESTAMP},
      </if>
      <if test="record.postDateGmt != null" >
        post_date_gmt = #{record.postDateGmt,jdbcType=TIMESTAMP},
      </if>
      <if test="record.postStatus != null" >
        post_status = #{record.postStatus,jdbcType=VARCHAR},
      </if>
      <if test="record.commentStatus != null" >
        comment_status = #{record.commentStatus,jdbcType=VARCHAR},
      </if>
      <if test="record.postPassword != null" >
        post_password = #{record.postPassword,jdbcType=VARCHAR},
      </if>
      <if test="record.postName != null" >
        post_name = #{record.postName,jdbcType=VARCHAR},
      </if>
      <if test="record.postModified != null" >
        post_modified = #{record.postModified,jdbcType=TIMESTAMP},
      </if>
      <if test="record.postModifiedGmt != null" >
        post_modified_gmt = #{record.postModifiedGmt,jdbcType=TIMESTAMP},
      </if>
      <if test="record.postParent != null" >
        post_parent = #{record.postParent,jdbcType=BIGINT},
      </if>
      <if test="record.menuOrder != null" >
        menu_order = #{record.menuOrder,jdbcType=INTEGER},
      </if>
      <if test="record.postType != null" >
        post_type = #{record.postType,jdbcType=VARCHAR},
      </if>
      <if test="record.postMimeType != null" >
        post_mime_type = #{record.postMimeType,jdbcType=VARCHAR},
      </if>
      <if test="record.hasCode != null" >
        has_code = #{record.hasCode,jdbcType=BIT},
      </if>
      <if test="record.hasPic != null" >
        has_pic = #{record.hasPic,jdbcType=BIT},
      </if>
      <if test="record.isReprint != null" >
        is_reprint = #{record.isReprint,jdbcType=BIT},
      </if>
      <if test="record.commentCount != null" >
        comment_count = #{record.commentCount,jdbcType=BIGINT},
      </if>
      <if test="record.readCount != null" >
        read_count = #{record.readCount,jdbcType=BIGINT},
      </if>
      <if test="record.postContent != null" >
        post_content = #{record.postContent,jdbcType=LONGVARCHAR},
      </if>
      <if test="record.postTitle != null" >
        post_title = #{record.postTitle,jdbcType=LONGVARCHAR},
      </if>
      <if test="record.postExcerpt != null" >
        post_excerpt = #{record.postExcerpt,jdbcType=LONGVARCHAR},
      </if>
      <if test="record.postContentFiltered != null" >
        post_content_filtered = #{record.postContentFiltered,jdbcType=LONGVARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExampleWithBLOBs" parameterType="map" >
    update blog_posts
    set ID = #{record.id,jdbcType=BIGINT},
      post_author = #{record.postAuthor,jdbcType=BIGINT},
      post_date = #{record.postDate,jdbcType=TIMESTAMP},
      post_date_gmt = #{record.postDateGmt,jdbcType=TIMESTAMP},
      post_status = #{record.postStatus,jdbcType=VARCHAR},
      comment_status = #{record.commentStatus,jdbcType=VARCHAR},
      post_password = #{record.postPassword,jdbcType=VARCHAR},
      post_name = #{record.postName,jdbcType=VARCHAR},
      post_modified = #{record.postModified,jdbcType=TIMESTAMP},
      post_modified_gmt = #{record.postModifiedGmt,jdbcType=TIMESTAMP},
      post_parent = #{record.postParent,jdbcType=BIGINT},
      menu_order = #{record.menuOrder,jdbcType=INTEGER},
      post_type = #{record.postType,jdbcType=VARCHAR},
      post_mime_type = #{record.postMimeType,jdbcType=VARCHAR},
      has_code = #{record.hasCode,jdbcType=BIT},
      has_pic = #{record.hasPic,jdbcType=BIT},
      is_reprint = #{record.isReprint,jdbcType=BIT},
      comment_count = #{record.commentCount,jdbcType=BIGINT},
      read_count = #{record.readCount,jdbcType=BIGINT},
      post_content = #{record.postContent,jdbcType=LONGVARCHAR},
      post_title = #{record.postTitle,jdbcType=LONGVARCHAR},
      post_excerpt = #{record.postExcerpt,jdbcType=LONGVARCHAR},
      post_content_filtered = #{record.postContentFiltered,jdbcType=LONGVARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update blog_posts
    set ID = #{record.id,jdbcType=BIGINT},
      post_author = #{record.postAuthor,jdbcType=BIGINT},
      post_date = #{record.postDate,jdbcType=TIMESTAMP},
      post_date_gmt = #{record.postDateGmt,jdbcType=TIMESTAMP},
      post_status = #{record.postStatus,jdbcType=VARCHAR},
      comment_status = #{record.commentStatus,jdbcType=VARCHAR},
      post_password = #{record.postPassword,jdbcType=VARCHAR},
      post_name = #{record.postName,jdbcType=VARCHAR},
      post_modified = #{record.postModified,jdbcType=TIMESTAMP},
      post_modified_gmt = #{record.postModifiedGmt,jdbcType=TIMESTAMP},
      post_parent = #{record.postParent,jdbcType=BIGINT},
      menu_order = #{record.menuOrder,jdbcType=INTEGER},
      post_type = #{record.postType,jdbcType=VARCHAR},
      post_mime_type = #{record.postMimeType,jdbcType=VARCHAR},
      has_code = #{record.hasCode,jdbcType=BIT},
      has_pic = #{record.hasPic,jdbcType=BIT},
      is_reprint = #{record.isReprint,jdbcType=BIT},
      comment_count = #{record.commentCount,jdbcType=BIGINT},
      read_count = #{record.readCount,jdbcType=BIGINT}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.huang.rp.blog.post.domain.BlogPostsWithBLOBs" >
    update blog_posts
    <set >
      <if test="postAuthor != null" >
        post_author = #{postAuthor,jdbcType=BIGINT},
      </if>
      <if test="postDate != null" >
        post_date = #{postDate,jdbcType=TIMESTAMP},
      </if>
      <if test="postDateGmt != null" >
        post_date_gmt = #{postDateGmt,jdbcType=TIMESTAMP},
      </if>
      <if test="postStatus != null" >
        post_status = #{postStatus,jdbcType=VARCHAR},
      </if>
      <if test="commentStatus != null" >
        comment_status = #{commentStatus,jdbcType=VARCHAR},
      </if>
      <if test="postPassword != null" >
        post_password = #{postPassword,jdbcType=VARCHAR},
      </if>
      <if test="postName != null" >
        post_name = #{postName,jdbcType=VARCHAR},
      </if>
      <if test="postModified != null" >
        post_modified = #{postModified,jdbcType=TIMESTAMP},
      </if>
      <if test="postModifiedGmt != null" >
        post_modified_gmt = #{postModifiedGmt,jdbcType=TIMESTAMP},
      </if>
      <if test="postParent != null" >
        post_parent = #{postParent,jdbcType=BIGINT},
      </if>
      <if test="menuOrder != null" >
        menu_order = #{menuOrder,jdbcType=INTEGER},
      </if>
      <if test="postType != null" >
        post_type = #{postType,jdbcType=VARCHAR},
      </if>
      <if test="postMimeType != null" >
        post_mime_type = #{postMimeType,jdbcType=VARCHAR},
      </if>
      <if test="hasCode != null" >
        has_code = #{hasCode,jdbcType=BIT},
      </if>
      <if test="hasPic != null" >
        has_pic = #{hasPic,jdbcType=BIT},
      </if>
      <if test="isReprint != null" >
        is_reprint = #{isReprint,jdbcType=BIT},
      </if>
      <if test="commentCount != null" >
        comment_count = #{commentCount,jdbcType=BIGINT},
      </if>
      <if test="readCount != null" >
        read_count = #{readCount,jdbcType=BIGINT},
      </if>
      <if test="postContent != null" >
        post_content = #{postContent,jdbcType=LONGVARCHAR},
      </if>
      <if test="postTitle != null" >
        post_title = #{postTitle,jdbcType=LONGVARCHAR},
      </if>
      <if test="postExcerpt != null" >
        post_excerpt = #{postExcerpt,jdbcType=LONGVARCHAR},
      </if>
      <if test="postContentFiltered != null" >
        post_content_filtered = #{postContentFiltered,jdbcType=LONGVARCHAR},
      </if>
    </set>
    where ID = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.huang.rp.blog.post.domain.BlogPostsWithBLOBs" >
    update blog_posts
    set post_author = #{postAuthor,jdbcType=BIGINT},
      post_date = #{postDate,jdbcType=TIMESTAMP},
      post_date_gmt = #{postDateGmt,jdbcType=TIMESTAMP},
      post_status = #{postStatus,jdbcType=VARCHAR},
      comment_status = #{commentStatus,jdbcType=VARCHAR},
      post_password = #{postPassword,jdbcType=VARCHAR},
      post_name = #{postName,jdbcType=VARCHAR},
      post_modified = #{postModified,jdbcType=TIMESTAMP},
      post_modified_gmt = #{postModifiedGmt,jdbcType=TIMESTAMP},
      post_parent = #{postParent,jdbcType=BIGINT},
      menu_order = #{menuOrder,jdbcType=INTEGER},
      post_type = #{postType,jdbcType=VARCHAR},
      post_mime_type = #{postMimeType,jdbcType=VARCHAR},
      has_code = #{hasCode,jdbcType=BIT},
      has_pic = #{hasPic,jdbcType=BIT},
      is_reprint = #{isReprint,jdbcType=BIT},
      comment_count = #{commentCount,jdbcType=BIGINT},
      read_count = #{readCount,jdbcType=BIGINT},
      post_content = #{postContent,jdbcType=LONGVARCHAR},
      post_title = #{postTitle,jdbcType=LONGVARCHAR},
      post_excerpt = #{postExcerpt,jdbcType=LONGVARCHAR},
      post_content_filtered = #{postContentFiltered,jdbcType=LONGVARCHAR}
    where ID = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.huang.rp.blog.post.domain.BlogPosts" >
    update blog_posts
    set post_author = #{postAuthor,jdbcType=BIGINT},
      post_date = #{postDate,jdbcType=TIMESTAMP},
      post_date_gmt = #{postDateGmt,jdbcType=TIMESTAMP},
      post_status = #{postStatus,jdbcType=VARCHAR},
      comment_status = #{commentStatus,jdbcType=VARCHAR},
      post_password = #{postPassword,jdbcType=VARCHAR},
      post_name = #{postName,jdbcType=VARCHAR},
      post_modified = #{postModified,jdbcType=TIMESTAMP},
      post_modified_gmt = #{postModifiedGmt,jdbcType=TIMESTAMP},
      post_parent = #{postParent,jdbcType=BIGINT},
      menu_order = #{menuOrder,jdbcType=INTEGER},
      post_type = #{postType,jdbcType=VARCHAR},
      post_mime_type = #{postMimeType,jdbcType=VARCHAR},
      has_code = #{hasCode,jdbcType=BIT},
      has_pic = #{hasPic,jdbcType=BIT},
      is_reprint = #{isReprint,jdbcType=BIT},
      comment_count = #{commentCount,jdbcType=BIGINT},
      read_count = #{readCount,jdbcType=BIGINT}
    where ID = #{id,jdbcType=BIGINT}
  </update>
  <!--自定义sql开始-->
  <select id="selectArticleExcerptByFilter" resultMap="ResultMapWithBLOBs"
          parameterType="com.huang.rp.blog.access.filter.AccessFilter">
    select
    *
    from blog_posts bp
    LEFT JOIN
    (
    select
    bpt.post_id,
    GROUP_CONCAT(CONCAT(conv(oct(sp.code),8,10),':',sp.`value`)) tags
    from blog_post_terms bpt
    LEFT JOIN sys_parameter sp
    on bpt.term_id=sp.code
    <!-- 标签 paraType='T001' -->
    where sp.para_code='T001'
    and bpt.type=sp.para_code
    GROUP BY bpt.post_id)tag
    on bp.ID=tag.post_id
    where 1=1
    <if test="tagId!=null and tagId !=''">
      and tag.post_id is not null
      and bp.id in(select post_id from blog_post_terms where term_id=#{tagId})
    </if>
    <if test="tags!=null and tags !=''">
      and tag.post_id is not null
      and bp.id in(select post_id from blog_post_terms where term_id in (${tags}))
    </if>
    <if test="searchStr!=null and searchStr !=''">
      and bp.post_content_filtered like #{searchStr}
    </if>
    <if test="users!=null and users !=''">
      and bp.post_author in (${users})
    </if>
    <if test="userId!=null">
      and bp.post_author=#{userId}
    </if>
    <if test="sidx != null and sidx != ''">
      order by bp.${sidx}
      <if test="sord!=null and sord!= ''">
        ${sord}
      </if>
    </if>
  </select>
</mapper>


text:
package javax.swing.text.html;

import javax.swing.*;
import javax.swing.event.*;
import java.util.BitSet;
import java.io.Serializable;

/**
 * This class extends DefaultListModel, and also implements
 * the ListSelectionModel interface, allowing for it to store state
 * relevant to a SELECT form element which is implemented as a List.
 * If SELECT has a size attribute whose value is greater than 1,
 * or if allows multiple selection then a JList is used to
 * represent it and the OptionListModel is used as its model.
 * It also stores the initial state of the JList, to ensure an
 * accurate reset, if the user requests a reset of the form.
 *
 * @author Sunita Mani
 */
@SuppressWarnings("serial") // Superclass is not serializable across versions
class OptionListModel<E> extends DefaultListModel<E> implements ListSelectionModel, Serializable {

    private static final int MIN = -1;
    private static final int MAX = Integer.MAX_VALUE;
    private int selectionMode = SINGLE_SELECTION;
    private int minIndex = MAX;
    private int maxIndex = MIN;
    private int anchorIndex = -1;
    private int leadIndex = -1;
    private int firstChangedIndex = MAX;
    private int lastChangedIndex = MIN;
    private boolean isAdjusting = false;
    private BitSet value = new BitSet(32);
    private BitSet initialValue = new BitSet(32);
    protected EventListenerList listenerList = new EventListenerList();

    protected boolean leadAnchorNotificationEnabled = true;

    public int getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; }

    public int getMaxSelectionIndex() { return maxIndex; }

    public boolean getValueIsAdjusting() { return isAdjusting; }

    public int getSelectionMode() { return selectionMode; }

    public void setSelectionMode(int selectionMode) {
        switch (selectionMode) {
        case SINGLE_SELECTION:
        case SINGLE_INTERVAL_SELECTION:
        case MULTIPLE_INTERVAL_SELECTION:
            this.selectionMode = selectionMode;
            break;
        default:
            throw new IllegalArgumentException("invalid selectionMode");
        }
    }

    public boolean isSelectedIndex(int index) {
        return ((index < minIndex) || (index > maxIndex)) ? false : value.get(index);
    }

    public boolean isSelectionEmpty() {
        return (minIndex > maxIndex);
    }

    public void addListSelectionListener(ListSelectionListener l) {
        listenerList.add(ListSelectionListener.class, l);
    }

    public void removeListSelectionListener(ListSelectionListener l) {
        listenerList.remove(ListSelectionListener.class, l);
    }

    /**
     * Returns an array of all the ListSelectionListeners added
     * to this OptionListModel with addListSelectionListener().
     *
     * @return all of the ListSelectionListeners added or an empty
     *         array if no listeners have been added
     * @since 1.4
     */
    public ListSelectionListener[] getListSelectionListeners() {
        return listenerList.getListeners(ListSelectionListener.class);
    }

    /**
     * Notify listeners that we are beginning or ending a
     * series of value changes
     */
    protected void fireValueChanged(boolean isAdjusting) {
        fireValueChanged(getMinSelectionIndex(), getMaxSelectionIndex(), isAdjusting);
    }

    /**
     * Notify ListSelectionListeners that the value of the selection,
     * in the closed interval firstIndex,lastIndex, has changed.
     */
    protected void fireValueChanged(int firstIndex, int lastIndex) {
        fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());
    }

    /**
     * @param firstIndex The first index in the interval.
     * @param lastIndex The last index in the interval.
     * @param isAdjusting True if this is the final change in a series of them.
     * @see EventListenerList
     */
    protected void fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
    {
        Object[] listeners = listenerList.getListenerList();
        ListSelectionEvent e = null;

        for (int i = listeners.length - 2; i >= 0; i -= 2) {
            if (listeners[i] == ListSelectionListener.class) {
                if (e == null) {
                    e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting);
                }
                ((ListSelectionListener)listeners[i+1]).valueChanged(e);
            }
        }
    }

    private void fireValueChanged() {
        if (lastChangedIndex == MIN) {
            return;
        }
        /* Change the values before sending the event to the
         * listeners in case the event causes a listener to make
         * another change to the selection.
         */
        int oldFirstChangedIndex = firstChangedIndex;
        int oldLastChangedIndex = lastChangedIndex;
        firstChangedIndex = MAX;
        lastChangedIndex = MIN;
        fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex);
    }

    // Update first and last change indices
    private void markAsDirty(int r) {
        firstChangedIndex = Math.min(firstChangedIndex, r);
        lastChangedIndex =  Math.max(lastChangedIndex, r);
    }

    // Set the state at this index and update all relevant state.
    private void set(int r) {
        if (value.get(r)) {
            return;
        }
        value.set(r);
        Option option = (Option)get(r);
        option.setSelection(true);
        markAsDirty(r);

        // Update minimum and maximum indices
        minIndex = Math.min(minIndex, r);
        maxIndex = Math.max(maxIndex, r);
    }

    // Clear the state at this index and update all relevant state.
    private void clear(int r) {
        if (!value.get(r)) {
            return;
        }
        value.clear(r);
        Option option = (Option)get(r);
        option.setSelection(false);
        markAsDirty(r);

        // Update minimum and maximum indices
        /*
           If (r > minIndex) the minimum has not changed.
           The case (r < minIndex) is not possible because r'th value was set.
           We only need to check for the case when lowest entry has been cleared,
           and in this case we need to search for the first value set above it.
        */
        if (r == minIndex) {
            for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) {
                if (value.get(minIndex)) {
                    break;
                }
            }
        }
        /*
           If (r < maxIndex) the maximum has not changed.
           The case (r > maxIndex) is not possible because r'th value was set.
           We only need to check for the case when highest entry has been cleared,
           and in this case we need to search for the first value set below it.
        */
        if (r == maxIndex) {
            for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) {
                if (value.get(maxIndex)) {
                    break;
                }
            }
        }
        /* Performance note: This method is called from inside a loop in
           changeSelection() but we will only iterate in the loops
           above on the basis of one iteration per deselected cell - in total.
           Ie. the next time this method is called the work of the previous
           deselection will not be repeated.

           We also don't need to worry about the case when the min and max
           values are in their unassigned states. This cannot happen because
           this method's initial check ensures that the selection was not empty
           and therefore that the minIndex and maxIndex had 'real' values.

           If we have cleared the whole selection, set the minIndex and maxIndex
           to their cannonical values so that the next set command always works
           just by using Math.min and Math.max.
        */
        if (isSelectionEmpty()) {
            minIndex = MAX;
            maxIndex = MIN;
        }
    }

    /**
     * Sets the value of the leadAnchorNotificationEnabled flag.
     * @see             #isLeadAnchorNotificationEnabled()
     */
    public void setLeadAnchorNotificationEnabled(boolean flag) {
        leadAnchorNotificationEnabled = flag;
    }

    /**
     * Returns the value of the leadAnchorNotificationEnabled flag.
     * When leadAnchorNotificationEnabled is true the model
     * generates notification events with bounds that cover all the changes to
     * the selection plus the changes to the lead and anchor indices.
     * Setting the flag to false causes a norrowing of the event's bounds to
     * include only the elements that have been selected or deselected since
     * the last change. Either way, the model continues to maintain the lead
     * and anchor variables internally. The default is true.
     * @return          the value of the leadAnchorNotificationEnabled flag
     * @see             #setLeadAnchorNotificationEnabled(boolean)
     */
    public boolean isLeadAnchorNotificationEnabled() {
        return leadAnchorNotificationEnabled;
    }

    private void updateLeadAnchorIndices(int anchorIndex, int leadIndex) {
        if (leadAnchorNotificationEnabled) {
            if (this.anchorIndex != anchorIndex) {
                if (this.anchorIndex != -1) { // The unassigned state.
                    markAsDirty(this.anchorIndex);
                }
                markAsDirty(anchorIndex);
            }

            if (this.leadIndex != leadIndex) {
                if (this.leadIndex != -1) { // The unassigned state.
                    markAsDirty(this.leadIndex);
                }
                markAsDirty(leadIndex);
            }
        }
        this.anchorIndex = anchorIndex;
        this.leadIndex = leadIndex;
    }

    private boolean contains(int a, int b, int i) {
        return (i >= a) && (i <= b);
    }

    private void changeSelection(int clearMin, int clearMax,
                                 int setMin, int setMax, boolean clearFirst) {
        for(int i = Math.min(setMin, clearMin); i <= Math.max(setMax, clearMax); i++) {

            boolean shouldClear = contains(clearMin, clearMax, i);
            boolean shouldSet = contains(setMin, setMax, i);

            if (shouldSet && shouldClear) {
                if (clearFirst) {
                    shouldClear = false;
                }
                else {
                    shouldSet = false;
                }
            }

            if (shouldSet) {
                set(i);
            }
            if (shouldClear) {
                clear(i);
            }
        }
        fireValueChanged();
    }

   /*   Change the selection with the effect of first clearing the values
    *   in the inclusive range [clearMin, clearMax] then setting the values
    *   in the inclusive range [setMin, setMax]. Do this in one pass so
    *   that no values are cleared if they would later be set.
    */
    private void changeSelection(int clearMin, int clearMax, int setMin, int setMax) {
        changeSelection(clearMin, clearMax, setMin, setMax, true);
    }

    public void clearSelection() {
        removeSelectionInterval(minIndex, maxIndex);
    }

    public void setSelectionInterval(int index0, int index1) {
        if (index0 == -1 || index1 == -1) {
            return;
        }

        if (getSelectionMode() == SINGLE_SELECTION) {
            index0 = index1;
        }

        updateLeadAnchorIndices(index0, index1);

        int clearMin = minIndex;
        int clearMax = maxIndex;
        int setMin = Math.min(index0, index1);
        int setMax = Math.max(index0, index1);
        changeSelection(clearMin, clearMax, setMin, setMax);
    }

    public void addSelectionInterval(int index0, int index1)
    {
        if (index0 == -1 || index1 == -1) {
            return;
        }

        if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION) {
            setSelectionInterval(index0, index1);
            return;
        }

        updateLeadAnchorIndices(index0, index1);

        int clearMin = MAX;
        int clearMax = MIN;
        int setMin = Math.min(index0, index1);
        int setMax = Math.max(index0, index1);
        changeSelection(clearMin, clearMax, setMin, setMax);
    }

    public void removeSelectionInterval(int index0, int index1)
    {
        if (index0 == -1 || index1 == -1) {
            return;
        }

        updateLeadAnchorIndices(index0, index1);

        int clearMin = Math.min(index0, index1);
        int clearMax = Math.max(index0, index1);
        int setMin = MAX;
        int setMax = MIN;
        changeSelection(clearMin, clearMax, setMin, setMax);
    }

    private void setState(int index, boolean state) {
        if (state) {
            set(index);
        }
        else {
            clear(index);
        }
    }

    /**
     * Insert length indices beginning before/after index. If the value
     * at index is itself selected, set all of the newly inserted
     * items, otherwise leave them unselected. This method is typically
     * called to sync the selection model with a corresponding change
     * in the data model.
     */
    public void insertIndexInterval(int index, int length, boolean before)
    {
        /* The first new index will appear at insMinIndex and the last
         * one will appear at insMaxIndex
         */
        int insMinIndex = (before) ? index : index + 1;
        int insMaxIndex = (insMinIndex + length) - 1;

        /* Right shift the entire bitset by length, beginning with
         * index-1 if before is true, index+1 if it's false (i.e. with
         * insMinIndex).
         */
        for(int i = maxIndex; i >= insMinIndex; i--) {
            setState(i + length, value.get(i));
        }

        /* Initialize the newly inserted indices.
         */
        boolean setInsertedValues = value.get(index);
        for(int i = insMinIndex; i <= insMaxIndex; i++) {
            setState(i, setInsertedValues);
        }
    }

    /**
     * Remove the indices in the interval index0,index1 (inclusive) from
     * the selection model.  This is typically called to sync the selection
     * model width a corresponding change in the data model.  Note
     * that (as always) index0 can be greater than index1.
     */
    public void removeIndexInterval(int index0, int index1)
    {
        int rmMinIndex = Math.min(index0, index1);
        int rmMaxIndex = Math.max(index0, index1);
        int gapLength = (rmMaxIndex - rmMinIndex) + 1;

        /* Shift the entire bitset to the left to close the index0, index1
         * gap.
         */
        for(int i = rmMinIndex; i <= maxIndex; i++) {
            setState(i, value.get(i + gapLength));
        }
    }

    public void setValueIsAdjusting(boolean isAdjusting) {
        if (isAdjusting != this.isAdjusting) {
            this.isAdjusting = isAdjusting;
            this.fireValueChanged(isAdjusting);
        }
    }

    public String toString() {
        String s =  ((getValueIsAdjusting()) ? "~" : "=") + value.toString();
        return getClass().getName() + " " + Integer.toString(hashCode()) + " " + s;
    }

    /**
     * Returns a clone of the receiver with the same selection.
     * listenerLists are not duplicated.
     *
     * @return a clone of the receiver
     * @exception CloneNotSupportedException if the receiver does not
     *    both (a) implement the Cloneable interface
     *    and (b) define a clone method
     */
    public Object clone() throws CloneNotSupportedException {
        @SuppressWarnings("unchecked")
        OptionListModel<E> clone = (OptionListModel)super.clone();
        clone.value = (BitSet)value.clone();
        clone.listenerList = new EventListenerList();
        return clone;
    }

    public int getAnchorSelectionIndex() {
        return anchorIndex;
    }

    public int getLeadSelectionIndex() {
        return leadIndex;
    }

    /**
     * Set the anchor selection index, leaving all selection values unchanged.
     *
     * @see #getAnchorSelectionIndex
     * @see #setLeadSelectionIndex
     */
    public void setAnchorSelectionIndex(int anchorIndex) {
        this.anchorIndex = anchorIndex;
    }

    /**
     * Set the lead selection index, ensuring that values between the
     * anchor and the new lead are either all selected or all deselected.
     * If the value at the anchor index is selected, first clear all the
     * values in the range [anchor, oldLeadIndex], then select all the values
     * values in the range [anchor, newLeadIndex], where oldLeadIndex is the old
     * leadIndex and newLeadIndex is the new one.
     *

     * If the value at the anchor index is not selected, do the same thing in reverse,
     * selecting values in the old range and deselecting values in the new one.
     *

     * Generate a single event for this change and notify all listeners.
     * For the purposes of generating minimal bounds in this event, do the
     * operation in a single pass; that way the first and last index inside the
     * ListSelectionEvent that is broadcast will refer to cells that actually
     * changed value because of this method. If, instead, this operation were
     * done in two steps the effect on the selection state would be the same
     * but two events would be generated and the bounds around the changed values
     * would be wider, including cells that had been first cleared and only
     * to later be set.
     *

     * This method can be used in the mouseDragged() method of a UI class
     * to extend a selection.
     *
     * @see #getLeadSelectionIndex
     * @see #setAnchorSelectionIndex
     */
    public void setLeadSelectionIndex(int leadIndex) {
        int anchorIndex = this.anchorIndex;
        if (getSelectionMode() == SINGLE_SELECTION) {
            anchorIndex = leadIndex;
        }

        int oldMin = Math.min(this.anchorIndex, this.leadIndex);
        int oldMax = Math.max(this.anchorIndex, this.leadIndex);
        int newMin = Math.min(anchorIndex, leadIndex);
        int newMax = Math.max(anchorIndex, leadIndex);
        if (value.get(this.anchorIndex)) {
            changeSelection(oldMin, oldMax, newMin, newMax);
        }
        else {
            changeSelection(newMin, newMax, oldMin, oldMax, false);
        }
        this.anchorIndex = anchorIndex;
        this.leadIndex = leadIndex;
    }

    /**
     * This method is responsible for storing the state
     * of the initial selection.  If the selectionMode
     * is the default, i.e allowing only for SINGLE_SELECTION,
     * then the very last OPTION that has the selected
     * attribute set wins.
     */
    public void setInitialSelection(int i) {
        if (initialValue.get(i)) {
            return;
        }
        if (selectionMode == SINGLE_SELECTION) {
            // reset to empty
            initialValue.and(new BitSet());
        }
        initialValue.set(i);
    }

    /**
     * Fetches the BitSet that represents the initial
     * set of selected items in the list.
     */
    public BitSet getInitialSelection() {
        return initialValue;
    }
}


text:
package com.lling.qiqu.controllers;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lling.qiqu.beans.Comment;
import com.lling.qiqu.beans.Joke;
import com.lling.qiqu.beans.User;
import com.lling.qiqu.commons.Limit;
import com.lling.qiqu.commons.PageResult;
import com.lling.qiqu.commons.ResponseInfo;
import com.lling.qiqu.enums.CodeRespEnum;
import com.lling.qiqu.service.IJokeService;
import com.lling.qiqu.service.IUserService;
import com.lling.qiqu.thread.GetImgSizeThread;
import com.lling.qiqu.utils.Util;

/**
 * @ClassName: QuShiController
 * @Description: 接口访问控制器
 * @author lling
 * @date 2015-7-26
 */
@Controller
@RequestMapping("/api")
public class APIController {

	@Resource
	private IJokeService jokeService;

	@Resource
	private IUserService userServie;

	private Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 客户端添加趣事访问接口
	 * @param content
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qushi/add", method=RequestMethod.POST)
	public ResponseInfo addAPI(@RequestParam(required = true) String content, @RequestParam(required = true) int userId) {
		logger.info("添加趣事接口----------------------------start");
		ResponseInfo responseInfo = new ResponseInfo();
		if(Util.isEmpty(content)) {
			//参数无效
			responseInfo.setCode(CodeRespEnum.CODE_PARAM_INVALUD.getCode());
			return responseInfo;
		}

		Joke joke = new Joke();
		User user = userServie.getUserById(userId);
		if(user == null) {
			//用户不存在,使用默认用户
			joke.setUserId(1);
			joke.setUserNike("残剑");
			joke.setPortraitUrl("http://7xixxm.com2.z0.glb.clouddn.com/cc44325c-701b-4e97-8b93-c9187c75218e.jpg");
		} else {
			joke.setUserId(user.getId());
			joke.setUserNike(user.getUserNike());
			joke.setPortraitUrl(user.getPortraitUrl());
		}
		joke.setContent(content);
		joke.setIsPass(Joke.NOT_PASS);
		joke.setType(Joke.TYPE_QUSHI);
		joke.setCreateDate(new Date());
		jokeService.addJoke(joke);
		logger.info("添加趣事接口----------------------------end");
		responseInfo.setCode(CodeRespEnum.CODE_SUCCESS.getCode());
		return responseInfo;
	}

	/**
	 * 客户端获取所有/趣事/趣图/美图列表
	 * @param newOrHotFlag 最新最热排序标记
	 * @param offset
	 * @param count
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public ResponseInfo getListAPI(@RequestParam(value = "newOrHotFlag", required = false) Integer newOrHotFlag,
			@RequestParam(value = "type", required = false) Integer type,
			@RequestParam(value = "offset", required = false, defaultValue = "0") int offset,
			@RequestParam(value = "count", required = false, defaultValue = "10") int count) {
		logger.info("获取列表----------------------------");
		if(newOrHotFlag == null) {
			newOrHotFlag = Joke.SORT_NEW;
		}
		PageResult<Joke> page;
		Limit limit = Limit.buildLimit(offset, count);
		if(type == null) {
			page = jokeService.getJokes(limit, newOrHotFlag);
		} else {
			page = jokeService.getJokes(limit, type, newOrHotFlag);
		}

		ResponseInfo responseInfo = new ResponseInfo();
		responseInfo.setCode(CodeRespEnum.CODE_SUCCESS.getCode());
		responseInfo.setData(page);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return responseInfo;
	}

	/**
	 * 客户端获取所有列表
	 * @param newOrHotFlag 最新最热排序标记
	 * @param offset
	 * @param count
	 * @return
	 *//*
	@ResponseBody
	@RequestMapping(value="/all", method=RequestMethod.GET)
	public ResponseInfo getAllListAPI(@RequestParam(value = "newOrHotFlag", required = false) Integer newOrHotFlag,
			@RequestParam(value = "offset", required = false, defaultValue = "0") int offset,
			@RequestParam(value = "count", required = false, defaultValue = "10") int count) {
		logger.info("获取所有----------------------------");
		if(newOrHotFlag == null) {
			newOrHotFlag = Joke.SORT_NEW;
		}

		Limit limit = Limit.buildLimit(offset, count);
		PageResult<Joke> page = jokeService.getJokes(limit, newOrHotFlag);

		ResponseInfo responseInfo = new ResponseInfo();
		responseInfo.setCode(CodeRespEnum.CODE_SUCCESS.getCode());
		responseInfo.setData(page);
		return responseInfo;
	}*/

	/**
	 * 客户端获取趣事评论
	 * @param qushiId
	 * @param offset
	 * @param count
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/comments", method=RequestMethod.GET)
	public ResponseInfo getCommentsAPI(@RequestParam(value = "qushiId", required = true) int qushiId,
			@RequestParam(value = "offset", required = false, defaultValue = "0") int offset,
			@RequestParam(value = "count", required = false, defaultValue = "10") int count) {
		logger.info("获取趣事评论----------------------------,id:" + qushiId);
		Limit limit = Limit.buildLimit(offset, count);
		PageResult<Comment> page = jokeService.getCommentsByJokeId(limit, qushiId);

		ResponseInfo responseInfo = new ResponseInfo();
		responseInfo.setCode(CodeRespEnum.CODE_SUCCESS.getCode());
		responseInfo.setData(page);
		return responseInfo;
	}

	/**
	 * 顶
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/ding", method=RequestMethod.POST)
	public ResponseInfo dingJoke(@RequestParam(value = "ids", required = true) String ids) {
		logger.info("用户顶----------------------------,ids:" + ids);
		return jokeService.ding(ids);
	}

	/**
	 * 踩
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/cai", method=RequestMethod.POST)
	public ResponseInfo caiJoke(@RequestParam(value = "ids", required = true) String ids) {
		logger.info("用户踩----------------------------,ids:" + ids);
		return jokeService.cai(ids);
	}

	/**
	 * 根据jokeId获取joke对象
	 * @param jokeId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/get_joke", method=RequestMethod.GET)
	public ResponseInfo getjokeById(@RequestParam(value = "jokeId", required = true) Integer jokeId) {
		logger.info("获取Joke----------------------------,jokeId:" + jokeId);
		return jokeService.getJokeByIdAPI(jokeId);
	}

	/**
	 * 用户评论接口
	 * @param jokeId
	 * @param userId
	 * @param userPortrait
	 * @param userNick
	 * @param content
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/comment", method=RequestMethod.POST)
	public ResponseInfo addCommentAPI(@RequestParam(value = "jokeId", required = true) Integer jokeId,
			@RequestParam(value = "userId", required = true) Integer userId,
			@RequestParam(value = "userPortrait", required = false) String userPortrait,
			@RequestParam(value = "userNick", required = true) String userNick,
			@RequestParam(value = "content", required = true) String content) {
		logger.info("用户评论----------------------------,jokeId:" + jokeId);
		return jokeService.addComment(jokeId, userId, userPortrait, userNick, content);
	}

	/**
	 * 客户端添加趣图访问接口
	 * @param content
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qutu/add", method=RequestMethod.POST)
	public ResponseInfo addAPI(@RequestParam(required = true) String title, @RequestParam(required = true) String imgUrl, @RequestParam(required = true) int userId) {
		logger.info("添加趣图接口----------------------------start");
		ResponseInfo responseInfo = new ResponseInfo();
		if(Util.isEmpty(imgUrl)) {
			//参数无效
			responseInfo.setCode(CodeRespEnum.CODE_PARAM_INVALUD.getCode());
			return responseInfo;
		}

		Joke joke = new Joke();
		User user = userServie.getUserById(userId);
		if(user == null) {
			//用户不存在,使用默认用户
			joke.setUserId(1);
			joke.setUserNike("残剑");
			joke.setPortraitUrl("http://7xixxm.com2.z0.glb.clouddn.com/cc44325c-701b-4e97-8b93-c9187c75218e.jpg");
		} else {
			joke.setUserId(user.getId());
			joke.setUserNike(user.getUserNike());
			joke.setPortraitUrl(user.getPortraitUrl());
		}
		joke.setTitle(title);
		joke.setImgUrl(imgUrl);
		joke.setIsPass(Joke.NOT_PASS);
		joke.setType(Joke.TYPE_QUTU);
		joke.setCreateDate(new Date());
		int jokeId = jokeService.addJoke(joke);
		Joke newJoke = jokeService.getJokeById(jokeId);
		new GetImgSizeThread(newJoke, jokeService).start();
		logger.info("添加趣图接口----------------------------end");
		responseInfo.setCode(CodeRespEnum.CODE_SUCCESS.getCode());
		return responseInfo;
	}

	/**
	 * 客户端添加趣事访问接口
	 * @param content
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public ResponseInfo addMeiTuAPI(@RequestParam(required = true) String title, @RequestParam(required = true) String imgUrl, @RequestParam(required = true) int userId) {
		logger.info("添加美图接口----------------------------start");
		ResponseInfo responseInfo = new ResponseInfo();
		if(Util.isEmpty(imgUrl)) {
			//参数无效
			responseInfo.setCode(CodeRespEnum.CODE_PARAM_INVALUD.getCode());
			return responseInfo;
		}

		Joke joke = new Joke();
		User user = userServie.getUserById(userId);
		if(user == null) {
			//用户不存在,使用默认用户
			joke.setUserId(1);
			joke.setUserNike("残剑");
			joke.setPortraitUrl("http://7xixxm.com2.z0.glb.clouddn.com/cc44325c-701b-4e97-8b93-c9187c75218e.jpg");
		} else {
			joke.setUserId(user.getId());
			joke.setUserNike(user.getUserNike());
			joke.setPortraitUrl(user.getPortraitUrl());
		}
		joke.setTitle(title);
		joke.setImgUrl(imgUrl);
		joke.setIsPass(Joke.NOT_PASS);
		joke.setType(Joke.TYPE_MEITU);
		joke.setCreateDate(new Date());
		int jokeId = jokeService.addJoke(joke);
		Joke newJoke = jokeService.getJokeById(jokeId);
		new GetImgSizeThread(newJoke, jokeService).start();
		logger.info("添加美图接口----------------------------end");
		responseInfo.setCode(CodeRespEnum.CODE_SUCCESS.getCode());
		return responseInfo;
	}
}


text:
function handles = addTag(handles,hObject)

maxNrOfTags = 6;
minNrOfTags = 0;

contents = get(handles.listboxTags,'String');
if length(contents) < maxNrOfTags
   contents{end+1} = handles.tagNames{length(contents)+1};
   set(handles.listboxTags,'String',contents)
   set(handles.listboxTags,'Value',length(contents))
end

if length(contents) == maxNrOfTags
    set(hObject,'Enable','off')
end
if length(contents) > minNrOfTags
    set(handles.pushbuttonRemove,'Enable','on')
    set(handles.sliderTime,'Enable','on')
end

handles.tags(1,length(contents)) = 1;
handles.tags(2,length(contents)) = 1;
handles.currentTag = get(handles.listboxTags,'Value');
intVal = calcInterval(handles.tags(2,handles.currentTag),handles.H);
set(handles.editTag,'String',intVal)
set(handles.sliderTime,'Value',handles.tags(2,handles.currentTag))
handles.TagContents = get(handles.listboxTags,'String');

if sum(handles.tags(1,:)) == 0
    set(handles.pushbuttonSegment,'Enable','off')
else
    set(handles.pushbuttonSegment,'Enable','on')
end


text:
import React from 'react';

import { Breadcrumb } from './breadcrumb';

export default {
  title: 'Navigation | Breadcrumb',
};

export const _default = () => (
  <Breadcrumb
    className="breadcrumb"
    crumbs={[{ id: '1', node: 'Documents' }, { id: '2', node: 'Deployment', onClick: () => {} }, { id: '3', node: 'Another' }]}
  />
);


text:
<?php
	/**
	*
	*/
	class Upload_model extends CI_Model
	{
		function get_all_upload()
		{
			return $this->db->query("SELECT * FROM galeri;");
		}

		function cari_folder($id){
			return $this->db->query("SELECT galeri.letak_folder FROM galeri WHERE galeri.id_galeri = '".$id."'");
		}

		function get_all_paging_sorting_upload($jtStartIndex,$jtPageSize,$jtSorting)
		{
			return $this->db->query("SELECT * FROM galeri ORDER BY '".$jtSorting."' LIMIT ".$jtStartIndex.",".$jtPageSize.";");
		}
		function post_create_upload($judul,$tanggal,$upl){
			return $this->db->query("INSERT INTO galeri(nama_galeri,tanggal_buat_galeri, letak_folder) VALUES ('".$judul."','".$tanggal."','".$upl."');");
		}

		function get_create_upload(){
			return $this->db->query("SELECT * FROM galeri WHERE galeri.id_galeri = LAST_INSERT_ID();");
		}

		function post_update_upload($id,$answer){
			return $this->db->query("UPDATE galeri SET galeri.nama_galeri = '".$answer."' WHERE galeri.id_galeri = '".$id."';");
		}

		function post_delete_upload($id){
			return $this->db->query("DELETE FROM galeri WHERE galeri.id_galeri = '".$id."'; ");
		}
	}

 ?>


text:
package net.firejack.platform.core.model.registry.resource;

import net.firejack.platform.api.content.model.ResourceType;
import net.firejack.platform.core.model.registry.RegistryNodeType;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

@Entity
@DiscriminatorValue("FIL")
public class FileResourceModel extends ResourceModel<FileResourceVersionModel> {
    private static final long serialVersionUID = -1704756476149750044L;

    @Transient
    public FileResourceVersionModel getResourceVersion() {
        return resourceVersion;
    }

    /**
     * @param resourceVersion
     */
    public void setResourceVersion(FileResourceVersionModel resourceVersion) {
        this.resourceVersion = resourceVersion;
    }

    @Transient
    public ResourceType getResourceType() {
        return ResourceType.FILE;
    }

    @Override
    @Transient
    public RegistryNodeType getType() {
        return RegistryNodeType.FILE_RESOURCE;
    }

}


text:
"use strict";

import React from "react";
import { ContextMenu, MenuItem } from "../../src";
import MenuTypes from "./constants";

const Menu = React.createClass({
    displayName: "Menu",
    handleClick(data) {
        window.alert(`Clicked on menu ${data.item}`);
    },
    render() {
        return (
            <ContextMenu identifier={MenuTypes.simple}>
                <MenuItem onSelect={this.handleClick} data={{item: "item 1"}}>Menu Item 1</MenuItem>
                <MenuItem onSelect={this.handleClick} data={{item: "item 2"}}>Menu Item 2</MenuItem>
            </ContextMenu>
        );
    }
});

export default Menu;