text:
/**
  * This template file was generated by dynaTrace client.
  * The dynaTrace community portal can be found here: http://community.compuwareapm.com/
  * For information how to publish a plugin please visit http://community.compuwareapm.com/plugins/contribute/
  **/

package com.dynatrace.plugin;

import com.dynatrace.diagnostics.pdk.*;
import com.tibco.tibjms.admin.ConsumerInfo;
import com.tibco.tibjms.admin.DestinationInfo;
import com.tibco.tibjms.admin.QueueInfo;
import com.tibco.tibjms.admin.ServerInfo;
import com.tibco.tibjms.admin.TibjmsAdmin;
import com.tibco.tibjms.admin.TibjmsAdminException;
import com.tibco.tibjms.admin.TopicInfo;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TibcoEmsPlugin implements Monitor {
	//
	private static final Logger log = Logger.getLogger(TibcoEmsPlugin.class.getName());

	private static final String METRIC_GROUP_BROKER_STAT = "Broker Stat";
	private static final String METRIC_GROUP_DEST_STAT = "Destination Stat";
	private static final String METRIC_GROUP_CONSUMER_STAT = "Consumers Stat";

	private static final String MSR_DISK_READ_RATE = "(Broker) - Disk Read Rate";
	private static final String MSR_DISK_WRITE_RATE="(Broker) - Disk Write Rate";
	private static final String MSR_SYNC_STORE_SIZE="(Broker) - Sync Msg Store Size";
	private static final String MSR_ASYNC_STORE_SIZE="(Broker) - Async Msg Store Size";

	private static final String MSR_MSG_MEM_USED="(Broker) - Msg Mem Used";
	private static final String MSR_MSG_MEM_POOL_USED="(Broker) - Msg Mem Pool Used";
	private static final String MSR_MSG_MAX_MEM="(Broker) - Max Msg Mem Allowed";
	private static final String MSR_MSG_FREE_MEM="(Broker) - Free Msg Mem";

	private static final String MSR_CONN_COUNT="(Broker) - Connection Count";
	private static final String MSR_CONN_PERCENTAGE="(Broker) - Connection Percentage to Max Connections";
	private static final String MSR_SESSION_COUNT="(Broker) - Session Count";
	private static final String MSR_MAX_CONNS="(Broker) - Maximum Connections";

	private static final String MSR_PRODUCER_COUNT="(Broker) - Producer Count";
	private static final String MSR_CONSUMER_COUNT="(Broker) - Consumer Count";
	private static final String MSR_DURABLE_COUNT="(Broker) - Durable Count";
	private static final String MSR_TOPIC_COUNT="(Broker) - Topic Count";
	private static final String MSR_QUEUE_COUNT="(Broker) - Queue Count";

	private static final String MSR_PENDING_MSG_COUNT="(Broker) - Pending Message Count";
	private static final String MSR_PENDING_MSG_SIZE="(Broker) - Pending Message Size";

	private static final String MSR_INBOUND_MSG_COUNT="(Broker) - Inbound Message Count";
	private static final String MSR_INBOUND_MSG_RATE="(Broker) - Inbound Message Rate";
	private static final String MSR_INBOUND_BYTES_RATE="(Broker) - Inbound Bytes Rate";

	private static final String MSR_OUTBOUND_MSG_COUNT="(Broker) - Outbound Message Count";
	private static final String MSR_OUTBOUND_MSG_RATE="(Broker) - Outbound Message Rate";
	private static final String MSR_OUTBOUND_BYTES_RATE="(Broker) - Outbound Bytes Rate";

	private static final String MSR_LOGFILE_MAX_SIZE="(Server) - Log File Size Max";
	private static final String MSR_LOGFILE_SIZE="(Server) - Log File Size";
	private static final String MSR_LOGFILE_PERCENT_USED="(Server) - Log File Percent Used";

	private static final String MSR_DEST_CONSUMER_COUNT="Consumer Count";
	private static final String MSR_DEST_FLOWCONTROL_MAXBYTES="FlowControl MaxBytes";
	private static final String MSR_DEST_PENDING_MSG_COUNT="Pending Message Count";
	private static final String MSR_DEST_PENDING_MSG_SIZE="Pending Message Size";

	private static final String MSR_DEST_INBOUND_MSG_COUNT="Inbound Message Count";
	private static final String MSR_DEST_INBOUND_MSG_RATE="Inbound Message Rate";
	private static final String MSR_DEST_INBOUND_BYTES_COUNT="Inbound Bytes Count";
	private static final String MSR_DEST_INBOUND_BYTES_RATE="Inbound Bytes Rate";

	private static final String MSR_DEST_OUTBOUND_MSG_COUNT="Outbound Message Count";
	private static final String MSR_DEST_OUTBOUND_MSG_RATE="Outbound Message Rate";
	private static final String MSR_DEST_OUTBOUND_BYTES_COUNT="Outbound Bytes Count";
	private static final String MSR_DEST_OUTBOUND_BYTES_RATE="Outbound Bytes Rate";

	private static final String MSR_DEST_Q_RECEIVER_COUNT="Queue Receiver Count";
	private static final String MSR_DEST_Q_DELIVERED_MSG_COUNT="Queue Delivered Message Count";
	private static final String MSR_DEST_Q_INTRANSIT_MSG_COUNT="Queue InTransit Message Count";

	private static final String MSR_DEST_T_SUBSCRIBER_COUNT="Topic Subscriber Count";
	private static final String MSR_DEST_T_DURABLE_COUNT="Topic Durable Count";

	/**
	 * Initializes the Plugin. This method is called in the following cases:
	 *

	 *
before <tt>execute</tt> is called the first time for this
	 * scheduled Plugin

	 *
before the next <tt>execute</tt> if <tt>teardown</tt> was called
	 * after the last execution

	 *

	 *

	 * If the returned status is <tt>null</tt> or the status code is a
	 * non-success code then {@link Plugin#teardown() teardown()} will be called
	 * next.
	 *

	 * Resources like sockets or files can be opened in this method.
	 * @param env
	 *            the configured <tt>MonitorEnvironment</tt> for this Plugin;
	 *            contains subscribed measures, but measurements will be
	 *            discarded
	 * @see Plugin#teardown()
	 * @return a <tt>Status</tt> object that describes the result of the
	 *         method call
	 */
	@Override
	public Status setup(MonitorEnvironment env) throws Exception {
		// TODO
		return new Status(Status.StatusCode.Success);
	}

	/**
	 * Executes the Monitor Plugin to retrieve subscribed measures and store
	 * measurements.
	 *
	 *

	 * This method is called at the scheduled intervals. If the Plugin execution
	 * takes longer than the schedule interval, subsequent calls to
	 * {@link #execute(MonitorEnvironment)} will be skipped until this method
	 * returns. After the execution duration exceeds the schedule timeout,
	 * {@link TaskEnvironment#isStopped()} will return <tt>true</tt>. In this
	 * case execution should be stopped as soon as possible. If the Plugin
	 * ignores {@link TaskEnvironment#isStopped()} or fails to stop execution in
	 * a reasonable timeframe, the execution thread will be stopped ungracefully
	 * which might lead to resource leaks!
	 *
	 * @param env
	 *            a <tt>MonitorEnvironment</tt> object that contains the
	 *            Plugin configuration and subscribed measures. These
	*            <tt>MonitorMeasure</tt>s can be used to store measurements.
	 * @return a <tt>Status</tt> object that describes the result of the
	 *         method call
	 * @throws Exception
	 */
	//@SuppressWarnings("deprecation")
	@Override
	public Status execute(MonitorEnvironment env) {
		/*
		// this sample which shows how to book to (dynamic) monitor measures

		Collection<MonitorMeasure> monitorMeasures = env.getMonitorMeasures("mymetricgroup", "mymetric");
		for (MonitorMeasure subscribedMonitorMeasure : monitorMeasures) {

			//this will book to the monitor measure
			subscribedMonitorMeasure.setValue(42);

			//for this subscribed measure we want to create a dynamic measure
			MonitorMeasure dynamicMeasure = env.createDynamicMeasure(subscribedMonitorMeasure, "Queue Name", "Queue 1");
			dynamicMeasure.setValue(24);

			//now we create another one for a different queue name
			dynamicMeasure = env.createDynamicMeasure(subscribedMonitorMeasure, "Queue Name", "Queue 2");
			dynamicMeasure.setValue(32);
		}
		*/

		TibjmsAdmin admin = null;

		try {
			log.fine("Starting execute...");

			String serverUrl = env.getHost().getAddress();

			log.fine("Server : " + serverUrl);

			String port = env.getConfigString("Port");

			log.fine("Port : " + port);

			String userName = env.getConfigString("Username");

			log.fine("User : " + userName);

			String password = env.getConfigPassword("Password");

			serverUrl = "tcp://" + serverUrl + ":" + port;

			log.fine("connecting as " + userName + " to " + serverUrl);

			admin = new TibjmsAdmin(serverUrl,userName,password);

			ServerInfo serverInfo = admin.getInfo();

			Collection<MonitorMeasure> measures;

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_DISK_READ_RATE)) != null) {
				//log.fine("measure: " + MSR_DISK_READ_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					measure.setValue(serverInfo.getDiskReadRate());
					log.fine("measure: " + MSR_DISK_READ_RATE + "  val: " + serverInfo.getDiskReadRate());
					//measure.setValue(100);
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_DISK_WRITE_RATE)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_DISK_WRITE_RATE + "  val: " + serverInfo.getDiskWriteRate());
					measure.setValue(serverInfo.getDiskWriteRate());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_SYNC_STORE_SIZE)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_SYNC_STORE_SIZE + "  val: " + serverInfo.getSyncDBSize());
					measure.setValue(serverInfo.getSyncDBSize());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_ASYNC_STORE_SIZE)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_ASYNC_STORE_SIZE + "  val: " + serverInfo.getAsyncDBSize());
					measure.setValue(serverInfo.getAsyncDBSize());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_MSG_MEM_USED)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_MSG_MEM_USED + "  val: " + serverInfo.getMsgMem());
					measure.setValue(serverInfo.getMsgMem());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_MSG_MEM_POOL_USED)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_MSG_MEM_POOL_USED + "  val: " + serverInfo.getMsgMemPooled());
					measure.setValue(serverInfo.getMsgMemPooled());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_MSG_MAX_MEM)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_MSG_MAX_MEM + "  val: " + serverInfo.getMaxMsgMemory());
					measure.setValue(serverInfo.getMaxMsgMemory());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_MSG_FREE_MEM)) != null) {
				//log.fine("measure: " + MSR_DISK_WRITE_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_MSG_FREE_MEM + "  val: " + (serverInfo.getMaxMsgMemory() - serverInfo.getMsgMem()));
					measure.setValue(serverInfo.getMaxMsgMemory() - serverInfo.getMsgMem());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_CONN_COUNT)) != null) {
				//log.fine("measure: " + MSR_CONN_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_CONN_COUNT + "  val: " + serverInfo.getConnectionCount());
					measure.setValue(serverInfo.getConnectionCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_MAX_CONNS)) != null) {
				//log.fine("measure: " + MSR_MAX_CONNS + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_MAX_CONNS + "  val: " + serverInfo.getMaxConnections());
					measure.setValue(serverInfo.getMaxConnections());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_CONN_PERCENTAGE)) != null) {
				//log.fine("measure: " + MSR_CONN_COUNT + "  len: " + measures.size());

				if (serverInfo.getMaxConnections() > 0) {
					int percentage = (int) (serverInfo.getConnectionCount() * 100 / serverInfo.getMaxConnections());

					for (MonitorMeasure measure : measures) {
						log.fine("measure: " + MSR_CONN_PERCENTAGE + "  val: " + percentage);
						measure.setValue(percentage);
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_SESSION_COUNT)) != null) {
				//log.fine("measure: " + MSR_CONN_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_SESSION_COUNT + "  val: " + serverInfo.getSessionCount());
					measure.setValue(serverInfo.getSessionCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_PRODUCER_COUNT)) != null) {
				//log.fine("measure: " + MSR_PRODUCER_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_PRODUCER_COUNT + "  val: " + serverInfo.getProducerCount());
					measure.setValue(serverInfo.getProducerCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_CONSUMER_COUNT)) != null) {
				//log.fine("measure: " + MSR_CONSUMER_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_CONSUMER_COUNT + "  val: " + serverInfo.getConsumerCount());
					measure.setValue(serverInfo.getConsumerCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_DURABLE_COUNT)) != null) {
				//log.fine("measure: " + MSR_CONSUMER_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_DURABLE_COUNT + "  val: " + serverInfo.getDurableCount());
					measure.setValue(serverInfo.getDurableCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_TOPIC_COUNT)) != null) {
				//log.fine("measure: " + MSR_CONSUMER_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_TOPIC_COUNT + "  val: " + serverInfo.getTopicCount());
					measure.setValue(serverInfo.getTopicCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_QUEUE_COUNT)) != null) {
				//log.fine("measure: " + MSR_CONSUMER_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_QUEUE_COUNT + "  val: " + serverInfo.getQueueCount());
					measure.setValue(serverInfo.getQueueCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_PENDING_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_PENDING_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_PENDING_MSG_COUNT + "  val: " + serverInfo.getPendingMessageCount());
					measure.setValue(serverInfo.getPendingMessageCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_PENDING_MSG_SIZE)) != null) {
				//log.fine("measure: " + MSR_PENDING_MSG_SIZE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_PENDING_MSG_SIZE + "  val: " + serverInfo.getPendingMessageSize());
					measure.setValue(serverInfo.getPendingMessageSize());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_INBOUND_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_INBOUND_MSG_COUNT + "  val: " + serverInfo.getInboundMessageCount());
					measure.setValue(serverInfo.getInboundMessageCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_INBOUND_MSG_RATE)) != null) {
				//log.fine("measure: " + MSR_INBOUND_MSG_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_INBOUND_MSG_RATE + "  val: " + serverInfo.getInboundMessageRate());
					measure.setValue(serverInfo.getInboundMessageRate());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_INBOUND_BYTES_RATE)) != null) {
				//log.fine("measure: " + MSR_INBOUND_BYTES_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_INBOUND_BYTES_RATE + "  val: " + serverInfo.getInboundBytesRate());
					measure.setValue(serverInfo.getInboundBytesRate());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_OUTBOUND_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_OUTBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_OUTBOUND_MSG_COUNT + "  val: " + serverInfo.getOutboundMessageCount());
					measure.setValue(serverInfo.getOutboundMessageCount());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_OUTBOUND_MSG_RATE)) != null) {
				//log.fine("measure: " + MSR_OUTBOUND_MSG_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_OUTBOUND_MSG_RATE + "  val: " + serverInfo.getOutboundMessageRate());
					measure.setValue(serverInfo.getOutboundMessageRate());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_OUTBOUND_BYTES_RATE)) != null) {
				//log.fine("measure: " + MSR_OUTBOUND_BYTES_RATE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_OUTBOUND_BYTES_RATE + "  val: " + serverInfo.getOutboundBytesRate());
					measure.setValue(serverInfo.getOutboundBytesRate());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_LOGFILE_MAX_SIZE)) != null) {
				//log.fine("measure: " + MSR_PENDING_MSG_SIZE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_LOGFILE_MAX_SIZE + "  val: " + serverInfo.getLogFileMaxSize());
					measure.setValue(serverInfo.getLogFileMaxSize());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_LOGFILE_SIZE)) != null) {
				//log.fine("measure: " + MSR_PENDING_MSG_SIZE + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					log.fine("measure: " + MSR_LOGFILE_SIZE + "  val: " + serverInfo.getLogFileSize());
					measure.setValue(serverInfo.getLogFileSize());
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_BROKER_STAT, MSR_LOGFILE_PERCENT_USED)) != null) {
				//log.fine("measure: " + MSR_PENDING_MSG_SIZE + "  len: " + measures.size());

				if (serverInfo.getLogFileMaxSize() > 0) {
					int percentage = (int) (serverInfo.getLogFileSize() * 100 / serverInfo.getLogFileMaxSize());

					for (MonitorMeasure measure : measures) {
						log.fine("measure: " + MSR_LOGFILE_PERCENT_USED + "  val: " + percentage);
						measure.setValue(percentage);
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_CONSUMER_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getConsumerCount());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_CONSUMER_COUNT + "  val: " + queueInfo.getConsumerCount());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getConsumerCount());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_CONSUMER_COUNT + "  val: " + topicInfo.getConsumerCount());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_FLOWCONTROL_MAXBYTES)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getFlowControlMaxBytes());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_FLOWCONTROL_MAXBYTES + "  val: " + queueInfo.getFlowControlMaxBytes());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getFlowControlMaxBytes());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_FLOWCONTROL_MAXBYTES + "  val: " + topicInfo.getFlowControlMaxBytes());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_PENDING_MSG_COUNT)) != null) {
				log.fine("measure: " + MSR_DEST_PENDING_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					log.fine("measure: " + MSR_DEST_PENDING_MSG_COUNT + "  dest get param: " + dest);

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					log.fine("measure: " + MSR_DEST_PENDING_MSG_COUNT + "  dest: " + dest + " queueInfos: " + queueInfos.length);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getPendingMessageCount());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_PENDING_MSG_COUNT + "  val: " + queueInfo.getPendingMessageCount());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						log.fine("measure: " + MSR_DEST_PENDING_MSG_COUNT + "  dest: " + dest + " topicInfos: " + topicInfos.length);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getPendingMessageCount());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_PENDING_MSG_COUNT + "  val: " + topicInfo.getPendingMessageCount());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_PENDING_MSG_SIZE)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getPendingMessageSize());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_PENDING_MSG_SIZE + "  val: " + queueInfo.getPendingMessageSize());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getPendingMessageSize());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_PENDING_MSG_SIZE + "  val: " + topicInfo.getPendingMessageSize());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_INBOUND_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getInboundStatistics().getTotalMessages());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  val: " + queueInfo.getInboundStatistics().getTotalMessages());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getInboundStatistics().getTotalMessages());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  val: " + topicInfo.getInboundStatistics().getTotalMessages());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_INBOUND_MSG_RATE)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getInboundStatistics().getMessageRate());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_INBOUND_MSG_RATE + "  val: " + queueInfo.getInboundStatistics().getMessageRate());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getInboundStatistics().getMessageRate());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_INBOUND_MSG_RATE + "  val: " + topicInfo.getInboundStatistics().getMessageRate());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_INBOUND_BYTES_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getInboundStatistics().getTotalBytes());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_INBOUND_BYTES_COUNT + "  val: " + queueInfo.getInboundStatistics().getTotalBytes());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getInboundStatistics().getTotalBytes());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_INBOUND_BYTES_COUNT + "  val: " + topicInfo.getInboundStatistics().getTotalBytes());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_INBOUND_BYTES_RATE)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getInboundStatistics().getByteRate());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_INBOUND_BYTES_RATE + "  val: " + queueInfo.getInboundStatistics().getByteRate());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getInboundStatistics().getByteRate());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_INBOUND_BYTES_RATE + "  val: " + topicInfo.getInboundStatistics().getByteRate());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_OUTBOUND_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getOutboundStatistics().getTotalMessages());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_MSG_COUNT + "  val: " + queueInfo.getOutboundStatistics().getTotalMessages());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getOutboundStatistics().getTotalMessages());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_MSG_COUNT + "  val: " + topicInfo.getOutboundStatistics().getTotalMessages());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_OUTBOUND_MSG_RATE)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getOutboundStatistics().getMessageRate());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_MSG_RATE + "  val: " + queueInfo.getOutboundStatistics().getMessageRate());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getOutboundStatistics().getMessageRate());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_MSG_RATE + "  val: " + topicInfo.getOutboundStatistics().getMessageRate());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_OUTBOUND_BYTES_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getOutboundStatistics().getTotalBytes());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_BYTES_COUNT + "  val: " + queueInfo.getOutboundStatistics().getTotalBytes());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getOutboundStatistics().getTotalBytes());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_BYTES_COUNT + "  val: " + topicInfo.getOutboundStatistics().getTotalBytes());
							}
						}
						else {
							measure.setValue(0);
						}
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_OUTBOUND_BYTES_RATE)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getOutboundStatistics().getByteRate());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_BYTES_RATE + "  val: " + queueInfo.getOutboundStatistics().getByteRate());
						}
					}
					else {
						TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

						if (topicInfos.length > 0) {
							for (TopicInfo topicInfo : topicInfos) {
								MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
								dynamicMeasure.setValue(topicInfo.getOutboundStatistics().getByteRate());
								log.fine("topic: " + topicInfo.getName() + " measure: " + MSR_DEST_OUTBOUND_BYTES_RATE + "  val: " + topicInfo.getOutboundStatistics().getByteRate());
							}
						}
						else {
							measure.setValue(0);
						}
					}

				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_Q_RECEIVER_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getReceiverCount());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_Q_RECEIVER_COUNT + "  val: " + queueInfo.getReceiverCount());
						}
					}
					else {
						measure.setValue(0);
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_Q_DELIVERED_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getDeliveredMessageCount());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_Q_DELIVERED_MSG_COUNT + "  val: " + queueInfo.getDeliveredMessageCount());
						}
					}
					else {
						measure.setValue(0);
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_Q_INTRANSIT_MSG_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					QueueInfo[] queueInfos = admin.getQueuesStatistics(dest);

					if (queueInfos.length > 0) {
						for (QueueInfo queueInfo : queueInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", queueInfo.getName());
							dynamicMeasure.setValue(queueInfo.getInTransitMessageCount());
							log.fine("queue: " + queueInfo.getName() + " measure: " + MSR_DEST_Q_INTRANSIT_MSG_COUNT + "  val: " + queueInfo.getInTransitMessageCount());
						}
					}
					else {
						measure.setValue(0);
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_T_SUBSCRIBER_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

					if (topicInfos.length > 0) {
						for (TopicInfo topicInfo : topicInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
							dynamicMeasure.setValue(topicInfo.getSubscriberCount());
							log.fine("queue: " + topicInfo.getName() + " measure: " + MSR_DEST_T_SUBSCRIBER_COUNT + "  val: " + topicInfo.getSubscriberCount());
						}
					}
					else {
						measure.setValue(0);
					}
				}
			}

			if ((measures = env.getMonitorMeasures(METRIC_GROUP_DEST_STAT, MSR_DEST_T_DURABLE_COUNT)) != null) {
				//log.fine("measure: " + MSR_DEST_INBOUND_MSG_COUNT + "  len: " + measures.size());

				for (MonitorMeasure measure : measures) {
					String dest = measure.getParameter("Destination");

					if (dest.equals("")) {
						break;
					}

					TopicInfo[] topicInfos = admin.getTopicsStatistics(dest);

					if (topicInfos.length > 0) {
						for (TopicInfo topicInfo : topicInfos) {
							MonitorMeasure dynamicMeasure = env.createDynamicMeasure(measure, "Dest Name", topicInfo.getName());
							dynamicMeasure.setValue(topicInfo.getDurableSubscriptionCount());
							log.fine("queue: " + topicInfo.getName() + " measure: " + MSR_DEST_T_DURABLE_COUNT + "  val: " + topicInfo.getDurableSubscriptionCount());
						}
					}
					else {
						measure.setValue(0);
					}
				}
			}

			admin.close();
			log.fine("closing connection ");

			return new Status(Status.StatusCode.Success);
		}

		catch (TibjmsAdminException exp) {
			String msg = "TibjmsAdminException: " + exp.getMessage();
			log.fine(msg);
			try {
				admin.close();
			} catch (TibjmsAdminException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			Status status = new Status();
			status.setException(exp);
			status.setExceptionClassName("TibjmsAdminException");
			status.setExceptionMessage(exp.getMessage());
			status.setMessage(msg);
			status.setShortMessage(msg);
			status.setStatusCode(Status.StatusCode.ErrorTargetService);
			return status;

			//log.log(Level.FINE, exp.getMessage(), exp);
			//return new Status(Status.StatusCode.ErrorInternal);
			//return new Status(Status.StatusCode.ErrorTargetService, msg, msg, exp);
			//throw new Exception(exp);
		}

		catch (Exception exp) {
			String msg = "Exception: " + exp.getMessage();
			log.fine(msg);
			try {
				admin.close();
			} catch (TibjmsAdminException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			Status status = new Status();
			status.setException(exp);
			status.setExceptionClassName("Exception");
			status.setExceptionMessage(exp.getMessage());
			status.setMessage(msg);
			status.setShortMessage(msg);
			status.setStatusCode(Status.StatusCode.ErrorTargetService);
			return status;

			//return new Status(Status.StatusCode.ErrorTargetService, msg, msg, exp);
			//log.log(Level.SEVERE, exp.getMessage(), exp);
			//return new Status(Status.StatusCode.ErrorInternal);
			//throw new Exception(exp);
		}
	}

	/**
	 * Shuts the Plugin down and frees resources. This method is called in the
	 * following cases:
	 *

	 *
the <tt>setup</tt> method failed

	 *
the Plugin configuration has changed

	 *
the execution duration of the Plugin exceeded the schedule timeout

	 *
the schedule associated with this Plugin was removed

	 *

	 *
	 *

	 * The Plugin methods <tt>setup</tt>, <tt>execute</tt> and
	 * <tt>teardown</tt> are called on different threads, but they are called
	 * sequentially. This means that the execution of these methods does not
	 * overlap, they are executed one after the other.
	 *
	 *

	 * Examples:
	 *

	 *
<tt>setup</tt> (failed) -> <tt>teardown</tt>

	 *
<tt>execute</tt> starts, configuration changes, <tt>execute</tt>
	 * ends -> <tt>teardown</tt>

	 * on next schedule interval: <tt>setup</tt> -> <tt>execute</tt> ...

	 *
<tt>execute</tt> starts, execution duration timeout,
	 * <tt>execute</tt> stops -> <tt>teardown</tt>

	 *
<tt>execute</tt> starts, <tt>execute</tt> ends, schedule is
	 * removed -> <tt>teardown</tt>

	 *

	 * Failed means that either an unhandled exception is thrown or the status
	 * returned by the method contains a non-success code.
	 *
	 *
	 *

	 * All by the Plugin allocated resources should be freed in this method.
	 * Examples are opened sockets or files.
	 *
	 * @see Monitor#setup(MonitorEnvironment)
	 */	@Override
	public void teardown(MonitorEnvironment env) throws Exception {
		 // TODO
	}

	 public static void main(String[] args) throws TibjmsAdminException {
		 System.out.println("erpo");

		 TibjmsAdmin erp = new TibjmsAdmin("tcp://localhost:7222", "admin","");

		 System.out.println("logfile max size:" + erp.getInfo().getLogFileMaxSize());
		 System.out.println("logfile size:" + erp.getInfo().getLogFileSize());

		 TopicInfo[] topicInfos = erp.getTopicsStatistics();

		 System.out.println("size:" + topicInfos.length);

		 for (TopicInfo topicInfo : topicInfos) {
			 System.out.println("topic: " + topicInfo.toString());

		 }

		 QueueInfo[] queueInfos = erp.getQueuesStatistics();

		 System.out.println("size:" + queueInfos.length);

		 for (QueueInfo queueInfo : queueInfos) {
			 System.out.println("queue: " + queueInfo.toString());

		 }

		 queueInfos = erp.getQueuesStatistics("");

		 System.out.println("size2:" + queueInfos.length);

		 System.out.println("queue count: " + queueInfos[0].getInboundStatistics().getTotalMessages());

		 System.out.println("erp1");
		 //erp.getChannelStatistics(arg0)
	 }
}


text:
package com.iluwatar.creature;

import com.iluwatar.property.Color;
import com.iluwatar.property.Movement;
import com.iluwatar.property.Size;

/**
 *
 * Goblin creature.
 *
 */
public class Goblin extends AbstractCreature {

	public Goblin() {
		super("Goblin", Size.SMALL, Movement.WALKING, Color.GREEN);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel;

namespace InnovatorAdmin.ColorTheory
{
  /// <summary>
  /// Structure to define RGB.
  /// </summary>
  public struct RGB
  {
    /// <summary>
    /// Gets an empty RGB structure;
    /// </summary>
    public static readonly RGB Empty = new RGB();

    #region Fields
    private int red;
    private int green;
    private int blue;

    #endregion

    #region Operators
    public static bool operator ==(RGB item1, RGB item2)
    {
      return (
        item1.Red == item2.Red
        && item1.Green == item2.Green
        && item1.Blue == item2.Blue
        );
    }

    public static bool operator !=(RGB item1, RGB item2)
    {
      return (
        item1.Red != item2.Red
        || item1.Green != item2.Green
        || item1.Blue != item2.Blue
        );
    }

    #endregion

    #region Accessors
    [Description("Red component."),]
    public int Red
    {
      get
      {
        return red;
      }
      set
      {
        red = (value>255)? 255 : ((value<0)?0 : value);
      }
    }

    [Description("Green component."),]
    public int Green
    {
      get
      {
        return green;
      }
      set
      {
        green = (value>255)? 255 : ((value<0)?0 : value);
      }
    }

    [Description("Blue component."),]
    public int Blue
    {
      get
      {
        return blue;
      }
      set
      {
        blue = (value>255)? 255 : ((value<0)?0 : value);
      }
    }
    #endregion

    public RGB(int R, int G, int B)
    {
      red = (R>255)? 255 : ((R<0)?0 : R);
      green = (G>255)? 255 : ((G<0)?0 : G);
      blue = (B>255)? 255 : ((B<0)?0 : B);
    }

    public System.Drawing.Color ToColor()
    {
      return System.Drawing.Color.FromArgb(this.red, this.green, this.blue);
    }

    #region Methods
    public override bool Equals(Object obj)
    {
      if(obj==null || GetType()!=obj.GetType()) return false;

      return (this == (RGB)obj);
    }

    public override int GetHashCode()
    {
      return Red.GetHashCode() ^ Green.GetHashCode() ^ Blue.GetHashCode();
    }

    #endregion
  }
}


text:
/**
 * Helper for splitted-navigation element.
 *
 * @author Htmlstream
 * @version 1.0
 *
 */
;(function($){
	'use strict';

	$.HSCore.helpers.HSNavigationSplitted = {

		/**
		 * Base configuration of the helper.
		 *
		 * @private
		 */
		_baseConfig: {
			breakpoint: 992,
			mobileTarget: null,
			logoSelector: '.navbar-brand',
			logoItemSelector: '.nav-logo-item'
		},

		/**
		 * Contains all initialized items on the page.
		 *
		 * @private
		 */
		_pageCollection: $(),

		/**
		 * Initialization.
		 *
		 * @param {jQuery} collection
		 * @param {Object} config
		 *
		 * @return {jQuery}
		 */
		init: function(collection, config) {

			var self;

			if(!collection || !collection.length) return $();

			self = this;

			$(window).on('resize.HSSplitteNavigation', function(){

				if( self.resizeTimeOutId ) clearTimeout( self.resizeTimeOutId );

				self.resizeTimeOutId = setTimeout(function(){
					self._pageCollection.each(function(i, el){
						$(el).data('HSSplittedNavigation').check();
					});
				},10);

			});

			collection.each(function(i, el){

				var $item = $(el);

				config = config && $.isPlainObject(config) ?
								$.extend(true, {}, self._baseConfig, config, $item.data()) :
								$.extend(true, {}, self._baseConfig, $item.data());

				if( $item.data('HSSplittedNavigation') ) return;

				$item.data('HSSplittedNavigation', new HSSplittedNavigation( $item, config ));
				self._pageCollection = self._pageCollection.add($item);

			});

			self._pageCollection.each(function(i, el){
				$(el).data('HSSplittedNavigation').run();
			});

			return collection;

		}

	};

	/**
	 * Creates a splitted-navigation object.
	 *
	 * @param {jQuery} element
	 * @param {Object} config
	 *
	 * @constructor
	 */
	function HSSplittedNavigation(element, config) {
		this.element = element;
		this.config = config;

		this.logo = this.element.find( this.config.logoSelector );
		this.logoItem = this.element.find( this.config.logoItemSelector );
		this.target = this.element.find( this.config.mobileTarget ).length ? this.element.find( this.config.mobileTarget ) : this.element;
	}

	/**
	 *
	 *
	 * @public
	 * @return {HSSplittedNavigation}
	 */
	HSSplittedNavigation.prototype.run = function() {

		this[$(window).width() < this.config.breakpoint ? 'toMobileState' : 'toDefaultState']();

		return this;

	}

	/**
	 *
	 *
	 * @public
	 * @return {HSSplittedNavigation}
	 */
	HSSplittedNavigation.prototype.check = function() {

		var $w = $(window);

		if( $w.width() < this.config.breakpoint && this.defaultState) {
			this.toMobileState();
		}
		else if( $w.width() >= this.config.breakpoint && !this.defaultState ) {
			this.toDefaultState();
		}

		return this;

	}

	/**
	 *
	 *
	 * @public
	 * @return {HSSplittedNavigation}
	 */
	HSSplittedNavigation.prototype.toDefaultState = function() {
		if( !this.logoItem.length || !this.logo.length ) return this;

		this.logoItem.show().append( this.logo );

		this.defaultState = true;
		return this;
	}

	/**
	 *
	 *
	 * @public
	 * @return {HSSplittedNavigation}
	 */
	HSSplittedNavigation.prototype.toMobileState = function() {
		if( !this.logoItem.length || !this.logo.length ) return this;

		this.target.before( this.logo );
		this.logoItem.hide();

		this.defaultState = false;
		return this;
	}

})(jQuery);


text:
package org.waveprotocol.box.server.persistence.mongodb;

import static com.mongodb.client.model.Filters.eq;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.BasicBSONList;
import org.waveprotocol.box.attachment.AttachmentMetadata;
import org.waveprotocol.box.attachment.AttachmentProto;
import org.waveprotocol.box.attachment.proto.AttachmentMetadataProtoImpl;
import org.waveprotocol.box.server.account.AccountData;
import org.waveprotocol.box.server.account.HumanAccountData;
import org.waveprotocol.box.server.account.HumanAccountDataImpl;
import org.waveprotocol.box.server.account.RobotAccountData;
import org.waveprotocol.box.server.account.RobotAccountDataImpl;
import org.waveprotocol.box.server.account.SecretToken;
import org.waveprotocol.box.server.authentication.PasswordDigest;
import org.waveprotocol.box.server.persistence.AccountStore;
import org.waveprotocol.box.server.persistence.AttachmentStore;
import org.waveprotocol.box.server.persistence.PersistenceException;
import org.waveprotocol.box.server.persistence.SignerInfoStore;
import org.waveprotocol.box.server.robots.RobotCapabilities;
import org.waveprotocol.wave.crypto.SignatureException;
import org.waveprotocol.wave.crypto.SignerInfo;
import org.waveprotocol.wave.federation.Proto.ProtocolSignerInfo;
import org.waveprotocol.wave.media.model.AttachmentId;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.Preconditions;
import org.waveprotocol.wave.model.wave.ParticipantId;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.wave.api.Context;
import com.google.wave.api.ProtocolVersion;
import com.google.wave.api.event.EventType;
import com.google.wave.api.robot.Capability;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateOptions;

/**
 * CertPathStore:

 * Collection(signerInfo):
 *

 *
_id : signerId byte array.

 *
protoBuff : byte array representing the protobuff message of a
 * {@link ProtocolSignerInfo}.

 *

 *

 *
 * @author ljvderijk@google.com (Lennard de Rijk)
 * @author josephg@gmail.com (Joseph Gentle)
 *
 */
public final class MongoDbStore implements SignerInfoStore, AttachmentStore, AccountStore {

  private static final String ACCOUNT_COLLECTION = "account";
  private static final String ACCOUNT_HUMAN_DATA_FIELD = "human";
  private static final String ACCOUNT_ROBOT_DATA_FIELD = "robot";

  private static final String HUMAN_PASSWORD_FIELD = "passwordDigest";

  private static final String PASSWORD_DIGEST_FIELD = "digest";
  private static final String PASSWORD_SALT_FIELD = "salt";

  private static final String ROBOT_URL_FIELD = "url";
  private static final String ROBOT_SECRET_FIELD = "secret";
  private static final String ROBOT_CAPABILITIES_FIELD = "capabilities";
  private static final String ROBOT_VERIFIED_FIELD = "verified";

  private static final String CAPABILITIES_VERSION_FIELD = "version";
  private static final String CAPABILITIES_HASH_FIELD = "capabilitiesHash";
  private static final String CAPABILITIES_CAPABILITIES_FIELD = "capabilities";
  private static final String CAPABILITY_CONTEXTS_FIELD = "contexts";
  private static final String CAPABILITY_FILTER_FIELD = "filter";

  private static final Logger LOG = Logger.getLogger(MongoDbStore.class.getName());
  private static final String EMAIL_FIELD = "email";
  private static final String TOKEN_FIELD = "token";
  private static final String TOKEN_DATE_FIELD = "token_date";

  private static final String ACCOUNT_AVATAR_FILE = "avatarFile";
  private static final String ACCOUNT_LOCALE = "locale";
  private static final String NAME_FIELD = "name";

  private final MongoDatabase database;
  private final GridFSBucket attachmentGrid;
  private final GridFSBucket thumbnailGrid;
  private final GridFSBucket metadataGrid;

  MongoDbStore(MongoDatabase database) {
    this.database = database;
    attachmentGrid = GridFSBuckets.create(database, "attachments");
    thumbnailGrid = GridFSBuckets.create(database, "thumbnails");
    metadataGrid = GridFSBuckets.create(database, "metadata");
  }

  @Override
  public void initializeSignerInfoStore() throws PersistenceException {
    // Nothing to initialize
  }

  private static Bson filterSignerInfoBy(byte[] signerId) {
    return Filters.eq("_id", signerId);
  }

  @Override
  public SignerInfo getSignerInfo(byte[] signerId) {

    BasicDBObject signerInfoDBObject = getSignerInfoCollection().find(filterSignerInfoBy(signerId)).first();
    // Sub-class contract specifies return null when not found
    SignerInfo signerInfo = null;

    if (signerInfoDBObject != null) {
      byte[] protobuff = (byte[]) signerInfoDBObject.get("protoBuff");
      try {
        signerInfo = new SignerInfo(ProtocolSignerInfo.parseFrom(protobuff));
      } catch (InvalidProtocolBufferException e) {
        LOG.log(Level.SEVERE, "Couldn't parse the protobuff stored in MongoDB: " + protobuff, e);
      } catch (SignatureException e) {
        LOG.log(Level.SEVERE, "Couldn't parse the certificate chain or domain properly", e);
      }
    }
    return signerInfo;
  }

  @Override
  public void putSignerInfo(ProtocolSignerInfo protocolSignerInfo) throws SignatureException {
    SignerInfo signerInfo = new SignerInfo(protocolSignerInfo);
    byte[] signerId = signerInfo.getSignerId();

    // Not using a modifier here because rebuilding the object is not a lot of
    // work.
    BasicDBObject signerInfoDBObject = new BasicDBObject("_id", signerId);
    signerInfoDBObject.put("protoBuff", protocolSignerInfo.toByteArray());

    getSignerInfoCollection().replaceOne(filterSignerInfoBy(signerId), signerInfoDBObject,
        new UpdateOptions().upsert(true));
  }

  /**
   * Returns an instance of {@link DBCollection} for storing SignerInfo.
   */
  private MongoCollection<BasicDBObject> getSignerInfoCollection() {
    return database.getCollection("signerInfo", BasicDBObject.class);
  }

  // *********** Attachments.

  @Override
  public AttachmentData getAttachment(AttachmentId attachmentId) {

    GridFSFile gridFile = getAttachmentGridFSFile(attachmentId);

    if (gridFile == null)
      return null;

    return fileToAttachmentData(gridFile);
  }

  @Override
  public void storeAttachment(AttachmentId attachmentId, InputStream dataInputStream)
      throws IOException {

    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024)
        .metadata(new Document("type", "attachment").append("id", attachmentId.serialise()));

    attachmentGrid.uploadFromStream(attachmentId.serialise(), dataInputStream, options);
  }

  @Override
  public void deleteAttachment(AttachmentId attachmentId) {
    GridFSFile attachmentFile = getAttachmentGridFSFile(attachmentId);
    if (attachmentFile != null)
      attachmentGrid.delete(attachmentFile.getObjectId());

    GridFSFile thumbnailFile = getThumnailGridFSFile(attachmentId);
    if (thumbnailFile != null)
      thumbnailGrid.delete(thumbnailFile.getObjectId());

    GridFSFile metadataFile = getMetadataGridFSFile(attachmentId);
    if (metadataFile != null)
      metadataGrid.delete(metadataFile.getObjectId());
  }

  private GridFSFile getAttachmentGridFSFile(AttachmentId attachmentId) {
    return attachmentGrid.find(eq("metadata.id", attachmentId.serialise())).first();
  }

  private GridFSFile getMetadataGridFSFile(AttachmentId attachmentId) {
    return metadataGrid.find(eq("metadata.id", attachmentId.serialise())).first();
  }

  private GridFSFile getThumnailGridFSFile(AttachmentId attachmentId) {
    return thumbnailGrid.find(eq("metadata.id", attachmentId.serialise())).first();
  }

  @Override
  public AttachmentMetadata getMetadata(AttachmentId attachmentId) throws IOException {
    GridFSFile metadataFile = getMetadataGridFSFile(attachmentId);

    if (metadataFile == null)
      return null;

    try (GridFSDownloadStream metadataStream = metadataGrid
        .openDownloadStream(metadataFile.getObjectId())) {

      if (metadataStream == null) {
        return null;
      }

      AttachmentProto.AttachmentMetadata protoMetadata = AttachmentProto.AttachmentMetadata
          .parseFrom(metadataStream);

      return new AttachmentMetadataProtoImpl(protoMetadata);

    } catch (MongoException e) {
      throw new IOException(e);
    }

  }

  @Override
  public AttachmentData getThumbnail(AttachmentId attachmentId) throws IOException {
    GridFSFile thumbFile = getThumnailGridFSFile(attachmentId);
    return fileToAttachmentData(thumbFile);
  }

  @Override
  public void storeMetadata(AttachmentId attachmentId, AttachmentMetadata metaData)
      throws IOException {
    AttachmentMetadataProtoImpl proto = new AttachmentMetadataProtoImpl(metaData);
    byte[] bytes = proto.getPB().toByteArray();

    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(255)
        .metadata(new Document("type", "metadata").append("id", attachmentId.serialise()));

    metadataGrid.uploadFromStream(attachmentId.serialise(), new ByteArrayInputStream(bytes),
        options);
  }

  @Override
  public void storeThumbnail(AttachmentId attachmentId, InputStream dataInputStream)
      throws IOException {

    GridFSUploadOptions options = new GridFSUploadOptions()
        .chunkSizeBytes(1024)
        .metadata(new Document("type", "thumbnail").append("id", attachmentId.serialise()));

    thumbnailGrid.uploadFromStream(attachmentId.serialise(), dataInputStream,
        options);
  }

  private AttachmentData fileToAttachmentData(final GridFSFile attachmentFile) {
    if (attachmentFile == null) {
      return null;
    } else {
      return new AttachmentData() {

        @Override
        public InputStream getInputStream() throws IOException {
          return attachmentGrid.openDownloadStream(attachmentFile.getObjectId());
        }

        @Override
        public long getSize() {
          return attachmentFile.getLength();
        }
      };
    }
  }

  // ******** AccountStore

  private static Bson filterAccountBy(ParticipantId id) {
    return Filters.eq("_id", id.getAddress());
  }

  private static Bson filterAccountByEmail(String email) {
    return Filters.eq(ACCOUNT_HUMAN_DATA_FIELD + "." + EMAIL_FIELD, email);
  }

  private BasicDBObject getAccountDBObject(ParticipantId id) {
    return getAccountCollection().find(filterAccountBy(id)).first();
  }

  @Override
  public void initializeAccountStore() throws PersistenceException {
    // TODO: Sanity checks not handled by MongoDBProvider???
  }

  @Override
  public AccountData getAccount(ParticipantId id) {
    BasicDBObject accountDBObject = getAccountDBObject(id);

    if (accountDBObject == null) {
      return null;
    }

    return accountFromQueryResult(accountDBObject, id);
  }

  @Override
  public void putAccount(AccountData account) {

    BasicDBObject object = new BasicDBObject("_id", account.getId().getAddress());

    if (account.isHuman()) {
      object.put(ACCOUNT_HUMAN_DATA_FIELD, humanToObject(account.asHuman()));
    } else if (account.isRobot()) {
      object.put(ACCOUNT_ROBOT_DATA_FIELD, robotToObject(account.asRobot()));
    } else {
      throw new IllegalStateException("Account is neither a human nor a robot");
    }

    getAccountCollection().replaceOne(
        filterAccountBy(account.getId()),
        object,
        new UpdateOptions().upsert(true));
  }

  @Override
  public void removeAccount(ParticipantId id) {
    getAccountCollection().deleteOne(filterAccountBy(id));
  }

  private MongoCollection<BasicDBObject> getAccountCollection() {
    return database.getCollection(ACCOUNT_COLLECTION, BasicDBObject.class);
  }

  // ****** HumanAccountData serialization

  private DBObject humanToObject(HumanAccountData account) {
    DBObject object = new BasicDBObject();

    PasswordDigest digest = account.getPasswordDigest();
    if (digest != null) {
      DBObject digestObj = new BasicDBObject();
      digestObj.put(PASSWORD_SALT_FIELD, digest.getSalt());
      digestObj.put(PASSWORD_DIGEST_FIELD, digest.getDigest());

      object.put(HUMAN_PASSWORD_FIELD, digestObj);
    }

    if (account.getEmail() != null) {
      object.put(EMAIL_FIELD, account.getEmail());
    }

    if (account.getRecoveryToken() != null) {
      object.put(TOKEN_FIELD, account.getRecoveryToken().getToken());
      object.put(TOKEN_DATE_FIELD, account.getRecoveryToken().getExpirationDate());
    }

    if (account.getLocale() != null) {
      object.put(ACCOUNT_LOCALE, account.getLocale());
    }

    if (account.getAvatarFileName() != null) {
      object.put(ACCOUNT_AVATAR_FILE, account.getAvatarFileId());
    }

    if (account.getName() != null) {
      object.put(NAME_FIELD, account.getName());
    }

    return object;
  }

  private HumanAccountData objectToHuman(ParticipantId id, DBObject object) {
    PasswordDigest passwordDigest = null;
    String email = null;
    SecretToken token = null;
    String locale = null;
    String avatarFileName = null;
    String name = null;

    DBObject digestObj = (DBObject) object.get(HUMAN_PASSWORD_FIELD);
    if (digestObj != null) {
      byte[] salt = (byte[]) digestObj.get(PASSWORD_SALT_FIELD);
      byte[] digest = (byte[]) digestObj.get(PASSWORD_DIGEST_FIELD);
      passwordDigest = PasswordDigest.from(salt, digest);
    }
    email = (String) object.get(EMAIL_FIELD);
    token = new SecretToken((String) object.get(TOKEN_FIELD),
        (java.util.Date) object.get(TOKEN_DATE_FIELD));

    locale = (String) object.get(ACCOUNT_LOCALE);
    avatarFileName = (String) object.get(ACCOUNT_AVATAR_FILE);
    name = (String) object.get(NAME_FIELD);

    return new HumanAccountDataImpl(id, passwordDigest, email, token, locale, avatarFileName, name);
  }

  // ****** RobotAccountData serialization

  private DBObject robotToObject(RobotAccountData account) {
    return new BasicDBObject()
        .append(ROBOT_URL_FIELD, account.getUrl())
        .append(ROBOT_SECRET_FIELD, account.getConsumerSecret())
        .append(ROBOT_CAPABILITIES_FIELD, capabilitiesToObject(account.getCapabilities()))
        .append(ROBOT_VERIFIED_FIELD, account.isVerified());
  }

  private DBObject capabilitiesToObject(RobotCapabilities capabilities) {
    if (capabilities == null) {
      return null;
    }

    BasicDBObject capabilitiesObj = new BasicDBObject();
    for (Capability capability : capabilities.getCapabilitiesMap().values()) {
      BasicBSONList contexts = new BasicBSONList();
      for (Context c : capability.getContexts()) {
        contexts.add(c.name());
      }
      capabilitiesObj.put(capability.getEventType().name(),
          new BasicDBObject()
              .append(CAPABILITY_CONTEXTS_FIELD, contexts)
              .append(CAPABILITY_FILTER_FIELD, capability.getFilter()));
    }

    BasicDBObject object =
        new BasicDBObject()
            .append(CAPABILITIES_CAPABILITIES_FIELD, capabilitiesObj)
            .append(CAPABILITIES_HASH_FIELD, capabilities.getCapabilitiesHash())
            .append(CAPABILITIES_VERSION_FIELD, capabilities.getProtocolVersion().name());

    return object;
  }

  private AccountData objectToRobot(ParticipantId id, DBObject robot) {
    String url = (String) robot.get(ROBOT_URL_FIELD);
    String secret = (String) robot.get(ROBOT_SECRET_FIELD);
    RobotCapabilities capabilities =
        objectToCapabilities((DBObject) robot.get(ROBOT_CAPABILITIES_FIELD));
    boolean verified = (Boolean) robot.get(ROBOT_VERIFIED_FIELD);
    return new RobotAccountDataImpl(id, url, secret, capabilities, verified);
  }

  @SuppressWarnings("unchecked")
  private RobotCapabilities objectToCapabilities(DBObject object) {
    if (object == null) {
      return null;
    }

    Map<String, Object> capabilitiesObj =
	(Map<String, Object>) object.get(CAPABILITIES_CAPABILITIES_FIELD);
    Map<EventType, Capability> capabilities = CollectionUtils.newHashMap();

    for (Entry<String, Object> capability : capabilitiesObj.entrySet()) {
      EventType eventType = EventType.valueOf(capability.getKey());
      List<Context> contexts = CollectionUtils.newArrayList();
      DBObject capabilityObj = (DBObject) capability.getValue();
      DBObject contextsObj = (DBObject) capabilityObj.get(CAPABILITY_CONTEXTS_FIELD);
      for (String contextId : contextsObj.keySet()) {
        contexts.add(Context.valueOf((String) contextsObj.get(contextId)));
      }
      String filter = (String) capabilityObj.get(CAPABILITY_FILTER_FIELD);

      capabilities.put(eventType, new Capability(eventType, contexts, filter));
    }

    String capabilitiesHash = (String) object.get(CAPABILITIES_HASH_FIELD);
    ProtocolVersion version =
        ProtocolVersion.valueOf((String) object.get(CAPABILITIES_VERSION_FIELD));

    return new RobotCapabilities(capabilities, capabilitiesHash, version);
  }

  @Override
  public List<AccountData> getAccountByEmail(String email) throws PersistenceException {

    Preconditions.checkNotNull(email, "Email can't be null");
    final ArrayList<AccountData> accounts = new ArrayList<AccountData>();
    getAccountCollection().find(filterAccountByEmail(email)).forEach(new Block<BasicDBObject>() {

      @Override
      public void apply(BasicDBObject t) {
        accounts.add(accountFromQueryResult(t, null));
      }

    });
    return accounts;

  }

  private AccountData accountFromQueryResult(DBObject result, ParticipantId id) {

    if (id == null) {
      id = new ParticipantId((String) result.get("_id"));
    }

    DBObject human = (DBObject) result.get(ACCOUNT_HUMAN_DATA_FIELD);
    if (human != null) {
      return objectToHuman(id, human);
    }

    DBObject robot = (DBObject) result.get(ACCOUNT_ROBOT_DATA_FIELD);
    if (robot != null) {
      return objectToRobot(id, robot);
    }

    throw new IllegalStateException("DB object contains neither a human nor a robot");

  }

}


text:
It can be quite useful to add colour to your output from `grep`, since it helps is identifying matches and hence makes sure you do not overlook something.

Basic example:

```bash
$ grep --color <pattern> <file>
```

Default colour is red, but can be changes using the environment variable `GREP_COLOR`:

An example:

```bash
$ GREP_COLOR='1;36' grep --color <pattern> <file>
```

I have only used two parameters in the above example, You can in addition set the background colour, please see the listed source for more details.

## References

- [Website](http://www.unixcl.com/2009/03/highlight-match-with-color-in-grep.html)


text:
package net.imglib2.ops.operation.img.unary;

import net.imglib2.Cursor;
import net.imglib2.FinalInterval;
import net.imglib2.Interval;
import net.imglib2.RandomAccess;
import net.imglib2.RealInterval;
import net.imglib2.img.Img;
import net.imglib2.ops.operation.UnaryOperation;
import net.imglib2.type.Type;

/**
 * Crops an image.
 *
 * @author Christian Dietz (University of Konstanz)
 * @author Martin Horn (University of Konstanz)
 * @deprecated Use net.imagej.ops instead.
 */
@Deprecated
public class ImgCrop< T extends Type< T >> implements UnaryOperation< Img< T >, Img< T >>
{

	/**
	 * The interval to be cropped
	 */
	private final Interval m_interval;

	/**
	 * Crops the intervaled defined by origin and extend
	 *
	 * @param origin
	 *            origin of the interval
	 *
	 * @param extend
	 *            extend of the interval
	 */
	public ImgCrop( long[] origin, long[] extend )
	{
		long[] max = new long[ extend.length ];
		for ( int i = 0; i < max.length; i++ )
		{
			max[ i ] = origin[ i ] + extend[ i ] - 1;
		}
		m_interval = new FinalInterval( origin, max );
	}

	/**
	 * Crops the intervaled defined by origin and extend
	 *
	 * @param origin
	 *            origin of the interval
	 *
	 * @param extend
	 *            extend of the interval
	 */
	public ImgCrop( int[] origin, int[] extend )
	{
		long[] max = new long[ extend.length ];
		long[] loffset = new long[ extend.length ];
		for ( int i = 0; i < max.length; i++ )
		{
			max[ i ] = origin[ i ] + extend[ i ] - 1;
			loffset[ i ] = origin[ i ];
		}
		m_interval = new FinalInterval( loffset, max );
	}

	/**
	 * Crops an interval
	 *
	 * @param interval
	 */
	public ImgCrop( Interval interval )
	{
		m_interval = interval;
	}

	/**
	 *
	 * @param interval
	 * @param imgFac
	 */
	public ImgCrop( RealInterval interval )
	{
		long[] min = new long[ interval.numDimensions() ];
		long[] max = new long[ interval.numDimensions() ];
		for ( int i = 0; i < max.length; i++ )
		{
			min[ i ] = ( long ) Math.floor( interval.realMin( i ) );
			max[ i ] = ( long ) Math.ceil( interval.realMax( i ) );
		}
		m_interval = new FinalInterval( min, max );
	}

	@Override
	public Img< T > compute( Img< T > op, Img< T > r )
	{
		Cursor< T > rc = r.localizingCursor();
		RandomAccess< T > opc = op.randomAccess();
		while ( rc.hasNext() )
		{
			rc.next();
			for ( int d = 0; d < m_interval.numDimensions(); d++ )
			{
				opc.setPosition( rc.getLongPosition( d ) + m_interval.min( d ), d );
			}
			rc.get().set( opc.get() );
		}

		return r;
	}

	@Override
	public UnaryOperation< Img< T >, Img< T >> copy()
	{
		return new ImgCrop< T >( m_interval );
	}
}


text:
import DetailsWithDiff from '../../../../ui/components/details-diff.jsx';
import fixture from '../../../fixtures/components/failed/details-diff.js';
import {render, stubMethod} from '../../helpers.js';

describe('Failed', function() {
  describe('Callbacks', function() {
    let component;

    beforeEach(function() {
      stubMethod(DetailsWithDiff, 'render', null);
      component = render(DetailsWithDiff, fixture);
    });

    DetailsWithDiff.VIEWS.forEach(function(item) {
      it(`should change the view to ${item.name}`, function() {
        const view = item.name;

        component.onViewChange({target: {name: view}});
        expect(component.state.view).to.equal(view);
      });
    });

    it('should change the state which toggles the error message', function() {
      component.onErrorMessageOpen(false);
      expect(component.state.openError).to.be.true;
    });
  });
});


text:
.list li{background: #F2F4F3; list-style: none; overflow: hidden;margin: 0 0 8px 0;}
.list a{
    text-align: left;
    width: 100%;
    height: 100%;
    padding: 10px;
    display: block;
    background: url(../images/arrow.png) no-repeat right center;
    background-size: auto 10px;
    background-origin:content-box;
}
.list a:active,
.list a.active{ background-color: #eee;}
.list a >*{height: 50px; vertical-align: middle; display: table-cell;}
.list a >*:last-child{width: 100%;}
.list .list-img b{ width: 50px; height: 50px; overflow: hidden;text-align: center; display: block;}
.list-img .fa{ font-size: 40px; width: 50px; height: 50px; line-height: 50px; color: #999;}
.list .list-text>*{padding-right: 10px;font-weight: 100;  line-height: 20px; }
.list h1,
.list h2{text-indent: 10px;overflow:hidden;height: 20px;}
.list-text b,
.list-text small{ padding-left: 10px; display: block;}
.list a >*:first-child h1,
.list a >*:first-child h2{text-indent: 0;}
.list a >*:first-child b,
.list a >*:first-child small{ padding-left: 0;}
.list h1,
.list-text b{ font-size: 14px; color: #333;}
.list h2,
.list-text small{ font-size: 12px; color: #666;}
.list img{ width: 100%; min-height: 100%;}
.btn-up-1{ background: #999;}
.btn-up-1 .fa{ background: #fff; color: #999;}
.navPop-1 .navPop-btn{ background: #999;}
.navPop-1 .navPop-btn .fa{ background: #fff; color: #999;}
.navPop-wrap>div a{
    background: #999;
    color: #fff;
}
.slider-hor .slider-span{ width: 100%;}


text:
{-# LANGUAGE TemplateHaskell #-}

module LenseDemo
       ()where

import Control.Lens

data Point = Point {
           _x :: Double,
           _y :: Double
           } deriving (Show)

data Mario = Mario { _location :: Point } deriving (Show)

makeLenses ''Point
makeLenses ''Mario

player1 = Mario (Point 0 0)

main = print (location.x +~ 10 $ player1)


text:
function k = whitefixedKernDiagCompute(kern, x)

% WHITEFIXEDKERNDIAGCOMPUTE Compute diagonal of WHITEFIXED kernel.
% FORMAT
% DESC computes the diagonal of the kernel matrix for the fixed parameter white noise kernel given a design matrix of inputs.
% ARG kern : the kernel structure for which the matrix is computed.
% ARG x : input data matrix in the form of a design matrix.
% RETURN k : a vector containing the diagonal of the kernel matrix
% computed at the given points.
%
% SEEALSO : whitefixedKernParamInit, kernDiagCompute, kernCreate, whitefixedKernCompute
%
% COPYRIGHT : Nathaniel J. King, 2006

% KERN

k = whiteKernDiagCompute(kern, x);


text:
using System;
using System.Threading.Tasks;

namespace StackExchange.Exceptional
{
    public static partial class ExceptionalUtils
    {
        /// <summary>
        /// General test methods for exceptions.
        /// </summary>
        public static class Test
        {
#pragma warning disable CS1591, CS1998
            public static async Task ThrowStackAsync() => await MethodA().ConfigureAwait(false);
            private static async Task MethodA() => await MethodB().ConfigureAwait(false);
            private static async Task MethodB() => await MethodC().ConfigureAwait(false);
            private static async Task MethodC() {
                var ex = new Exception("This is a test async exception from Exceptional, I SAY GOOD DAY!");
                ex.Data["SQL"] = "Select * From FUBARAsync -- This is a SQL command!";
                ex.Data["Redis-Server"] = "REDIS01";
                ex.Data["Some-Key"] = "Hello!";
                throw ex;
            }
#pragma warning restore CS1998, CS1591

            /// <summary>
            /// Gets an example RedisException
            /// </summary>
            /// <returns></returns>
            public static RedisException GetRedisException()
            {
                var ex = new RedisException("GetInt: Timeout performing GET prod-throttle-11.22.33.44-reqs, inst: 1, queue: 8, qu: 0, qs: 8, qc: 0, wr: 0, wq: 0, in: 0, ar: 0, clientName: API v2, serverEndpoint: Unspecified/redis01.servers.stackexchange.com:6379, keyHashSlot: 2576, IOCP: (Busy=0,Free=1000,Min=48,Max=1000), WORKER: (Busy=3,Free=32764,Min=48,Max=32767) (Please take a look at this article for some common client-side issues that can cause timeouts: http://stackexchange.github.io/StackExchange.Redis/Timeouts) with keys: throttle-11.22.33.44-reqs");
                ex.Data["redis-command"] = "GET prod-throttle-11.22.33.44-reqs";
                ex.Data["redis-server"] = "redis01.servers.stackexchange.com:6379";
                ex.Data["Redis-Message"] = "GET prod-throttle-11.22.33.44-reqs";
                ex.Data["Redis-Instantaneous"] = "1";
                ex.Data["Redis-Queue-Length"] = "8";
                ex.Data["Redis-Queue-Outstanding"] = "0";
                ex.Data["Redis-Queue-Awaiting-Response"] = "0";
                ex.Data["Redis-Queue-Completion-Outstanding"] = "0";
                ex.Data["Redis-Active-Writers"] = "0";
                ex.Data["Redis-Write-Queue"] = "0";
                ex.Data["Redis-Inbound-Bytes"] = "0";
                ex.Data["Redis-Active-Readers"] = "0";
                ex.Data["Redis-Client-Name"] = "API v2";
                ex.Data["Redis-Server-Endpoint"] = "Unspecified/redis01.servers.stackexchange.com:6379";
                ex.Data["Redis-Key-HashSlot"] = "2576";
                ex.Data["Redis-ThreadPool-IO-Completion"] = "(Busy=0,Free=1000,Min=48,Max=1000)";
                ex.Data["Redis-ThreadPool-Workers"] = "(Busy=3,Free=32764,Min=48,Max=32767)";
                ex.Data["Redis-Busy-Workers"] = "3";
                return ex;
            }

#pragma warning disable RCS1194 // Implement exception constructors.
            /// <summary>
            /// A mock RedisException, like StackExchange.Redis contains
            /// </summary>
            public class RedisException : Exception, IExceptionalHandled
            {
                /// <summary>
                /// Creates a redis exception with a message.
                /// </summary>
                /// <param name="message">The message to use for this exception.</param>
                public RedisException(string message) : base(message) { }

                /// <summary>
                /// An example of a handler that adds data to the exception when logged.
                /// This will be called whenever the exception is logged, adding a command and keys
                /// to the exception.
                /// </summary>
                /// <param name="e">The <see cref="Error"/> wrapper of the exception to handle.</param>
                public void ExceptionalHandler(Error e)
                {
                    var cmd = e.AddCommand(new Command("Redis"));
                    foreach (string k in e.Exception.Data.Keys) // can also use `this`
                    {
                        var val = e.Exception.Data[k] as string;
                        if (k == "redis-command") cmd.CommandString = val;
                        if (k.StartsWith("Redis-")) cmd.AddData(k.Substring("Redis-".Length), val);
                    }
                }
            }
#pragma warning restore RCS1194 // Implement exception constructors.
        }
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _promise;

function _load_promise() {
  return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}

var _asyncToGenerator2;

function _load_asyncToGenerator() {
  return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}

var _errors;

function _load_errors() {
  return _errors = require('../errors.js');
}

var _baseFetcher;

function _load_baseFetcher() {
  return _baseFetcher = _interopRequireDefault(require('./base-fetcher.js'));
}

var _git;

function _load_git() {
  return _git = _interopRequireDefault(require('../util/git.js'));
}

var _fs;

function _load_fs() {
  return _fs = _interopRequireWildcard(require('../util/fs.js'));
}

var _crypto;

function _load_crypto() {
  return _crypto = _interopRequireWildcard(require('../util/crypto.js'));
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const tar = require('tar');

const url = require('url');
const path = require('path');
const fs = require('fs');

const invariant = require('invariant');

class GitFetcher extends (_baseFetcher || _load_baseFetcher()).default {
  _fetch() {
    var _url$parse = url.parse(this.reference);

    const protocol = _url$parse.protocol,
          pathname = _url$parse.pathname;

    if (protocol === null && typeof pathname === 'string') {
      return this.fetchFromLocal(pathname);
    } else {
      return this.fetchFromExternal();
    }
  }

  fetchFromLocal(pathname) {
    var _this = this;

    return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
      const ref = _this.reference,
            config = _this.config;

      const offlineMirrorPath = config.getOfflineMirrorPath() || '';
      const localTarball = path.resolve(offlineMirrorPath, ref);
      const reporter = config.reporter;

      if (!(yield (_fs || _load_fs()).exists(localTarball))) {
        throw new (_errors || _load_errors()).MessageError(reporter.lang('tarballNotInNetworkOrCache', ref, localTarball));
      }

      return new (_promise || _load_promise()).default(function (resolve, reject) {
        const untarStream = tar.Extract({ path: _this.dest });

        const hashStream = new (_crypto || _load_crypto()).HashStream();

        const cachedStream = fs.createReadStream(localTarball);
        cachedStream.pipe(hashStream).pipe(untarStream).on('end', function () {
          const expectHash = _this.hash;
          const actualHash = hashStream.getHash();
          if (!expectHash || expectHash === actualHash) {
            resolve({
              hash: actualHash,
              resolved: `${pathname}#${actualHash}`
            });
          } else {
            reject(new (_errors || _load_errors()).SecurityError(reporter.lang('fetchBadHash', expectHash, actualHash)));
          }
        }).on('error', function (err) {
          reject(new (_errors || _load_errors()).MessageError(reporter.lang('fetchErrorCorrupt', err.message, localTarball)));
        });
      });
    })();
  }

  fetchFromExternal() {
    var _this2 = this;

    return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
      const commit = _this2.hash;
      invariant(commit, 'Commit hash required');

      const git = new (_git || _load_git()).default(_this2.config, _this2.reference, commit);
      yield git.init();
      yield git.clone(_this2.dest);

      // Get the tarball filename from the url

      var _url$parse2 = url.parse(_this2.reference);

      const pathname = _url$parse2.pathname;

      let tarballFilename;
      if (pathname == null) {
        tarballFilename = _this2.reference;
      } else {
        tarballFilename = path.basename(pathname);
      }

      let tarballInMirrorPath = _this2.config.getOfflineMirrorPath(tarballFilename);

      const mirrorRootPath = _this2.config.getOfflineMirrorPath();
      if (tarballInMirrorPath && _this2.hash && mirrorRootPath) {
        tarballInMirrorPath = `${tarballInMirrorPath}-${commit}`;
        const hash = yield git.archive(tarballInMirrorPath);
        const relativeMirrorPath = path.relative(mirrorRootPath, tarballInMirrorPath);
        return {
          hash: commit,
          resolved: relativeMirrorPath ? `${relativeMirrorPath}#${hash}` : null
        };
      }

      return {
        hash: commit,
        resolved: null
      };
    })();
  }
}
exports.default = GitFetcher;


text:
package org.fseek.simon.swing.filetree.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
import javax.swing.ImageIcon;
import org.fseek.simon.swing.filetree.interfaces.LinkTreeNode;
import org.fseek.thedeath.os.CachedFileSystemView;
import org.fseek.thedeath.os.util.Debug;
import org.fseek.thedeath.os.util.OSUtil;

/**
 *
 * @author Thedeath<www.fseek.org>
 *
 * Fast (and logical) implementation of retrieving icons for a certain node.
 * It simply works through all added nodes but also supports preferring a node (because it got expanded for example)
 */

public class IconQueue  extends Thread
{
   private static boolean simpleIcons = false;
   private static IconQueue runningThread;
   private static Stack<LinkTreeNode> priorityNodes = new Stack<>();
   private static HashMap<LinkTreeNode, IconEntry> mapCache = new HashMap<>();

   public static synchronized void addEntry(IconEntry entry){
        if(entry == null)return;
        if(runningThread == null){
            runningThread = new IconQueue();
            runningThread.start();
        }
        synchronized(mapCache){
            mapCache.put(entry.getNode(), entry);
            mapCache.notifyAll();
        }
    }

    public static void setSimpleIcons(boolean simpleIcons)
    {
        IconQueue.simpleIcons = simpleIcons;
    }

    public static boolean isSimpleIcons()
    {
        return simpleIcons;
    }

   public static void addPriorityNode(LinkTreeNode node){
       priorityNodes.push(node);
   }

    private LinkTreeNode priorityNode;
    public IconQueue()
    {
        super("IconQueue");
    }

    @Override
    public void run()
    {
        while(true){

            synchronized(mapCache){
                try
                {
                    if(mapCache.size() <= 0){
                    mapCache.wait();
                    }
                } catch (InterruptedException ex)
                {
                    break;
                }
            }
            if(priorityNodes.size() > 0 && priorityNode == null){
                priorityNode = priorityNodes.pop();
            }
            if(priorityNode != null){
                IconEntry get = mapCache.get(priorityNode);
                if(get != null){
                    mapCache.remove(priorityNode);
                    //mapCache.remove(priorityNode);
                    priorityNode = null;
                    doIt(get);
                    continue;
                }else{
                    //if the node can't be found in the cache just ignore it (seems a logical bug then)
                    //priorityNodes.add(0, priorityNode);
                    priorityNode = null;
                    continue;
                }
            }
            IconEntry poll;
            synchronized(mapCache){
                Iterator<Map.Entry<LinkTreeNode, IconEntry>> iterator = mapCache.entrySet().iterator();
                poll = iterator.next().getValue();
                iterator.remove();
            }
            if(doIt(poll) == false){
                continue;
            }
        }
    }

    private boolean doIt(IconEntry entry){
        if(entry == null || entry.getFile() == null || entry.getNode() == null){
            return false;
        }
        CachedFileSystemView fileSystemView = OSUtil.getFileSystemView();
        ImageIcon icon = simpleIcons? fileSystemView.getSimpleIcon(entry.getFile()):fileSystemView.getSystemIcon(entry.getFile(), false);
        if(icon == null){
            //should normally not happen
            Debug.println("Something strange happened");
            return false;
        }
        entry.getNode().setIcon(icon);
        return true;
    }
}


text:
class RenamingV2EventsToResearchSessions < ActiveRecord::Migration[4.2]
  def change
    rename_table :v2_event_invitations, :research_sessions
    rename_table :v2_reservations, :invitations
    drop_table :v2_events
    drop_table :v2_time_slots

    add_column :research_sessions, :start_datetime, :datetime
    add_column :research_sessions, :end_datetime, :datetime
    add_column :research_sessions, :sms_description, :string
    add_column :research_sessions, :type, :integer, default: 1

    remove_column :research_sessions, :date
    remove_column :research_sessions, :people_ids
    remove_column :research_sessions, :start_time
    remove_column :research_sessions, :end_time
    remove_column :research_sessions, :v2_event_id
    remove_column :research_sessions, :slot_length

    remove_column :invitations, :time_slot_id
    remove_column :invitations, :event_id
    remove_column :invitations, :user_id

    rename_column :invitations, :event_invitation_id, :research_session_id
  end
end


text:
using System;
using UnityEngine;
using CotcSdk;
using System.Reflection;
using IntegrationTests;
using System.Collections;

public class GamerTests : TestBase {

	private const string BoBatchConfiguration = "Needs a set up batch to work (please check for the related test function's comment in code).";
	private const string BoHookConfiguration = "Needs a set up hook to work (please check for the related test function's comment in code).";

	[Test("Sets a property and checks that it worked properly (tests read all & write single).")]
	public IEnumerator ShouldSetProperty() {
		Login(cloud, gamer => {
			// Set property, then get all and check it
			gamer.Properties.SetKey(
				key: "testkey",
				value: "value")
			.ExpectSuccess(setResult => {
				Assert(setResult["done"] == 1, "Expected done = 1");

				return gamer.Properties.GetAll();
			})
			.ExpectSuccess(getResult => {
                Assert(getResult.Has("testkey"), "Previously set key is missing");
                Assert(getResult["testkey"] == "value", "Previously set key contains a wrong value");

                CompleteTest();
			});
		});
        return WaitForEndOfTest();
	}

	[Test("Sets properties and checks them (tests read all & write all).")]
	public IEnumerator ShouldSetMultipleProperties() {
		Login(cloud, gamer => {
			Bundle props = Bundle.CreateObject();
			props["hello"] = "world";
			props["array"] = Bundle.CreateArray(1, 2, 3);

			// Set property, then get all and check it
			gamer.Properties.SetAll(props)
			.ExpectSuccess(setResult => {
				Assert(setResult["done"] == 1, "Expected done = 1");

				gamer.Properties.GetAll()
				.ExpectSuccess(getResult => {
					Assert(getResult["hello"] == "world", "Should contain hello: world key");
					Assert(getResult["array"].AsArray().Count == 3, "Should have a 3-item array");
					Assert(getResult["array"].AsArray()[0] == 1
					    && getResult["array"].AsArray()[1] == 2
                        && getResult["array"].AsArray()[2] == 3, "Content of array invalid");
					CompleteTest();
				});
			});
		});
        return WaitForEndOfTest();
	}

	[Test("Tests removal of a single property (tests remove single & read single).")]
	public IEnumerator ShouldRemoveProperty() {
		Login(cloud, gamer => {
			Bundle props = Bundle.CreateObject();
			props["hello"] = "world";
			props["prop2"] = 123;
			// Set properties, remove one, then get it and check
			gamer.Properties.SetAll(props)
			.ExpectSuccess(setResult => {
				gamer.Properties.RemoveKey("hello")
				.ExpectSuccess(removeResult => {
					// Should not find anymore
					gamer.Properties.GetKey("hello")
					.ExpectSuccess(getResult => {
						Assert(getResult.IsEmpty, "The key should be empty");
						CompleteTest();
					});
				});
			});
		});
        return WaitForEndOfTest();
	}

	[Test("Tests removal of all properties.")]
	public IEnumerator ShouldRemoveAllProperties() {
		Login(cloud, gamer => {
			Bundle props = Bundle.CreateObject();
			props["hello"] = "world";
			props["prop2"] = 123;
			// Set properties, remove them, then get all and check it
			gamer.Properties.SetAll(props)
			.ExpectSuccess(setResult => {

				gamer.Properties.RemoveAll()
				.ExpectSuccess(removeResult => {

					gamer.Properties.GetAll()
					.ExpectSuccess(getResult => {
						Assert(getResult.IsEmpty, "Expected no properties");
						CompleteTest();
					});
				});
			});
		});
        return WaitForEndOfTest();
	}

	[Test("Fetches and updates profile information about a gamer, testing that the GamerProfile methods work as expected.")]
	public IEnumerator ShouldUpdateProfile() {
		Login(cloud, gamer => {
			gamer.Profile.Get()
			.ExpectSuccess(profile => {
				Assert(profile["email"] == "cloud@localhost.localdomain", "Invalid e-mail address (verify Login method in TestBase)");
				Assert(profile["lang"] == "en", "Default language should be english");

                gamer.Profile.Set(Bundle.CreateObject("displayName", "QA", "firstName", "Tester"))
                .ExpectSuccess(setProfile => {
                    Assert(setProfile == true, "Update profile expected to return true");

                    return gamer.Profile.Get();
                })
                // Ensure that the profile have been updated
                .ExpectSuccess(profile2 => {
                    Assert(profile2["displayName"] == "QA", "Display name has not been updated");
                    Assert(profile2["firstName"] == "Tester", "First name has not been updated");
                    CompleteTest();
                });
			});
		});
        return WaitForEndOfTest();
	}

	[Test("Runs a batch on the server and checks the return value.", requisite: BoBatchConfiguration)]
	/*
		Backend prerequisites >> Add the following "unitTest_testGamer" batch:

		function __unitTest_testGamer(params, customData, mod) {
			"use strict";
			// don't edit above this line // must be on line 3
			// Used for unit test.
			return this.user.profile.read(params.user_id).then(function (result) {
		    	return {message: params.request.prefix + result.profile.email};
			});
		} // must be on last line, no CR
	*/
	public IEnumerator ShouldRunGamerBatch() {
		Login(cloud, gamer => {
			gamer.Batches.Run("unitTest_testGamer", Bundle.CreateObject("prefix", "Hello "))
			.ExpectSuccess(batchResult => {
				Assert(batchResult["message"] == "Hello cloud@localhost.localdomain", "Returned value invalid (" + batchResult["message"] + ", check hook on server");
				CompleteTest();
			});
		});
        return WaitForEndOfTest();
	}

	[Test("Creates a match, and checks that the request has been hooked by looking for a new field in the data returned", requisite: BoHookConfiguration)]
	/*
		Backend prerequisites >> Add the following "after-match-create" hook:

		function after-match-create(params, customData, mod) {
			"use strict";
			// don't edit above this line // must be on line 3
			// Used for unit test.
		    params.match.globalState = {hooked:true};
		} // must be on last line, no CR
	*/
    public IEnumerator ShouldBeHooked() {
        LoginNewUser(cloud, gamer => {
            gamer.Matches.Create(1)
            .ExpectSuccess(match => {
                Assert(match.GlobalState["hooked"].AsBool(), "Expected a field 'hooked:true' in the globalState");
                CompleteTest();
            });
        });
        return WaitForEndOfTest();
    }

	[Test("Tests the outline functionality")]
	public IEnumerator ShouldReturnProperOutline() {
		Login(cloud, gamer => {
			gamer.Profile.Outline()
			.ExpectSuccess(outline => {
				Assert(outline.Network.Describe() == gamer.Network, "Expected same network");
				Assert(outline.NetworkId == gamer.NetworkId, "Expected same network ID");
				Assert(outline["games"].Type == Bundle.DataType.Array, "Expected games array");
				CompleteTest();
			});
		});
        return WaitForEndOfTest();
	}
}