text:
using Google.VisualStudioFake.API;
using Google.VisualStudioFake.API.UI;
using Google.VisualStudioFake.Internal.Interop;
using Google.VisualStudioFake.Internal.Jobs;
using Google.VisualStudioFake.Util;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Threading;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Google.VisualStudioFake.Internal.UI
{
    /// <summary>
    /// Contains logic to set fired breakpoints.
    /// </summary>
    public interface IFiredBreakpointSetter
    {
        /// <summary>
        /// Sets the bound breakpoints that fired at the current code location.
        /// </summary>
        void Set(IEnumerable<IDebugBoundBreakpoint2> boundBreakpoints);
    }

    public class BreakpointsWindow : IBreakpointsWindow, IFiredBreakpointSetter
    {
        readonly IList<Breakpoint> _breakpoints = new List<Breakpoint>();

        readonly IDictionary<IDebugPendingBreakpoint2, Breakpoint> _pendingToBreakpoint =
            new Dictionary<IDebugPendingBreakpoint2, Breakpoint>();

        readonly IDebugSessionContext _debugSessionContext;
        readonly IJobQueue _jobQueue;
        readonly JoinableTaskContext _taskContext;

        IBreakpoint _firedBreakpoint;

        public BreakpointsWindow(IDebugSessionContext debugSessionContext, IJobQueue jobQueue,
                                 JoinableTaskContext taskContext)
        {
            _debugSessionContext = debugSessionContext;
            _jobQueue = jobQueue;
            _taskContext = taskContext;
        }

        #region IBreakpointsWindow

        public IBreakpoint Add(string filename, int lineNumber) =>
            Add(new Breakpoint(() => new FileLineBreakpointRequest(filename, lineNumber),
                               $"Breakpoint at {filename}:{lineNumber}"));

        public IBreakpoint SetPassCount(IBreakpoint breakpoint, uint count, PassCountStyle style)
        {
            CheckState(breakpoint, "set pass count for");

            Breakpoint bp = _breakpoints.FirstOrDefault(b => b == breakpoint);
            bp.PassCount = count;
            bp.PassCountStyle = style;

            if (_debugSessionContext.ProgramState == ProgramState.Running ||
                _debugSessionContext.ProgramState == ProgramState.AtBreak)
            {
                _jobQueue.Push(new GenericJob(() => SetPassCount(bp),
                                              $"Set pass count {bp.PassCount}, style " +
                                              $"{bp.PassCountStyle} for breakpoint {bp}"));
            }

            return breakpoint;
        }

        public IList<IBreakpoint> GetBreakpoints() => new List<IBreakpoint>(_breakpoints);

        public void Delete(IBreakpoint breakpoint)
        {
            CheckState(breakpoint, "delete");
            QueueDelete(_breakpoints.FirstOrDefault(b => b == breakpoint));
        }

        public void DeleteAll()
        {
            foreach (var bp in _breakpoints)
            {
                QueueDelete(bp);
            }
        }

        public IBreakpoint FiredBreakpoint
        {
            get =>
                _debugSessionContext.ProgramState == ProgramState.AtBreak
                    ? _firedBreakpoint
                    : null;
            private set => _firedBreakpoint = value;
        }

        #endregion

        #region Internal API

        public IEnumerable<IBreakpoint> BindPendingBreakpoints()
        {
            IEnumerable<Breakpoint> pendingBreakpoints = _breakpoints.Where(
                b => b.State == BreakpointState.RequestedPreSession);
            foreach (Breakpoint bp in pendingBreakpoints)
            {
                Bind(bp);
                if (bp.PassCount != 0 && bp.PassCountStyle != PassCountStyle.None)
                {
                    SetPassCount(bp);
                }
            }

            return pendingBreakpoints;
        }

        public void HandleBindResultEvent(DebugEventArgs args)
        {
            if (args.Event is IDebugBreakpointBoundEvent2)
            {
                HandleBoundEvent((IDebugBreakpointBoundEvent2) args.Event);
            }
            else if (args.Event is IDebugBreakpointErrorEvent2)
            {
                HandleErrorEvent((IDebugBreakpointErrorEvent2) args.Event);
            }
        }

        #endregion

        #region IFiredBreakpointSetter

        public void Set(IEnumerable<IDebugBoundBreakpoint2> boundBreakpoints)
        {
            if (!boundBreakpoints.Any())
            {
                FiredBreakpoint = null;
                return;
            }

            IDebugPendingBreakpoint2 pendingBreakpoint;
            HResultChecker.Check(boundBreakpoints.First()
                                     .GetPendingBreakpoint(out pendingBreakpoint));
            FiredBreakpoint = _pendingToBreakpoint[pendingBreakpoint];
        }

        #endregion

        void HandleBoundEvent(IDebugBreakpointBoundEvent2 evnt)
        {
            IDebugPendingBreakpoint2 pendingBreakpoint;
            HResultChecker.Check(evnt.GetPendingBreakpoint(out pendingBreakpoint));
            var state = new PENDING_BP_STATE_INFO[1];
            HResultChecker.Check(pendingBreakpoint.GetState(state));
            var breakpoint = _pendingToBreakpoint[pendingBreakpoint];
            breakpoint.State = ToBreakpointState(state[0].state);
        }

        void HandleErrorEvent(IDebugBreakpointErrorEvent2 evnt)
        {
            IDebugErrorBreakpoint2 errorBreakpoint;
            HResultChecker.Check(evnt.GetErrorBreakpoint(out errorBreakpoint));
            IDebugErrorBreakpointResolution2 errorBreakpointResolution;
            HResultChecker.Check(
                errorBreakpoint.GetBreakpointResolution(out errorBreakpointResolution));
            var errorResolutionInfo = new BP_ERROR_RESOLUTION_INFO[1];
            HResultChecker.Check(errorBreakpointResolution.GetResolutionInfo(
                                     enum_BPERESI_FIELDS.BPERESI_MESSAGE, errorResolutionInfo));
            IDebugPendingBreakpoint2 pendingBreakpoint;
            HResultChecker.Check(errorBreakpoint.GetPendingBreakpoint(out pendingBreakpoint));
            var breakpoint = _pendingToBreakpoint[pendingBreakpoint];
            breakpoint.Error = errorResolutionInfo[0].bstrMessage;
            breakpoint.State = BreakpointState.Error;
        }

        void Bind(Breakpoint breakpoint)
        {
            using (var breakpointRequest = breakpoint.CreateRequest())
            {
                IDebugPendingBreakpoint2 pendingBreakpoint = null;
                _taskContext.RunOnMainThread(() => HResultChecker.Check(
                                                 _debugSessionContext.DebugEngine
                                                     .CreatePendingBreakpoint(
                                                         breakpointRequest,
                                                         out pendingBreakpoint)));
                breakpoint.PendingBreakpoint = pendingBreakpoint;
                _pendingToBreakpoint[pendingBreakpoint] = breakpoint;
                HResultChecker.Check(pendingBreakpoint.Enable(1));
                if (pendingBreakpoint.Virtualize(1) != VSConstants.E_NOTIMPL)
                {
                    throw new InvalidOperationException("VSFake should be updated to handle " +
                                                        $"{nameof(pendingBreakpoint.Virtualize)}.");
                }

                pendingBreakpoint.Bind();
            }
        }

        IBreakpoint Add(Breakpoint breakpoint)
        {
            if (_debugSessionContext.ProgramState == ProgramState.Terminated)
            {
                throw new InvalidOperationException(
                    "Breakpoint cannot be added because the program has terminated.");
            }

            _breakpoints.Add(breakpoint);
            if (_debugSessionContext.ProgramState == ProgramState.Running ||
                _debugSessionContext.ProgramState == ProgramState.AtBreak)
            {
                _jobQueue.Push(new GenericJob(() => Bind(breakpoint)));
            }

            return breakpoint;
        }

        BreakpointState ToBreakpointState(enum_PENDING_BP_STATE state)
        {
            switch (state)
            {
                case enum_PENDING_BP_STATE.PBPS_DELETED:
                    return BreakpointState.Deleted;
                case enum_PENDING_BP_STATE.PBPS_DISABLED:
                    return BreakpointState.Disabled;
                case enum_PENDING_BP_STATE.PBPS_ENABLED:
                    return BreakpointState.Enabled;
                default:
                    return BreakpointState.Error;
            }
        }

        void SetPassCount(Breakpoint breakpoint)
        {
            // Set pass count on pending breakpoint.
            BP_PASSCOUNT pc = new BP_PASSCOUNT();
            pc.dwPassCount = breakpoint.PassCount;
            pc.stylePassCount = ToVsStyle(breakpoint.PassCountStyle);
            HResultChecker.Check(breakpoint.PendingBreakpoint.SetPassCount(pc));

            // Also set pass count on all bound breakpoints.
            HResultChecker.Check(
                breakpoint.PendingBreakpoint.EnumBoundBreakpoints(
                    out IEnumDebugBoundBreakpoints2 boundBreakpointsEnum));
            HResultChecker.Check(boundBreakpointsEnum.Reset());
            HResultChecker.Check(boundBreakpointsEnum.GetCount(out uint numBound));
            var boundBreakpoints = new IDebugBoundBreakpoint2[numBound];
            uint actual = 0;
            HResultChecker.Check(boundBreakpointsEnum.Next(numBound, boundBreakpoints, ref actual));
            if (actual != numBound)
            {
                throw new VSFakeException("Could not fetch all bound breakpoints. " +
                                          $"Expected: {numBound}, got: {actual}");
            }

            foreach (var bp in boundBreakpoints)
            {
                HResultChecker.Check(bp.SetPassCount(pc));
            }
        }

        void QueueDelete(Breakpoint breakpoint)
        {
            CheckState(breakpoint, "delete");

            bool shouldDeleteInteropBreakpoint = breakpoint.State == BreakpointState.Disabled ||
                breakpoint.State == BreakpointState.Enabled;
            breakpoint.State = BreakpointState.Pending;
            _jobQueue.Push(new GenericJob(() =>
            {
                if (shouldDeleteInteropBreakpoint)
                {
                    HResultChecker.Check(breakpoint.PendingBreakpoint.Delete());
                }

                breakpoint.State = BreakpointState.Deleted;
                _breakpoints.Remove(breakpoint);
                if (breakpoint.PendingBreakpoint != null)
                {
                    _pendingToBreakpoint.Remove(breakpoint.PendingBreakpoint);
                }
            }, $"Delete breakpoint ({breakpoint})"));
        }

        enum_BP_PASSCOUNT_STYLE ToVsStyle(PassCountStyle style)
        {
            switch (style)
            {
                case PassCountStyle.None: return enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_NONE;
                case PassCountStyle.Equal: return enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL;
                case PassCountStyle.EqualOrGreater:
                    return enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL_OR_GREATER;
                case PassCountStyle.Mod: return enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_MOD;
            }

            throw new InvalidOperationException($"Unhandled pass count style: {style}");
        }

        void CheckState(IBreakpoint breakpoint, string operation)
        {
            if (breakpoint.State == BreakpointState.Pending ||
                breakpoint.State == BreakpointState.Deleted)
            {
                throw new InvalidOperationException(
                    $"Cannot {operation} breakpoint ({breakpoint}); state = {breakpoint.State}.");
            }
        }
    }
}


text:
package com.xinqihd.sns.gameserver.session;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.MessageLite;
import com.xinqihd.sns.gameserver.GameContext;
import com.xinqihd.sns.gameserver.Stat;
import com.xinqihd.sns.gameserver.ai.AIManager;
import com.xinqihd.sns.gameserver.ai.SessionAIMessage;
import com.xinqihd.sns.gameserver.config.Constant;
import com.xinqihd.sns.gameserver.config.GlobalConfig;
import com.xinqihd.sns.gameserver.entity.user.User;
import com.xinqihd.sns.gameserver.transport.XinqiMessage;
import com.xinqihd.sns.gameserver.util.StringUtil;

/**
 * MinaMessageQueue is a MessageQueue implementation for Mina framework.
 * It can asynchrously write the message back to user.
 *
 * @author wangqi
 *
 */
public class MinaMessageQueue extends IoHandlerAdapter implements MessageQueue {

	private static final Logger logger = LoggerFactory.getLogger(MinaMessageQueue.class);

	private static final MessageQueue instance = new MinaMessageQueue();

	/**
	 * The underlying message quee.
	 */
	private LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();

	/**
	 * The resource lock for this queue.
	 */
	private Lock lock = new ReentrantLock();

	private int numberOfCpuCores = 1;//Constant.CPU_CORES;

	private ExecutorService writeService = null;

	private String messageServerZkRoot = null;

	/**
	 * It is the map to store message client tunnel to other MessageServers.
	 */
	private ConcurrentHashMap<String, MessageClient> messageClientMap = new ConcurrentHashMap<String, MessageClient>(8);

	private String localMessageServerId = null;

	//private ConfigWatcher configWatcher = new ConfigWatcher();

	//Synchronized write
	private boolean syncWrite = false;

	/**
	 * Instead create new instance, call the getInstance() to get a Singleton.
	 *
	 * Note: The ReloadClassLoader will call this constructor so it is public.
	 */
	public MinaMessageQueue() {
		if ( numberOfCpuCores < 1 ) {
			numberOfCpuCores = 2;
		}
		if ( logger.isDebugEnabled() ) {
			logger.debug("Start #" + numberOfCpuCores + " for processing session.write");
		}

		//Get zookeeper's root
		messageServerZkRoot = GlobalConfig.getInstance().getStringProperty(GlobalConfig.RUNTIME_MESSAGE_LIST_ROOT);
		localMessageServerId = GlobalConfig.getInstance().getStringProperty(GlobalConfig.RUNTIME_MESSAGE_SERVER_ID);

		if ( logger.isDebugEnabled() ) {
			logger.debug("MessageServerListRoot: " + messageServerZkRoot + ", localMessageServerId: " + localMessageServerId);
		}
		if ( !syncWrite ) {
			writeService = Executors.newFixedThreadPool(numberOfCpuCores);
			for ( int i=0; i<numberOfCpuCores; i++ ) {
				writeService.submit(new SessionWriteTask(this.messageQueue));
			}
		}
	}

	/**
	 * Initialize the MessageQueue
	 */
	@Override
	public final void initQueue() {
		/*
		try {
			ZooKeeperFacade facade = ZooKeeperFactory.getInstance();
			if ( facade != null ) {
				ZooKeeper zooKeeper = facade.getZooKeeper();
				List<String> messageServers = zooKeeper.getChildren(messageServerZkRoot, configWatcher);
				setUpMessageClient(messageServers);
			} else {
				if ( logger.isWarnEnabled() ) {
					logger.warn("ZooKeeper is unavailable");
				}
			}
		} catch (Throwable e) {
			logger.warn("#initQueue exception: {}", e.getMessage());
			logger.debug(e.getMessage(), e);
		}
		*/
	}

	/**
	 * Destroy the MessageQueue
	 */
	@Override
	public final void destroyQueue() {
		Set<String> serverKeySet = messageClientMap.keySet();
		for ( String serverKey : serverKeySet ) {
			MessageClient client = messageClientMap.remove(serverKey);
			if ( client != null ) {
				client.disconnectFromServer();
				client = null;
			}
			if ( logger.isDebugEnabled() ) {
				logger.debug("Close down the MessageClient: " + client);
			}
		}
	}

	/**
	 * Set up the message server map. Note a server may be added or removed.
	 * @param messageServerIds
	 */
	public final void setUpMessageClient(List<String> messageServerIds) {
		//Remove those obsolete servers
		ArrayList<String> servers = new ArrayList<String>(messageServerIds);
		Collections.sort(servers);
		Set<String> serverKeySet = messageClientMap.keySet();
		for ( String serverKey : serverKeySet ) {
			int index = Collections.binarySearch(servers, serverKey);
			if ( index < 0 ) {
				MessageClient client = messageClientMap.remove(serverKey);
				if ( client != null ) {
					client.disconnectFromServer();
					client = null;
				}
				if ( logger.isDebugEnabled() ) {
					logger.debug("Remove a obsolete MessageServer: " + serverKey);
				}
			}
		}

		for ( String messageServerId : servers ) {
			if ( localMessageServerId.equals(messageServerId) ) {
				if ( logger.isDebugEnabled() ) {
					logger.debug("Ignore same JVM MessageServer: " + messageServerId);
				}
				continue;
			}
			MessageClient client = messageClientMap.get(messageServerId);
			if ( client == null ) {
				client = setUpSingleMessageClient(messageServerId);
			} // if client == null...
			else {
				if ( logger.isDebugEnabled() ) {
					logger.debug("The connection to MessageServer: " + messageServerId + " is already open");
				}
			}
		}
	}

	/**
	 * Setup a single message client by the given machineid.
	 * @param messageServerId
	 * @return
	 */
	public MessageClient setUpSingleMessageClient(String messageServerId) {
		MessageClient client = null;
		int colonIndex = messageServerId.indexOf(':');
		String host = null;
		int port = 0;
		if ( colonIndex > 0 && colonIndex < messageServerId.length() ) {
			host = messageServerId.substring(0, colonIndex);
			port = StringUtil.toInt(messageServerId.substring(colonIndex+1), 0);
		}
		if ( host != null && host.length()>0 && port > 0 && port < 65536 ) {
			client = new MessageClient(host, port);
			client.connectToServer();
			messageClientMap.put(messageServerId, client);
			if ( logger.isDebugEnabled() ) {
				logger.debug("Add a new MessageServer: " + host+":"+port);
			}
		}
		return client;
	}

	/**
	 * Get the Singleton impelmentation.
	 * @return
	 */
	public static MessageQueue getInstance() {
		return instance;
	}

	/**
	 * Get an exception when connected.
	 */
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		Stat.getInstance().messageServerReceivedFail++;
		logger.warn("#exceptionCaught exception: {}", cause.getMessage());
		if ( logger.isDebugEnabled() ) {
			logger.debug(session.getRemoteAddress().toString(), cause.getCause());
		}
	}

	/**
	 * Directly output a message to local JVM
	 */
	@Override
	public void sessionWrite(IoSession session, Object message, SessionKey sessionKey) {
		try {
			lock.lock();
			if ( session == null ) {
				//It is in the JUnit test mode.
				return;
			}
			XinqiMessage xinqiMessage = null;
			IoBuffer ioBuffer = null;
			if ( message instanceof XinqiMessage ) {
				xinqiMessage = (XinqiMessage)message;
				xinqiMessage.index = (int)(System.currentTimeMillis()/1000);
			} else if ( message instanceof MessageLite ) {
				xinqiMessage = new XinqiMessage();
				xinqiMessage.payload = (MessageLite)message;
				xinqiMessage.index = (int)(System.currentTimeMillis()/1000);
			} else if ( message instanceof IoBuffer ) {
				ioBuffer = (IoBuffer)message;
			}

			Message msg = new Message();
			if ( sessionKey != null ) {
				User user = GameContext.getInstance().findLocalUserBySessionKey(sessionKey);
				if ( user.isAI() ) {
					SessionAIMessage aiMessage = new SessionAIMessage();
					aiMessage.setMessage(xinqiMessage);
					aiMessage.setSessionKey(sessionKey);
					msg.message = aiMessage;
					msg.session = session;
				} else {
					if ( xinqiMessage != null ) {
						msg.message = xinqiMessage;
					} else {
						msg.message = ioBuffer;
					}
					msg.session = session;
				}
			} else {
				if ( xinqiMessage != null ) {
					msg.message = xinqiMessage;
				} else {
					msg.message = ioBuffer;
				}
				msg.session = session;
			}

			//TODO test the synchronized method to send message
			//wangqi 2012-7-13
			if ( syncWrite ) {
				writeResponse(msg);
			} else {
				messageQueue.put(msg);
				Stat.getInstance().writeQueueSize++;
			}

			if ( logger.isDebugEnabled() ) {
				SessionKey key = (SessionKey)session.getAttribute(Constant.SESSION_KEY);
				logger.debug("Queue a write message to session: " + key + ", SocketAddress: " + session.getRemoteAddress());
			}
		} catch ( Exception e) {
			logger.debug("#sessionWrite exception: {}", e);
			logger.warn(e.getMessage());
		} finally {
			lock.unlock();
		}
	}

	/**
	 * Send a message to client.
	 *
	 * @param sessionKey
	 * @param message
	 */
	@Override
	public void sessionWrite(SessionKey sessionKey, Object message) {
		if ( sessionKey == null || message == null ) return;
			//Find the user at local jvm session table
			IoSession userSession = findSession(sessionKey);
			if ( userSession == null ) {
				//TODO The user exists in a different GameServer.
				//find the machineid for this session.
				//send it thru messageclient.
				try {
					//First check if it is a remote AI user
					boolean isAI = AIManager.getInstance().isAIUser(sessionKey);
					if ( isAI ) {
						XinqiMessage xinqi = null;
						if ( message instanceof XinqiMessage ) {
							xinqi = (XinqiMessage)message;
							xinqi.index = (int)(System.currentTimeMillis()/1000);
						} else if ( message instanceof MessageLite ) {
							MessageLite liteMessage = (MessageLite)message;
							xinqi = new XinqiMessage();
							xinqi.payload = liteMessage;
							xinqi.index = (int)(System.currentTimeMillis()/1000);
						}
						SessionAIMessage aiMessage = new SessionAIMessage();
						aiMessage.setMessage(xinqi);
						aiMessage.setSessionKey(sessionKey);

						AIManager.getInstance().sendClientMessageToAIServer(
								aiMessage.getSessionKey(), aiMessage);
					} else {
						String machineId = GameContext.getInstance().findMachineId(sessionKey);
						if ( machineId != null ) {
							MessageClient client = messageClientMap.get(machineId);
							if ( client == null ) {
								if ( logger.isDebugEnabled() ) {
									logger.debug("Not found MessageClient for machineid: " + machineId+", Try to setup it.");
								}
								client = setUpSingleMessageClient(machineId);
							}
							if ( client == null ) {
								return;
							}
							if ( message instanceof XinqiMessage ) {
								SessionRawMessage rawMessage = new SessionRawMessage();
								rawMessage.setSessionkey(sessionKey);
								XinqiMessage xinqi = (XinqiMessage)message;
								xinqi.index = (int)(System.currentTimeMillis()/1000);
								rawMessage.setRawMessage(xinqi.toByteArray());

								client.sendMessageToServer(rawMessage);
							} else if ( message instanceof MessageLite ) {
								SessionRawMessage rawMessage = new SessionRawMessage();
								rawMessage.setSessionkey(sessionKey);
								MessageLite liteMessage = (MessageLite)message;
								XinqiMessage xinqi = new XinqiMessage();
								xinqi.payload = liteMessage;
								xinqi.index = (int)(System.currentTimeMillis()/1000);
								rawMessage.setRawMessage(xinqi.toByteArray());

								client.sendMessageToServer(rawMessage);
							} else if ( message instanceof SessionRawMessage ){
								client.sendMessageToServer((SessionRawMessage)message);
							} else {
								if ( logger.isDebugEnabled() ) {
									logger.debug("sessionWrite not support message type " + message.getClass());
								}
							}
						} else {
							if ( logger.isDebugEnabled() ) {
								logger.debug("Cannot send message to user because the machineid is null.");
							}
						}
					}
				} catch (Throwable e) {
					logger.warn("Send message exception: {}", e.getMessage());
					logger.debug("Send message exception", e);
				}
			} else {
				if ( logger.isDebugEnabled() ) {
					logger.debug("Send message to this GameServer.");
				}
				sessionWrite(userSession, message, sessionKey);
			}
	}

	/**
	 * Find a IoSession by its session key.
	 * @param sessionKey
	 * @return
	 */
	@Override
	public IoSession findSession(SessionKey sessionKey) {
		return GameContext.getInstance().findLocalUserIoSession(sessionKey);
	}

	/**
	 * Write the response back
	 * @param message
	 */
	private static void writeResponse(Message message) {
		try {
			//Write the actual message to session.
			if ( message == null || message.message == null ) {
				if ( logger.isDebugEnabled() ) {
					logger.debug("Message to send is null.");
				}
			} else {
				if ( message.message instanceof SessionAIMessage ) {
					//The sendClientMessageToAIServer support reconnect to server.
					SessionAIMessage sessionAIMessage = (SessionAIMessage)message.message;
					AIManager.getInstance().sendClientMessageToAIServer(
							sessionAIMessage.getSessionKey(), sessionAIMessage);
				} else if ( message.session != null && message.session.isConnected() ) {
					message.session.write(message.message);
					if ( message.message instanceof XinqiMessage ) {
						XinqiMessage xinqi = (XinqiMessage)message.message;
						if ( logger.isDebugEnabled() ) {
							logger.debug("Send to client:" + message.session.getRemoteAddress()
									+ ", message: " + message.message );
						}
						/*
						if ( logger.isInfoEnabled() ) {
							int currentSecond = (int)(System.currentTimeMillis()/1000);
							logger.info("message type:{}, second elapse:{}", xinqi.type, currentSecond-xinqi.index);
						}
						*/
					}
				} else {
					if ( logger.isDebugEnabled() ) {
						logger.debug("Client address: " + message.session.getRemoteAddress() + " has been closed.");
					}
				}
			}
		} catch (Throwable e) {
			logger.warn("SessionWriteTask.run exception: {}", e.getMessage());
			logger.debug(e.getMessage(), e);
		}
	}

	/**
	 * The backgroud session write task
	 * @author wangqi
	 *
	 */
	private static class SessionWriteTask implements Runnable {

		private LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();

		public SessionWriteTask(LinkedBlockingQueue<Message> messageQueue) {
			this.messageQueue = messageQueue;
		}

		public void run() {
			for ( ; ; ) {
				try {
					Message message = messageQueue.take();
					writeResponse(message);
					Stat.getInstance().writeQueueSize--;
					Stat.getInstance().gameServerSent++;
				} catch (InterruptedException e) {
				}
			}
		}
	}

	/**
	 * The internal message for queue.
	 * @author wangqi
	 *
	 */
	private static class Message {
		IoSession session;
		Object message;
	}

	/**
	 * Watch the config path.
	 * @author wangqi
	 *
	 */
	/*
	class ConfigWatcher implements Watcher {

		public void process(WatchedEvent event) {
			if ( logger.isDebugEnabled() ) {
				logger.debug("Event type="+event.getType()+", path="+event.getPath() + " changed. Read it again. ");
			}
			initQueue();
			if ( event.getType() == Watcher.Event.EventType.NodeDeleted ) {
				if ( logger.isDebugEnabled() ) {
					logger.debug(event.getPath() + " is deleted.");
				}
			}
		}
	}
	*/
}

redpajama_set_name: RedPajamaGithub


text:
package org.carrot2.workbench.editors.impl.numeric;

import java.util.Map;

import org.carrot2.workbench.core.helpers.GUIFactory;
import org.carrot2.workbench.editors.*;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;

/**
 * An dummy editor for read-only numerics.
 */
final class ReadOnlyEditor extends AttributeEditorAdapter
{
    /** */
    private Text text;

    /** */
    private Object lastValue;

    @Override
    protected AttributeEditorInfo init(Map<String,Object> defaultValues)
    {
        return new AttributeEditorInfo(1, false);
    }

    /*
     * Return the current editor value.
     */
    @Override
    public Object getValue()
    {
        return lastValue;
    }

    @Override
    public void setValue(Object object)
    {
        if (lastValue == object)
        {
            return;
        }

        this.lastValue = object;
        this.text.setText(lastValue == null ? "(null)" : lastValue.toString());

        fireAttributeChanged(new AttributeEvent(this));
    }

    /*
     *
     */
    @Override
    public void createEditor(Composite parent, int gridColumns)
    {
        createText(parent, gridColumns);
    }

    /**
     * Create the scale control.
     */
    private void createText(Composite parent, int gridColumns)
    {
        final GridDataFactory factory = GUIFactory.editorGridData();

        final GridData layoutData = factory.create();
        layoutData.horizontalSpan = gridColumns;
        layoutData.grabExcessHorizontalSpace = false;
        layoutData.verticalAlignment = SWT.CENTER;

        text = new Text(parent, SWT.RIGHT | SWT.SINGLE);
        text.setEnabled(false);
        text.setLayoutData(layoutData);
    }
}


text:
/* ================================================================ */
/*
File:   ConvertUTF.C
Author: Mark E. Davis
Copyright (C) 1994 Taligent, Inc. All rights reserved.

This code is copyrighted. Under the copyright laws, this code may not
be copied, in whole or part, without prior written consent of Taligent.

Taligent grants the right to use or reprint this code as long as this
ENTIRE copyright notice is reproduced in the code or reproduction.
The code is provided AS-IS, AND TALIGENT DISCLAIMS ALL WARRANTIES,
EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  IN
NO EVENT WILL TALIGENT BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING,
WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS
INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY
LOSS) ARISING OUT OF THE USE OR INABILITY TO USE THIS CODE, EVEN
IF TALIGENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF
LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE
LIMITATION MAY NOT APPLY TO YOU.

RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the
government is subject to restrictions as set forth in subparagraph
(c)(l)(ii) of the Rights in Technical Data and Computer Software
clause at DFARS 252.227-7013 and FAR 52.227-19.

This code may be protected by one or more U.S. and International
Patents.

TRADEMARKS: Taligent and the Taligent Design Mark are registered
trademarks of Taligent, Inc.
*/
/* ================================================================ */

#include "cvtutf.h"

/* ================================================================ */

static const int halfShift             = 10;
static const UCS4 halfBase             = 0x0010000UL;
static const UCS4 halfMask             = 0x3FFUL;
static const UCS4 kSurrogateHighStart  = 0xD800UL;
static const UCS4 kSurrogateHighEnd    = 0xDBFFUL;
static const UCS4 kSurrogateLowStart   = 0xDC00UL;
static const UCS4 kSurrogateLowEnd     = 0xDFFFUL;

/* ================================================================ */

ConversionResult
ConvertUCS4toUTF16(UCS4** sourceStart, const UCS4* sourceEnd,
                   UTF16** targetStart, const UTF16* targetEnd)
{
  ConversionResult result = ok;
  register UCS4* source = *sourceStart;
  register UTF16* target = *targetStart;
  while (source < sourceEnd) {
    register UCS4 ch;
    if (target >= targetEnd) {
      result = targetExhausted; break;
    };
    ch = *source++;
    if (ch <= kMaximumUCS2) {
      *target++ = ch;
    } else if (ch > kMaximumUTF16) {
      *target++ = kReplacementCharacter;
    } else {
      if (target + 1 >= targetEnd) {
        result = targetExhausted; break;
      };
      ch -= halfBase;
      *target++ = (ch >> halfShift) + kSurrogateHighStart;
      *target++ = (ch & halfMask) + kSurrogateLowStart;
    };
  };
  *sourceStart = source;
  *targetStart = target;
  return result;
};

/* ================================================================ */

ConversionResult ConvertUTF16toUCS4(UTF16** sourceStart, UTF16* sourceEnd,
                                    UCS4** targetStart, const UCS4* targetEnd)
{
  ConversionResult result = ok;
  register UTF16* source = *sourceStart;
  register UCS4* target = *targetStart;
  while (source < sourceEnd) {
    register UCS4 ch;
    ch = *source++;
    if (ch >= kSurrogateHighStart &&
        ch <= kSurrogateHighEnd &&
        source < sourceEnd) {
      register UCS4 ch2 = *source;
      if (ch2 >= kSurrogateLowStart && ch2 <= kSurrogateLowEnd) {
        ch = ((ch - kSurrogateHighStart) << halfShift)
          + (ch2 - kSurrogateLowStart) + halfBase;
        ++source;
      };
    };
    if (target >= targetEnd) {
      result = targetExhausted; break;
    };
    *target++ = ch;
  };
  *sourceStart = source;
  *targetStart = target;
  return result;
};

/* ================================================================ */

static UCS4 offsetsFromUTF8[6] = {
  0x00000000UL, 0x00003080UL, 0x000E2080UL,
  0x03C82080UL, 0xFA082080UL, 0x82082080UL
};
static char bytesFromUTF8[256] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

static UTF8 firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC};

/* ================================================================ */
/*      This code is similar in effect to making successive calls on the
mbtowc and wctomb routines in FSS-UTF. However, it is considerably
different in code:
* it is adapted to be consistent with UTF16,
* the interface converts a whole buffer to avoid function-call overhead
* constants have been gathered.
* loops & conditionals have been removed as much as possible for
efficiency, in favor of drop-through switch statements.
*/

/* ================================================================ */
int NSConvertUTF16toUTF8(unichar             **sourceStart,
                         const unichar       *sourceEnd,
                         unsigned char       **targetStart,
                         const unsigned char *targetEnd)
{
  ConversionResult result = ok;
  register UTF16* source = *sourceStart;
  register UTF8* target = *targetStart;
  while (source < sourceEnd) {
    register UCS4 ch;
    register unsigned short bytesToWrite = 0;
    register const UCS4 byteMask = 0xBF;
    register const UCS4 byteMark = 0x80;
    ch = *source++;
    if (ch >= kSurrogateHighStart && ch <= kSurrogateHighEnd
        && source < sourceEnd) {
      register UCS4 ch2 = *source;
      if (ch2 >= kSurrogateLowStart && ch2 <= kSurrogateLowEnd) {
        ch = ((ch - kSurrogateHighStart) << halfShift)
          + (ch2 - kSurrogateLowStart) + halfBase;
        ++source;
      };
    };
    if (ch < 0x80) {                    bytesToWrite = 1;
    } else if (ch < 0x800) {            bytesToWrite = 2;
    } else if (ch < 0x10000) {          bytesToWrite = 3;
    } else if (ch < 0x200000) {         bytesToWrite = 4;
    } else if (ch < 0x4000000) {        bytesToWrite = 5;
    } else if (ch <= kMaximumUCS4){     bytesToWrite = 6;
    } else {                                            bytesToWrite = 2;
    ch = kReplacementCharacter;
    }; /* I wish there were a smart way to avoid this conditional */

    target += bytesToWrite;
    if (target > targetEnd) {
      target -= bytesToWrite; result = targetExhausted; break;
    };
    switch (bytesToWrite) {     /* note: code falls through cases! */
      case 6:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 5:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 4:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 3:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 2:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 1:   *--target =  ch | firstByteMark[bytesToWrite];
    };
    target += bytesToWrite;
  };
  *sourceStart = source;
  *targetStart = target;

  return result;
};

/* ================================================================ */

int NSConvertUTF8toUTF16(unsigned char **sourceStart,const unsigned char *sourceEnd,
                         unichar **targetStart, const unichar *targetEnd)
{
  ConversionResult result = ok;
  register UTF8  *source = *sourceStart;
  register UTF16 *target = *targetStart;

  while (source < sourceEnd) {
    register UCS4 ch = 0;
    register unsigned short extraBytesToWrite = bytesFromUTF8[*source];

    if (source + extraBytesToWrite > sourceEnd) {
      result = sourceExhausted; break;
    };
    switch(extraBytesToWrite) { /* note: code falls through cases! */
      case 5:   ch += *source++; ch <<= 6;
      case 4:   ch += *source++; ch <<= 6;
      case 3:   ch += *source++; ch <<= 6;
      case 2:   ch += *source++; ch <<= 6;
      case 1:   ch += *source++; ch <<= 6;
      case 0:   ch += *source++;
    };
    ch -= offsetsFromUTF8[extraBytesToWrite];

    if (target >= targetEnd) {
      result = targetExhausted; break;
    };
    if (ch <= kMaximumUCS2) {
      *target++ = ch;
    } else if (ch > kMaximumUTF16) {
      *target++ = kReplacementCharacter;
    } else {
      if (target + 1 >= targetEnd) {
        result = targetExhausted; break;
      };
      ch -= halfBase;
      *target++ = (ch >> halfShift) + kSurrogateHighStart;
      *target++ = (ch & halfMask) + kSurrogateLowStart;
    };
  };
  *sourceStart = source;
  *targetStart = target;

  return result;
};

/* ================================================================ */
ConversionResult ConvertUCS4toUTF8 ( UCS4** sourceStart, const UCS4* sourceEnd,
                                     UTF8** targetStart, const UTF8* targetEnd)
{
  ConversionResult result = ok;
  register UCS4* source = *sourceStart;
  register UTF8* target = *targetStart;
  while (source < sourceEnd) {
    register UCS4 ch;
    register unsigned short bytesToWrite = 0;
    register const UCS4 byteMask = 0xBF;
    register const UCS4 byteMark = 0x80;
    ch = *source++;
    if (ch >= kSurrogateHighStart && ch <= kSurrogateHighEnd
        && source < sourceEnd) {
      register UCS4 ch2 = *source;
      if (ch2 >= kSurrogateLowStart && ch2 <= kSurrogateLowEnd) {
        ch = ((ch - kSurrogateHighStart) << halfShift)
          + (ch2 - kSurrogateLowStart) + halfBase;
        ++source;
      };
    };
    if (ch < 0x80) {                            bytesToWrite = 1;
    } else if (ch < 0x800) {            bytesToWrite = 2;
    } else if (ch < 0x10000) {          bytesToWrite = 3;
    } else if (ch < 0x200000) {         bytesToWrite = 4;
    } else if (ch < 0x4000000) {        bytesToWrite = 5;
    } else if (ch <= kMaximumUCS4){     bytesToWrite = 6;
    } else {                                            bytesToWrite = 2;
    ch = kReplacementCharacter;
    }; /* I wish there were a smart way to avoid this conditional */

    target += bytesToWrite;
    if (target > targetEnd) {
      target -= bytesToWrite; result = targetExhausted; break;
    };
    switch (bytesToWrite) {     /* note: code falls through cases! */
      case 6:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 5:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 4:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 3:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 2:   *--target = (ch | byteMark) & byteMask; ch >>= 6;
      case 1:   *--target =  ch | firstByteMark[bytesToWrite];
    };
    target += bytesToWrite;
  };
  *sourceStart = source;
  *targetStart = target;
  return result;
};

/* ================================================================ */

ConversionResult ConvertUTF8toUCS4 (UTF8** sourceStart, UTF8* sourceEnd,
                                    UCS4** targetStart, const UCS4* targetEnd)
{
  ConversionResult result = ok;
  register UTF8* source = *sourceStart;
  register UCS4* target = *targetStart;
  while (source < sourceEnd) {
    register UCS4 ch = 0;
    register unsigned short extraBytesToWrite = bytesFromUTF8[*source];
    if (source + extraBytesToWrite > sourceEnd) {
      result = sourceExhausted; break;
    };
    switch(extraBytesToWrite) { /* note: code falls through cases! */
      case 5:   ch += *source++; ch <<= 6;
      case 4:   ch += *source++; ch <<= 6;
      case 3:   ch += *source++; ch <<= 6;
      case 2:   ch += *source++; ch <<= 6;
      case 1:   ch += *source++; ch <<= 6;
      case 0:   ch += *source++;
    };
    ch -= offsetsFromUTF8[extraBytesToWrite];

    if (target >= targetEnd) {
      result = targetExhausted; break;
    };
    if (ch <= kMaximumUCS2) {
      *target++ = ch;
    } else if (ch > kMaximumUCS4) {
      *target++ = kReplacementCharacter;
    } else {
      if (target + 1 >= targetEnd) {
        result = targetExhausted; break;
      };
      ch -= halfBase;
      *target++ = (ch >> halfShift) + kSurrogateHighStart;
      *target++ = (ch & halfMask) + kSurrogateLowStart;
    };
  };
  *sourceStart = source;
  *targetStart = target;
  return result;
};


text:
package org.apache.harmony.sql.tests.internal.rowset;

import java.sql.SQLException;

import javax.sql.rowset.spi.SyncProviderException;

public class JoinRowSetCachedRowSetTest extends JoinRowSetTestCase {

    public void testGetCommandAndUrl() throws Exception {
        assertNull(jrs.getCommand());
        assertNull(jrs.getUrl());
        assertNull(jrs.getUsername());
        assertNull(jrs.getPassword());

        String sqlCommand = "select * from USER_INFO";
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.setCommand(sqlCommand);
        noInitialCrset.setUrl(DERBY_URL);
        noInitialCrset.execute();
        assertEquals(sqlCommand, noInitialCrset.getCommand());
        assertEquals(DERBY_URL, noInitialCrset.getUrl());
        assertTrue(noInitialCrset.first());
        assertEquals(1, noInitialCrset.getInt(1));

        // add CachedRowSet to JoinRowSet
        jrs.addRowSet(noInitialCrset, 1);
        assertTrue(jrs.first());
        assertEquals(1, jrs.getInt(1));

        // check command and url
        assertNull(jrs.getCommand());
        assertNull(jrs.getUrl());
        assertNull(jrs.getUsername());
        assertNull(jrs.getPassword());
    }

    public void testSetCommandAndUrl() throws Exception {
        // Test empty JoinRowSet
        String sqlCommand = "select * from CUSTOMER_INFO";
        jrs.setCommand(sqlCommand);
        jrs.setUrl(DERBY_URL);
        try {
            jrs.execute();
            fail("should throw SQLException");
        } catch (SQLException e) {
            // expected
        }
        assertEquals(sqlCommand, jrs.getCommand());
        assertEquals(DERBY_URL, jrs.getUrl());

        // Test JoinRowSet filled with CachedRowSet
        jrs = newJoinRowSet();
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.setCommand(sqlCommand);
        noInitialCrset.setUrl(DERBY_URL);
        noInitialCrset.execute();
        jrs.addRowSet(noInitialCrset, 1);
        assertTrue(jrs.first());
        assertEquals(1111, jrs.getInt(1));
        assertNull(jrs.getCommand());
        assertNull(jrs.getUrl());
        // call JoinRowSet.execute()
        jrs.beforeFirst();
        jrs.execute();
        // check data
        int index = 0;
        noInitialCrset.beforeFirst();
        while (jrs.next() && noInitialCrset.next()) {
            index++;
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(jrs.getObject(i), noInitialCrset.getObject(i));
            }
        }

        // set command and url
        sqlCommand = "select * from USER_INFO";
        jrs.setCommand(sqlCommand);
        jrs.setUrl(DERBY_URL);
        assertEquals(sqlCommand, jrs.getCommand());
        assertEquals(DERBY_URL, jrs.getUrl());
        // call JoinRowSet.execute() after set cmd and url
        jrs.execute();
        /*
         * Check data. Though the sql command is changed, the data of JoinRowSet
         * remains the same.
         */
        jrs.beforeFirst();
        noInitialCrset.beforeFirst();
        while (jrs.next() && noInitialCrset.next()) {
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(jrs.getObject(i), noInitialCrset.getObject(i));
            }
        }
        assertEquals(sqlCommand, jrs.getCommand());
        assertEquals(DERBY_URL, jrs.getUrl());
    }

    public void testPopulate() throws Exception {
        /*
         * JoinRowSet.populate(ResultSet) won't throw exception. However,
         * JoinRowSet is still empty.
         */
        rs = st.executeQuery("select * from USER_INFO");
        jrs.populate(rs);
        assertNull(jrs.getMetaData());
        jrs.beforeFirst();
        assertFalse(jrs.next());
        assertFalse(jrs.first());

        /*
         * Test JoinRowSet which has added a CachedRowSet
         */
        jrs = newJoinRowSet();
        jrs.addRowSet(crset, 1);
        assertTrue(jrs.first());
        assertEquals(1, jrs.getInt(1));

        rs = st.executeQuery("select * from BOOKS");
        // populate() still has no effect here
        jrs.populate(rs);
        jrs.beforeFirst();
        rs = st.executeQuery("select * from USER_INFO");
        while (jrs.next() && rs.next()) {
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(rs.getObject(i), jrs.getObject(i));
            }
        }
    }

    public void testExecuteWithoutConn_Normal() throws Exception {
        /*
         * Add a CachedRowSet which has set command and url but not call execute
         * to JoinRowSet
         */
        rs = st.executeQuery("select * from USER_INFO");
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.setCommand("select * from BOOKS");
        noInitialCrset.setUrl(DERBY_URL);
        noInitialCrset.populate(rs);
        assertTrue(noInitialCrset.first());
        assertEquals("hermit", noInitialCrset.getString(2));
        assertEquals("select * from BOOKS", noInitialCrset.getCommand());
        assertEquals(DERBY_URL, noInitialCrset.getUrl());
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(noInitialCrset, 1);
        assertNull(jrs.getStatement());
        // check data
        assertSame(noInitialCrset.getMetaData(), jrs.getMetaData());
        rs = st.executeQuery("select * from USER_INFO");
        jrs.beforeFirst();
        int index = 0;
        while (jrs.next() && rs.next()) {
            index++;
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(jrs.getObject(i), rs.getObject(i));
            }
        }
        assertEquals(4, index);
        // call JoinRowSet.execute()
        assertNull(jrs.getCommand());
        jrs.execute();
        assertNull(jrs.getStatement());
        assertNull(jrs.getCommand());
        // check JoinRowSet's data
        assertNotSame(noInitialCrset.getMetaData(), jrs.getMetaData());
        rs = st.executeQuery("select * from BOOKS");
        jrs.beforeFirst();
        index = 0;
        while (jrs.next() && rs.next()) {
            index++;
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(jrs.getObject(i), rs.getObject(i));
            }
        }
        assertEquals(7, index);
        // check noInitialCrset's data
        rs = st.executeQuery("select * from USER_INFO");
        noInitialCrset.beforeFirst();
        index = 0;
        while (noInitialCrset.next() && rs.next()) {
            index++;
            for (int i = 1; i <= noInitialCrset.getMetaData().getColumnCount(); i++) {
                assertEquals(noInitialCrset.getObject(i), rs.getObject(i));
            }
        }
        assertEquals(4, index);
        // call noInitialCrset's execute()
        assertEquals("select * from BOOKS", noInitialCrset.getCommand());
        noInitialCrset.execute();
        // check noInitialCrset's data
        jrs.beforeFirst();
        noInitialCrset.beforeFirst();
        index = 0;
        while (noInitialCrset.next() && jrs.next()) {
            index++;
            for (int i = 1; i <= noInitialCrset.getMetaData().getColumnCount(); i++) {
                assertEquals(noInitialCrset.getObject(i), jrs.getObject(i));
            }
        }
        assertEquals(7, index);

        // change noInitialCrset's command
        noInitialCrset.setCommand("select * from CUSTOMER_INFO");
        // call JoinRowSet.execute()
        jrs.execute();
        // check data
        jrs.beforeFirst();
        noInitialCrset.beforeFirst();
        index = 0;
        while (noInitialCrset.next() && jrs.next()) {
            index++;
            for (int i = 1; i <= noInitialCrset.getMetaData().getColumnCount(); i++) {
                assertEquals(noInitialCrset.getObject(i), jrs.getObject(i));
            }
        }
        assertEquals(7, index);

        /*
         * Add a CachedRowSet which has set command and url to JoinRowSet
         */
        crset = newNoInitialInstance();
        crset.setCommand("select * from USER_INFO");
        crset.setUrl(DERBY_URL);
        crset.execute();
        assertTrue(crset.absolute(1));
        assertEquals("hermit", crset.getString(2));
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(crset, 1);
        // check data
        assertSame(crset.getMetaData(), jrs.getMetaData());
        assertTrue(jrs.first());
        assertEquals("hermit", jrs.getString(2));
        // call JoinRowSet.execute()
        jrs.execute();
        // check data
        assertNotSame(crset.getMetaData(), jrs.getMetaData());
        isMetaDataEquals(crset.getMetaData(), jrs.getMetaData());
        assertTrue(jrs.absolute(1));
        assertEquals("hermit", jrs.getString(2));

        // set command and url for JoinRowSet, then call execute() again
        jrs.setCommand("select * from BOOKS");
        jrs.setUrl(DERBY_URL);
        jrs.execute();
        // the data remains the same as crset's
        assertNotSame(crset.getMetaData(), jrs.getMetaData());
        isMetaDataEquals(crset.getMetaData(), jrs.getMetaData());
        assertTrue(jrs.absolute(1));
        assertEquals("hermit", jrs.getString(2));

        // change command for CachedRowSet, then call JoinRowSet.execute()
        crset.setCommand("select * from BOOKS");
        jrs.execute();
        assertNotSame(crset.getMetaData(), jrs.getMetaData());
        isMetaDataEquals(crset.getMetaData(), jrs.getMetaData());
        assertTrue(jrs.absolute(1));
        assertEquals("hermit", jrs.getString(2));
        // call CachedRowSet.execute()
        crset.execute();
        assertTrue(crset.first());
        assertEquals("sn1-1", crset.getString(2));
        assertTrue(jrs.absolute(1));
        assertEquals("hermit", jrs.getString(2));

        /*
         * Add another CachedRowSet which also can call execute()
         * successfully to JoinRowSet
         */
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.setCommand("select * from BOOKS");
        noInitialCrset.setUrl(DERBY_URL);
        noInitialCrset.execute();
        /*
         * TODO The match column will lost after call execute(). Therefore, it
         * would throw exception and prompts that no match column. It's need to
         * test Joinable.
         */
        if ("true".equals(System.getProperty("Testing Harmony"))) {
            // TODO
        } else {
            try {
                jrs.addRowSet(noInitialCrset, 1);
                fail("should throw SQLException");
            } catch (SQLException e) {
                // expected
            }
        }
    }

    public void testExecuteWithoutConn_Exception() throws Exception {
        /*
         * An empty JoinRowSet call execute() would throw SQLException even when
         * command and url are set.
         */
        try {
            jrs.execute();
            fail("should throw SQLException.");
        } catch (SQLException e) {
            // expected
        }

        String sqlCommand = "select * from USER_INFO";
        jrs.setCommand(sqlCommand);
        jrs.setUrl(DERBY_URL);
        try {
            jrs.execute();
            fail("should throw SQLException.");
        } catch (SQLException e) {
            // expected
        }

        /*
         * Add a CachedRowSet without set command and url to JoinRowSet
         */
        rs = st.executeQuery("select * from USER_INFO");
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.populate(rs);
        assertTrue(noInitialCrset.first());
        assertEquals(1, noInitialCrset.getInt(1));
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(noInitialCrset, 1);
        assertTrue(jrs.last());
        assertEquals(4, jrs.getInt(1));
        // call execute()
        try {
            jrs.execute();
            fail("should throw SQLException.");
        } catch (SQLException e) {
            // expected
        }
        // if execute() fail, then the JoinRowSet's data would lose
        assertNotNull(jrs.getMetaData());
        assertSame(noInitialCrset.getMetaData(), jrs.getMetaData());
        assertFalse(jrs.first());
        assertFalse(jrs.absolute(3));
        assertTrue(noInitialCrset.first());
        assertEquals("hermit", noInitialCrset.getString(2));

        /*
         * Add two CachedRowSets which both can call execute()
         */
        crset = newNoInitialInstance();
        crset.setCommand("select * from USER_INFO");
        crset.setUrl(DERBY_URL);
        crset.execute();
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.setCommand("select * from BOOKS");
        noInitialCrset.setUrl(DERBY_URL);
        noInitialCrset.execute();
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(crset, 1);
        jrs.addRowSet(noInitialCrset, 1);
        // it would throw SQLException when more than one RowSet is added
        try {
            jrs.execute();
            fail("should throw SQLException");
        } catch (SQLException e) {
            // expected
        }
        assertNotNull(jrs.getMetaData());
        assertFalse(jrs.first());
    }

    public void testExecuteWithConn_Normal() throws Exception {
        assertNull(jrs.getStatement());
        /*
         * Add a CachedRowSet which has set command and call execute() to
         * JoinRowSet
         */
        crset = newNoInitialInstance();
        crset.setCommand("select * from USER_INFO");
        crset.execute(conn);
        assertTrue(crset.absolute(1));
        assertEquals("hermit", crset.getString(2));
        assertEquals(1, crset.getRow());
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(crset, 1);
        assertNull(jrs.getStatement());
        // check data
        assertSame(crset.getMetaData(), jrs.getMetaData());
        assertTrue(jrs.absolute(1));
        assertEquals("hermit", jrs.getString(2));
        assertEquals(1, jrs.getRow());
        assertTrue(jrs.last());
        assertEquals(4, jrs.getRow());
        // call JoinRowSet.execute()
        jrs.execute(conn);
        assertNull(jrs.getStatement());
        // check data
        assertNotSame(crset.getMetaData(), jrs.getMetaData());
        isMetaDataEquals(crset.getMetaData(), jrs.getMetaData());
        rs = st.executeQuery("select * from USER_INFO");
        jrs.beforeFirst();
        int index = 0;
        while (jrs.next() && rs.next()) {
            index++;
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(jrs.getObject(i), rs.getObject(i));
            }
            assertEquals(index, jrs.getRow());
        }
        assertEquals(4, index);

        // set command and url for JoinRowSet, then call execute() again
        jrs.setCommand("select * from BOOKS");
        jrs.execute(conn);
        assertNull(jrs.getStatement());
        // the data remains the same as crset's
        assertNotSame(crset.getMetaData(), jrs.getMetaData());
        isMetaDataEquals(crset.getMetaData(), jrs.getMetaData());
        rs = st.executeQuery("select * from USER_INFO");
        jrs.beforeFirst();
        index = 0;
        while (jrs.next() && rs.next()) {
            index++;
            for (int i = 1; i <= jrs.getMetaData().getColumnCount(); i++) {
                assertEquals(jrs.getObject(i), rs.getObject(i));
            }
        }
        assertEquals(4, index);
    }

    public void testExecuteWithConn_Exception() throws Exception {
        /*
         * Test empty JoinRowSet
         */
        try {
            jrs.execute(conn);
            fail("should throw SQLException");
        } catch (SQLException e) {
            // expected
        }

        jrs.setCommand("select * from USER_INFO");
        try {
            jrs.execute(conn);
            fail("should throw SQLException");
        } catch (SQLException e) {
            // expected
        }

        /*
         * Add a CachedRowSet without set command and url to JoinRowSet
         */
        rs = st.executeQuery("select * from USER_INFO");
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.populate(rs);
        assertTrue(noInitialCrset.first());
        assertEquals("hermit", noInitialCrset.getString(2));
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(noInitialCrset, 1);
        // check data
        assertSame(noInitialCrset.getMetaData(), jrs.getMetaData());
        assertTrue(jrs.last());
        assertEquals("test4", jrs.getString(2));
        // call execute(conn)
        jrs.setCommand("select * from USER_INFO");
        try {
            jrs.execute(conn);
            fail("should throw SQLException");
        } catch (SQLException e) {
            // expected
        }
        // check data
        assertSame(noInitialCrset.getMetaData(), jrs.getMetaData());
        assertFalse(jrs.first());
        assertTrue(noInitialCrset.first());
        assertEquals("hermit", noInitialCrset.getString(2));

        /*
         * Add two CachedRowSets which both can call execute(conn)
         */
        crset = newNoInitialInstance();
        crset.setCommand("select * from USER_INFO");
        crset.execute(conn);
        noInitialCrset = newNoInitialInstance();
        noInitialCrset.setCommand("select * from BOOKS");
        noInitialCrset.execute(conn);
        // add to JoinRowSet
        jrs = newJoinRowSet();
        jrs.addRowSet(crset, 1);
        jrs.addRowSet(noInitialCrset, 1);
        // it would throw SQLException when more than one RowSet is added
        try {
            jrs.execute(conn);
            fail("should throw SQLException");
        } catch (SQLException e) {
            // expected
        }
        // check data
        assertNotNull(jrs.getMetaData());
        assertFalse(jrs.first());
    }

    public void testCursorMoved() throws Exception {
        Listener listener = new Listener();
        jrs.addRowSetListener(listener);
        assertNull(listener.getTag());

        jrs.addRowSet(crset, 1);

        assertTrue(jrs.absolute(1));
        assertNull(listener.getTag());

        assertTrue(jrs.next());
        assertNull(listener.getTag());
    }

    public void testRowChanged() throws Exception {
        Listener listener = new Listener();
        jrs.addRowSetListener(listener);
        assertNull(listener.getTag());
        jrs.addRowSet(crset, 1);

        assertTrue(jrs.absolute(1));
        assertNull(listener.getTag());
        jrs.setOriginalRow();
        assertNull(listener.getTag());

        /*
         * updateRow() - rowChanged
         */
        assertTrue(jrs.absolute(3));
        jrs.updateString(2, "abc");
        assertNull(listener.getTag());
        jrs.updateRow();
        assertNull(listener.getTag());

        /*
         * deleteRow() - rowChanged
         */
        assertTrue(jrs.last());
        jrs.deleteRow();
        assertNull(listener.getTag());
    }

    public void testAcceptChanges_Exception() throws Exception {
        try {
            jrs.acceptChanges();
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }

        try {
            jrs.acceptChanges(conn);
            fail("Should throw NullPointerException.");
        } catch (NullPointerException e) {
            // Expected.
        }

        jrs.addRowSet(crset, 1);

        jrs.acceptChanges();
        jrs.acceptChanges(conn);

        jrs.absolute(4);
        jrs.updateString(2, "Updated");
        jrs.updateRow();

        jrs.acceptChanges();

        jrs = newJoinRowSet();
        jrs.addRowSet(crset, 1);
        try {
            jrs.acceptChanges();
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }

        jrs.acceptChanges(conn);
        jrs.acceptChanges();
    }

    public void testAcceptChanges_Insert() throws Exception {
        jrs.addRowSet(crset, 1);
        jrs.absolute(4);
        jrs.moveToInsertRow();
        jrs.updateString(2, "Inserted");
        jrs.updateInt(1, 5);
        jrs.insertRow();
        jrs.moveToCurrentRow();

        try {
            jrs.acceptChanges();
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }
        jrs.acceptChanges(conn);
        rs = st.executeQuery("select * from USER_INFO");
        crset = newNoInitialInstance();
        crset.populate(rs);
        int rowNum = 0;
        crset.beforeFirst();
        while (crset.next()) {
            rowNum++;
        }
        assertEquals(5, rowNum);

        assertTrue(jrs.absolute(5));
        assertEquals("Inserted", jrs.getString(2));
    }

    public void testAcceptChanges_Update() throws Exception {
        jrs.addRowSet(crset, 1);

        jrs.absolute(4);
        jrs.updateString(2, "Updated");
        jrs.updateRow();
        jrs.moveToCurrentRow();

        try {
            jrs.acceptChanges();
            fail("Should throw SyncProviderException.");

        } catch (SyncProviderException e) {
            // Expected.
        }
        jrs.acceptChanges(conn);

        rs = st.executeQuery("select * from USER_INFO");
        crset = newNoInitialInstance();
        crset.populate(rs);

        crset.absolute(4);
        assertEquals("Updated", crset.getString(2));

        jrs.absolute(4);
        assertEquals("Updated", jrs.getString(2));
    }

    public void testAcceptChanges_Delete() throws Exception {
        jrs.addRowSet(crset, 1);

        jrs.absolute(4);

        jrs.deleteRow();
        jrs.setShowDeleted(true);

        int rowNum = 0;
        jrs.beforeFirst();
        while (jrs.next()) {
            rowNum++;
        }

        jrs.acceptChanges(conn);

        rs = st.executeQuery("select * from USER_INFO");
        crset = newNoInitialInstance();
        crset.populate(rs);

        rowNum = 0;
        jrs.beforeFirst();
        while (jrs.next()) {
            rowNum++;
        }
        assertEquals(3, rowNum);

        rowNum = 0;
        crset.beforeFirst();
        while (crset.next()) {
            rowNum++;
        }
        // In RI, the deletion will not affect database.
        // In harmony, The deletion will happen in database according to spec.
        if ("true".equals(System.getProperty("Testing Harmony"))) {
            assertEquals(3, rowNum);
        } else {
            assertEquals(4, rowNum);
        }
    }

    public void testAcceptChanges_TwoSameRowSets() throws Exception {
        jrs.addRowSet(crset, 1);
        crset.beforeFirst();
        jrs.addRowSet(crset, 1);

        jrs.absolute(4);
        jrs.updateString(2, "Updated");
        jrs.updateRow();

        try {
            jrs.acceptChanges(conn);
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }
    }

    public void testAcceptChange_UpdateOriginalRowSet() throws Exception {
        jrs.addRowSet(crset, 1);
        crset.absolute(4);
        crset.updateString(2, "Updated");
        crset.updateRow();

        jrs.acceptChanges(conn);

        rs = st.executeQuery("select * from USER_INFO");
        crset = newNoInitialInstance();
        crset.populate(rs);
        crset.absolute(4);
        assertEquals("test4", crset.getString(2));
    }

    public void testUndoDeleted_Empty() throws Exception {
        // No Exception.
        jrs.undoDelete();
    }

    public void testUndoDeleted() throws Exception {
        jrs.addRowSet(crset, 1);

        /*
         * Test exception. It would throw SQLException when calling undoDelete()
         * in such conditions.
         */
        if ("true".equals(System.getProperty("Testing Harmony"))) {
            // TODO RI doesn't follow the spec, we follow spec
            jrs.beforeFirst();
            assertTrue(jrs.isBeforeFirst());
            try {
                jrs.undoDelete();
                fail("Should throw SQLException");
            } catch (SQLException e) {
                // expected, invalid cursor
            }

            jrs.afterLast();
            assertTrue(jrs.isAfterLast());
            try {
                jrs.undoDelete();
                fail("Should throw SQLException");
            } catch (SQLException e) {
                // expected, invalid cursor
            }

            jrs.moveToInsertRow();
            try {
                jrs.undoDelete();
                fail("Should throw SQLException");
            } catch (SQLException e) {
                // expected, invalid cursor
            }

            jrs.moveToCurrentRow();
            assertTrue(jrs.absolute(1));
            assertFalse(jrs.rowDeleted());
            try {
                jrs.undoDelete();
                fail("Should throw SQLException");
            } catch (SQLException e) {
                // expected, invalid cursor
            }

        } else {
            // when run on RI, it won't throw SQLException
            jrs.beforeFirst();
            assertTrue(jrs.isBeforeFirst());
            jrs.undoDelete();

            jrs.afterLast();
            assertTrue(jrs.isAfterLast());
            jrs.undoDelete();

            jrs.moveToInsertRow();
            jrs.undoDelete();

            jrs.moveToCurrentRow();
            assertTrue(jrs.absolute(1));
            assertFalse(jrs.rowDeleted());
            jrs.undoDelete();
        }

        // delete the fourth row
        assertTrue(jrs.absolute(4));
        assertEquals(4, jrs.getInt(1));
        assertFalse(jrs.rowDeleted());
        jrs.deleteRow();
        assertTrue(jrs.rowDeleted());

        if ("true".equals(System.getProperty("Testing Harmony"))) {
            jrs.undoDelete();
            assertFalse(jrs.rowDeleted());
            jrs.acceptChanges(conn);

            // check DB
            rs = st.executeQuery("SELECT COUNT(*) FROM USER_INFO WHERE ID = 4");
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));

            // check CachedRowSet
            jrs.beforeFirst();
            int index = 0;
            while (jrs.next()) {
                index++;
                assertEquals(index, jrs.getInt(1));
            }
            assertEquals(4, index);

        } else {
            // TODO undoDelete() still makes no difference in RI
            jrs.undoDelete();
            assertTrue(jrs.rowDeleted());
            jrs.acceptChanges(conn);

            // check DB
            rs = st.executeQuery("SELECT COUNT(*) FROM USER_INFO WHERE ID = 4");
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));

            // check CachedRowSet
            jrs.beforeFirst();
            int index = 0;
            while (jrs.next()) {
                index++;
                assertEquals(index, jrs.getInt(1));
            }
            assertEquals(3, index);
        }

    }

    public void testUndoInsert_Empty() throws Exception {
        try {
            jrs.undoInsert();
            fail("Should throw SQLException");
        } catch (SQLException e) {
            // Expected.
        } catch (ArrayIndexOutOfBoundsException e) {
            // RI throws it.
        }
    }

    public void testAcceptChanges_Complex() throws Exception {
        crset.acceptChanges();

        jrs.addRowSet(crset, 1);
        try {
            jrs.acceptChanges();
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }
        crset.acceptChanges();

        jrs.acceptChanges(conn);
        jrs.acceptChanges();

        try {
            jrs.acceptChanges(null);
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }

        try {
            jrs.acceptChanges();
            fail("Should throw SyncProviderException.");
        } catch (SyncProviderException e) {
            // Expected.
        }
    }
}


text:
Rails.application.routes.draw do
  root 'man#index'
  get '/validate' => 'man#validate'
end


text:
package com.moandjiezana.toml;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.junit.Ignore;
import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class BurntSushiValidTest {

  @Test
  public void array_empty() throws Exception {
    run("array-empty");
  }

  @Test
  public void array_nospaces() throws Exception {
    run("array-nospaces");
  }

  @Test
  public void arrays_hetergeneous() throws Exception {
    run("arrays-hetergeneous");
  }

  @Test
  public void arrays_nested() throws Exception {
    run("arrays-nested");
  }

  @Test
  public void arrays() throws Exception {
    run("arrays");
  }

  @Test
  public void bool() throws Exception {
    run("bool");
  }

  @Test
  public void comments_everywhere() throws Exception {
    run("comments-everywhere");
  }

  @Test
  public void datetime() throws Exception {
    run("datetime");
  }

  @Test
  public void empty() throws Exception {
    run("empty");
  }

  @Test
  public void example() throws Exception {
    run("example");
  }

  @Test
  public void float_() throws Exception {
    run("float");
  }

  @Test
  public void implicit_and_explicit_after() throws Exception {
    run("implicit-and-explicit-after");
  }

  @Test
  public void implicit_and_explicit_before() throws Exception {
    run("implicit-and-explicit-before");
  }

  @Test
  public void implicit_groups() throws Exception {
    run("implicit-groups");
  }

  @Test
  public void integer() throws Exception {
    run("integer");
  }

  @Test
  public void key_equals_nospace() throws Exception {
    run("key-equals-nospace");
  }

  @Test @Ignore
  public void key_space() throws Exception {
    run("key-space");
  }

  @Test
  public void key_space_modified() throws Exception {
    run("key-space-modified");
  }

  @Test @Ignore
  public void key_special_chars() throws Exception {
    run("key-special-chars");
  }

  @Test
  public void key_special_chars_modified() throws Exception {
    run("key-special-chars-modified");
  }

  @Test @Ignore
  public void keys_with_dots() throws Exception {
    run("keys-with-dots");
  }

  @Test
  public void keys_with_dots_modified() throws Exception {
    run("keys-with-dots-modified");
  }

  @Test
  public void long_float() throws Exception {
    run("long-float");
  }

  @Test
  public void long_integer() throws Exception {
    run("long-integer");
  }

  @Test @Ignore
  public void multiline_string() throws Exception {
    run("multiline-string");
  }

  @Test
  public void multiline_string_modified() throws Exception {
    run("multiline-string-modified");
  }

  @Test
  public void raw_multiline_string() throws Exception {
    run("raw-multiline-string");
  }

  @Test
  public void raw_string() throws Exception {
    run("raw-string");
  }

  @Test
  public void string_empty() throws Exception {
    run("string-empty");
  }

  @Test @Ignore
  public void string_escapes() throws Exception {
    run("string-escapes-modified");
  }

  @Test
  public void string_escapes_modified() throws Exception {
    run("string-escapes-modified");
  }

  @Test
  public void string_simple() throws Exception {
    run("string-simple");
  }

  @Test
  public void string_with_pound() throws Exception {
    run("string-with-pound");
  }

  @Test
  public void table_array_implicit() throws Exception {
    run("table-array-implicit");
  }

  @Test
  public void table_array_many() throws Exception {
    run("table-array-many");
  }

  @Test
  public void table_array_nest() throws Exception {
    run("table-array-nest");
  }

  @Test
  public void table_array_one() throws Exception {
    run("table-array-one");
  }

  @Test
  public void table_empty() throws Exception {
    run("table-empty");
  }

  @Test
  public void table_sub_empty() throws Exception {
    run("table-sub-empty");
  }

  @Test @Ignore
  public void table_whitespace() throws Exception {
    run("table-whitespace");
  }

  @Test @Ignore
  public void table_with_pound() throws Exception {
    run("table-with-pound");
  }

  @Test
  public void unicode_escape() throws Exception {
    run("unicode-escape");
  }

  @Test
  public void unicode_literal() throws Exception {
    run("unicode-literal");
  }

  private void run(String testName) {
    InputStream inputTomlStream = getClass().getResourceAsStream("burntsushi/valid/" + testName + ".toml");
    // InputStream inputToml = getClass().getResourceAsStream("burntsushi/valid/" + testName + ".toml");
    String inputToml = convertStreamToString(inputTomlStream).replaceAll("\r\n", "\n");
    Reader expectedJsonReader = new InputStreamReader(getClass().getResourceAsStream("burntsushi/valid/" + testName + ".json"));
    JsonElement expectedJson = GSON.fromJson(expectedJsonReader, JsonElement.class);

    Toml toml = new Toml().read(inputToml);
    JsonElement actual = TEST_GSON.toJsonTree(toml).getAsJsonObject().get("values");

    assertEquals(expectedJson, actual);

    try {
      inputTomlStream.close();
    } catch (IOException e) {}

    try {
      expectedJsonReader.close();
    } catch (IOException e) {}
  }

  static String convertStreamToString(java.io.InputStream is) {
      java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
      return s.hasNext() ? s.next() : "";
  }

  private static final Gson GSON = new Gson();
  private static final Gson TEST_GSON = new GsonBuilder()
    .registerTypeAdapter(Boolean.class, serialize(Boolean.class))
    .registerTypeAdapter(String.class, serialize(String.class))
    .registerTypeAdapter(Long.class, serialize(Long.class))
    .registerTypeAdapter(Double.class, serialize(Double.class))
    .registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
      @Override
      public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
        return context.serialize(new Value("datetime", iso8601Format.format(src)));
      }
    })
    .registerTypeHierarchyAdapter(List.class, new JsonSerializer<List<?>>() {
      @Override
      public JsonElement serialize(List<?> src, Type typeOfSrc, JsonSerializationContext context) {
        JsonArray array = new JsonArray();
        for (Object o : src) {
          array.add(context.serialize(o));
        }

        if (!src.isEmpty() && src.get(0) instanceof Map) {
          return array;
        }

        JsonObject object = new JsonObject();
        object.add("type", new JsonPrimitive("array"));
        object.add("value", array);

        return object;
      }
    })
    .registerTypeAdapter(Value.class, new JsonSerializer<Value>() {
      @Override
      public JsonElement serialize(Value src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.add("type", new JsonPrimitive(src.type));
        object.add("value", new JsonPrimitive(src.value));

        return object;
      }
    })
    .create();

  private static class Value {
    public final String type;
    public final String value;

    public Value(String type, String value) {
      this.type = type;
      this.value = value;
    }
  }

  private static <T> JsonSerializer<T> serialize(final Class<T> aClass) {
    return new JsonSerializer<T>() {
      @Override
      public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(new Value(toTomlType(aClass), src.toString()));
      }
    };
  }

  private static String toTomlType(Class<?> aClass) {
    if (aClass == String.class) {
      return "string";
    }

    if (aClass == Double.class) {
      return "float";
    }

    if (aClass == Long.class) {
      return "integer";
    }

    if (aClass == Date.class) {
      return "datetime";
    }

    if (aClass == Boolean.class) {
      return "bool";
    }

    return "array";
  }
}


text:
@interface BSClassProvider ()
@property (nonatomic, weak) Class klass;

- (id)initWithClass:(Class)class;

@end

@implementation BSClassProvider
@synthesize klass = _klass;

+ (BSClassProvider *)providerWithClass:(Class)class {
    return [[BSClassProvider alloc] initWithClass:class];
}

- (id)initWithClass:(Class)klass {
    self = [super init];
    if (self) {
        self.klass = klass;
    }
    return self;
}

- (id)provide:(NSArray *)args injector:(id<BSInjector>)injector {
    return [injector getInstance:self.klass];
}

@end


text:
package com.fs.app.portal.repository.impl;

import java.security.spec.KeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.fs.app.portal.utils.encryptionAnddecryption;
import com.fs.commons.app.pojo.UserInfoPojo;
import com.fs.commons.portal.repository.IUserInfoRepository;

@Repository
@Transactional
public class UserInfoRepository implements IUserInfoRepository {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Boolean addUser(UserInfoPojo userinfo) {
		try {
			sessionFactory.getCurrentSession().save(userinfo);
			return true;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 以明文方式传递的用户名和密码
	 */
	public UserInfoPojo getUserInfo(String name, String pswd) {
		try {
			Query hquery = sessionFactory
					.getCurrentSession()
					.createQuery(
							"from UserInfoPojo uinfo where uinfo.userName=:uname");
			hquery.setString("uname", name);
			List<UserInfoPojo> list = hquery.list();
			if (list != null && list.size()>0){
				encryptionAnddecryption jiami = new encryptionAnddecryption();
				UserInfoPojo result=null;
				for (UserInfoPojo uInfo : list) {
					byte[] bts = uInfo.getRemark();
					KeySpec keySpec = new DESKeySpec(bts);
					SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
					SecretKey key = factory.generateSecret(keySpec);
					String pwd_temp = jiami.decryptByDES(key, uInfo.getUserPassword());
					if(pwd_temp.equals(pswd))
						result=uInfo;
				}
				return result;
			}
			else
				return null;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 以明文用户名称+密文密码
	 */
	public UserInfoPojo getUserInfoBymark(String name, String pswd) {
		try {
			Query hquery = sessionFactory
					.getCurrentSession()
					.createQuery(
							"from UserInfoPojo uinfo where uinfo.userName=:uname");
			hquery.setString("uname", name);
			List<UserInfoPojo> list = hquery.list();
			if (list != null && list.size()>0){
				encryptionAnddecryption jiami = new encryptionAnddecryption();
				UserInfoPojo result=null;
				for (UserInfoPojo uInfo : list) {
					if(uInfo.getUserPassword().equals(pswd))
						result=uInfo;
				}
				return result;
			}
			else
				return null;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public UserInfoPojo getUserEmail(String email) {
		try {
			Query hquery = sessionFactory.getCurrentSession().createQuery(
					"from UserInfoPojo uinfo where uinfo.userEmail=:email");
			hquery.setString("email", email);
			List<UserInfoPojo> list = hquery.list();
			if (list != null && list.size() == 1)
				return list.get(0);
			else
				return null;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public Boolean changePassword(int uid, String newpwd) {
		try {
			Query hquery = sessionFactory.getCurrentSession().createQuery(
					"from UserInfoPojo uinfo where uinfo.id=:uid");
			hquery.setInteger("uid", uid);
			List<UserInfoPojo> list_users = (List<UserInfoPojo>)hquery.list();
			if (list_users != null && list_users.size() > 0) {
               UserInfoPojo temp_user=list_users.get(0);
               encryptionAnddecryption jiami = new encryptionAnddecryption();
   			   SecretKey key = jiami.createSecretKey("DES");
   			   String str_password = jiami.encryptToDES(key, newpwd);
               temp_user.setUserPassword(str_password);
               temp_user.setRemark(key.getEncoded());
               sessionFactory.getCurrentSession().update(temp_user);
               return true;
			}else
				return false;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return false;
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<UserInfoPojo> getAllUsers() {
		List<UserInfoPojo> list_result=new ArrayList<UserInfoPojo>();
		try {
			Query hquery = sessionFactory.getCurrentSession().createQuery(
					"from userInfo");
			list_result = hquery.list();
			if (list_result != null)
				return list_result;
			else
				return null;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}

}


text:
/*
 * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen.
 */
package com.solidfire.element.api;

import com.solidfire.gson.Gson;
import com.solidfire.core.client.Attributes;
import com.solidfire.gson.annotations.SerializedName;
import com.solidfire.core.annotation.Since;
import com.solidfire.core.javautil.Optional;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

/**
 * GetEncryptionAtRestInfoResult
 **/

public class GetEncryptionAtRestInfoResult implements Serializable {

    public static final long serialVersionUID = 374466650199754284L;
    @SerializedName("authenticationKeyInfo") private Optional<EncryptionKeyInfo> authenticationKeyInfo;
    @SerializedName("state") private String state;

    // parameterized constructor
    @Since("7.0")
    public GetEncryptionAtRestInfoResult(
    )
    {
    }
    // parameterized constructor
    @Since("12.0")
    public GetEncryptionAtRestInfoResult(
        Optional<EncryptionKeyInfo> authenticationKeyInfo,
        String state
    )
    {
        this.authenticationKeyInfo = (authenticationKeyInfo == null) ? Optional.<EncryptionKeyInfo>empty() : authenticationKeyInfo;
        this.state = state;
    }

    /**
     * Information about the encryption key that's being used for the Encryption At Rest feature.
     **/
    public Optional<EncryptionKeyInfo> getAuthenticationKeyInfo() { return this.authenticationKeyInfo; }

    public void setAuthenticationKeyInfo(Optional<EncryptionKeyInfo> authenticationKeyInfo) {
        this.authenticationKeyInfo = (authenticationKeyInfo == null) ? Optional.<EncryptionKeyInfo>empty() : authenticationKeyInfo;
    }
    /**
     * The current Encryption At Rest state. Possible values are "disabled", "enabling", "enabled" or "disabling".
     **/
    public String getState() { return this.state; }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        GetEncryptionAtRestInfoResult that = (GetEncryptionAtRestInfoResult) o;

        return
            Objects.equals(authenticationKeyInfo, that.authenticationKeyInfo) &&
            Objects.equals(state, that.state);
    }

    @Override
    public int hashCode() {
        return Objects.hash( authenticationKeyInfo,state );
    }

    public java.util.Map<String, Object> toMap() {
        java.util.Map<String, Object> map = new HashMap<>();
        map.put("authenticationKeyInfo", authenticationKeyInfo);
        map.put("state", state);
        return map;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        Gson gson = new Gson();
        sb.append( "{ " );

        if(null != authenticationKeyInfo && authenticationKeyInfo.isPresent()){
            sb.append(" authenticationKeyInfo : ").append(gson.toJson(authenticationKeyInfo)).append(",");
        }
        else{
            sb.append(" authenticationKeyInfo : ").append("null").append(",");
        }
        sb.append(" state : ").append(gson.toJson(state)).append(",");
        sb.append( " }" );

        if(sb.lastIndexOf(", }") != -1)
            sb.deleteCharAt(sb.lastIndexOf(", }"));

        return sb.toString();
    }

    public static Builder builder() {
        return new Builder();
    }

    public final Builder asBuilder() {
        return new Builder().buildFrom(this);
    }

    public static class Builder {
        private Optional<EncryptionKeyInfo> authenticationKeyInfo;
        private String state;

        private Builder() { }

        public GetEncryptionAtRestInfoResult build() {
            return new GetEncryptionAtRestInfoResult (
                         this.authenticationKeyInfo,
                         this.state);
        }

        private GetEncryptionAtRestInfoResult.Builder buildFrom(final GetEncryptionAtRestInfoResult req) {
            this.authenticationKeyInfo = req.authenticationKeyInfo;
            this.state = req.state;

            return this;
        }

        public GetEncryptionAtRestInfoResult.Builder optionalAuthenticationKeyInfo(final EncryptionKeyInfo authenticationKeyInfo) {
            this.authenticationKeyInfo = (authenticationKeyInfo == null) ? Optional.<EncryptionKeyInfo>empty() : Optional.of(authenticationKeyInfo);
            return this;
        }

        public GetEncryptionAtRestInfoResult.Builder state(final String state) {
            this.state = state;
            return this;
        }

    }
}


text:
require 'spec_helper'

describe "properties/show" do
  before(:each) do
    @property = assign(:property, stub_model(Property,
      :address => "Address",
      :rent => 1,
      :description => ""
    ))
  end

  it "renders attributes in <p>" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    rendered.should match(/Address/)
    rendered.should match(/1/)
    rendered.should match(//)
  end
end